-
Notifications
You must be signed in to change notification settings - Fork 6
/
heal.cpp
1399 lines (1165 loc) · 45.6 KB
/
heal.cpp
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
// Heal is a lightweight C++ framework to aid and debug applications.
// - rlyeh, zlib/libpng licensed // ~listening to Kalas - Monuments to Ruins
// Callstack code is based on code by Magnus Norddahl (See http://goo.gl/LM5JB)
// Mem/CPU OS code is based on code by David Robert Nadeau (See http://goo.gl/8P5Jqv)
// Distributed under Creative Commons Attribution 3.0 Unported License
// http://creativecommons.org/licenses/by/3.0/deed.en_US
// A few tweaks before loading STL on MSVC
// This improves stack unwinding.
#ifdef _SECURE_SCL
#undef _SECURE_SCL
#endif
#define _SECURE_SCL 0
#ifdef _ITERATOR_DEBUG_LEVEL
#undef _ITERATOR_DEBUG_LEVEL
#define _ITERATOR_DEBUG_LEVEL 1
#endif
//#define _HAS_ITERATOR_DEBUGGING 0
// Standard headers
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
// System headers
#ifdef _WIN32
//# define UNICODE
//# define _UNICODE
# include <winsock2.h>
# include <ws2tcpip.h>
# include <windows.h>
# include <commctrl.h>
# pragma comment(lib, "comctl32.lib")
# if defined _M_IX86
# pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
# elif defined _M_IA64
# pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
# elif defined _M_X64
# pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
# else
# pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
# endif
# // unwinding
# if defined(DEBUG) || defined(_DEBUG)
# include <CrtDbg.h>
# endif
# include <DbgHelp.h>
# pragma comment(lib, "dbghelp.lib")
# ifndef TD_SHIELD_ICON
# define TD_SHIELD_ICON MAKEINTRESOURCEW(-4)
# endif
#else
# include <unistd.h>
# include <signal.h>
# include <sys/time.h>
# include <sys/types.h>
// --
# if defined(HAVE_SYS_SYSCTL_H) && \
!defined(_SC_NPROCESSORS_ONLN) && !defined(_SC_NPROC_ONLN)
# include <sys/param.h>
# include <sys/sysctl.h>
# endif
// --
# include <execinfo.h>
// --
# include <cxxabi.h>
#endif
#ifdef __MINGW32__
#define backtrace(a,b) 0
#define backtrace_symbols(a,b) 0
#endif
// API
#include "heal.hpp"
namespace heal {
// sfstring is a safe string replacement that does not rely on stringstream
// this is actually safer on corner cases, like crashes, exception unwinding and in exit conditions
class sfstring : public std::string
{
public:
// basic constructors
sfstring() : std::string()
{}
template<size_t N>
sfstring( const char (&cstr)[N] ) : std::string( cstr )
{}
// constructor sugars
#if 0
// version that may crash on /MT on destructors
// (just because it depends on std::locale which may be deinitialized before crashing code)
template <typename T>
/* explicit */ sfstring( const T &t ) : std::string()
{
std::stringstream ss;
ss.precision( std::numeric_limits< long double >::digits10 + 1 );
if( ss << t )
this->assign( ss.str() );
}
#else
template<typename T>
sfstring( const T &t ) : std::string( std::string(t) )
{}
sfstring( const std::string &t ) : std::string( t )
{}
sfstring( const int &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%d", t ) > 0 ) this->assign(buf);
}
sfstring( const uint16_t &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%" SCNu16, t ) > 0 ) this->assign(buf);
}
sfstring( const uint32_t &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%" SCNu32, t ) > 0 ) this->assign(buf);
}
sfstring( const uint64_t &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%" SCNu64, t ) > 0 ) this->assign(buf);
}
sfstring( const float &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%f", t ) > 0 ) this->assign(buf);
}
sfstring( const double &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%lf", t ) > 0 ) this->assign(buf);
}
$msvc(
sfstring( const DWORD &t ) : std::string() {
char buf[128];
if( sprintf(buf, "%" SCNu32, t ) > 0 ) this->assign(buf);
}
)
sfstring( char *t ) : std::string( t ? t : "" )
{}
sfstring( const char *t ) : std::string( t ? t : "" )
{}
sfstring( void *t ) : std::string() {
char buf[128];
if( sprintf(buf, "%p", t ) > 0 ) this->assign(buf);
}
sfstring( const void *t ) : std::string() {
char buf[128];
if( sprintf(buf, "%p", t ) > 0 ) this->assign(buf);
}
#endif
// extended constructors; safe formatting
private:
template<unsigned N>
std::string &safefmt( const std::string &fmt, std::string (&t)[N] ) {
for( std::string::const_iterator it = fmt.begin(), end = fmt.end(); it != end; ++it ) {
unsigned index(*it);
if( index <= N ) t[0] += t[index];
else t[0] += *it;
}
return t[0];
}
public:
template< typename T1 >
sfstring( const std::string &fmt, const T1 &t1 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1) };
assign( safefmt( fmt, t ) );
}
template< typename T1, typename T2 >
sfstring( const std::string &fmt, const T1 &t1, const T2 &t2 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1), sfstring(t2) };
assign( safefmt( fmt, t ) );
}
template< typename T1, typename T2, typename T3 >
sfstring( const std::string &fmt, const T1 &t1, const T2 &t2, const T3 &t3 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1), sfstring(t2), sfstring(t3) };
assign( safefmt( fmt, t ) );
}
template< typename T1, typename T2, typename T3, typename T4 >
sfstring( const std::string &fmt, const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1), sfstring(t2), sfstring(t3), sfstring(t4) };
assign( safefmt( fmt, t ) );
}
template< typename T1, typename T2, typename T3, typename T4, typename T5 >
sfstring( const std::string &fmt, const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1), sfstring(t2), sfstring(t3), sfstring(t4), sfstring(t5) };
assign( safefmt( fmt, t ) );
}
template< typename T1, typename T2, typename T3, typename T4, typename T5, typename T6 >
sfstring( const std::string &fmt, const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1), sfstring(t2), sfstring(t3), sfstring(t4), sfstring(t5), sfstring(t6) };
assign( safefmt( fmt, t ) );
}
template< typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7 >
sfstring( const std::string &fmt, const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6, const T7 &t7 ) : std::string() {
std::string t[] = { std::string(), sfstring(t1), sfstring(t2), sfstring(t3), sfstring(t4), sfstring(t5), sfstring(t6), sfstring(t7) };
assign( safefmt( fmt, t ) );
}
// chaining operators
template< typename T >
sfstring &operator +=( const T &t ) {
return append( sfstring(t) ), *this;
}
template< typename T >
sfstring &operator <<( const T &t ) {
return append( sfstring(t) ), *this;
}
sfstring &operator <<( std::ostream &( *pf )(std::ostream &) ) {
return *pf == static_cast<std::ostream& ( * )(std::ostream&)>( std::endl ) ? (*this) += "\n", *this : *this;
}
// assignment sugars
template< typename T >
sfstring& operator=( const T &t ) {
if( &t != this ) {
*this = sfstring(t);
}
return *this;
}
sfstring &operator=( const char *t ) {
return assign( t ? t : "" ), *this;
}
std::string str() const {
return *this;
}
size_t count( const std::string &substr ) const {
size_t n = 0;
std::string::size_type pos = 0;
while( (pos = this->find( substr, pos )) != std::string::npos ) {
n++;
pos += substr.size();
}
return n;
}
sfstring replace( const std::string &target, const std::string &replacement ) const {
size_t found = 0;
sfstring s = *this;
while( ( found = s.find( target, found ) ) != std::string::npos ) {
s.std::string::replace( found, target.length(), replacement );
found += replacement.length();
}
return s;
}
};
class sfstrings : public std::deque< sfstring >
{
public:
sfstrings( unsigned size = 0 ) : std::deque< sfstring >( size )
{}
template <typename CONTAINER>
sfstrings( const CONTAINER &c ) : std::deque< sfstring >( c.begin(), c.end() )
{}
template <typename CONTAINER>
sfstrings &operator =( const CONTAINER &c ) {
if( &c != this ) {
*this = sfstrings( c );
}
return *this;
}
sfstring str( const char *format1 = "\1\n" ) const {
if( this->size() == 1 )
return *this->begin();
sfstring out;
for( const_iterator it = this->begin(); it != this->end(); ++it )
out += sfstring( format1, (*it) );
return out;
}
sfstring flat() const {
return str( "\1" );
}
};
}
// INFO MESSAGES
// Reminders for retrieving symbols
/*
# if $on($msvc)
$warning( "<heal/heal.cpp> says: do not forget /Zi, /Z7 or /C7 compiler settings! /Oy- also helps!" )
#elif $on($clang)
$warning( "<heal/heal.cpp> says: do not forget -g compiler setting!" )
#elif $on($gnuc)
$warning( "<heal/heal.cpp> says: do not forget -g -lpthread compiler settings!" )
#endif
*/
// ASSERT
namespace heal {
std::vector< heal_callback_in > warns(1);
std::vector< heal_callback_in > fails(1);
namespace {
bool default_warn( const std::string &text ) {
if( text.size() ) {
alert( text, "Warning" );
}
return true;
}
bool default_fail( const std::string &text ) {
if( text.size() ) {
errorbox( text, "Error" );
}
if( !debugger() ) {
alert( "Could not launch debugger" );
}
return true;
}
const bool init_warns = (warns[0] = default_warn, true);
const bool init_fails = (fails[0] = default_fail, true);
}
void warn( const std::string &error ) {
static bool recursive = false;
if( !recursive ) {
recursive = true;
for( unsigned i = warns.size(); i--; ) {
if( warns[i] ) if( warns[i]( error ) ) break;
}
recursive = false;
}
}
void fail( const std::string &error ) {
static bool recursive = false;
if( !recursive ) {
recursive = true;
for( unsigned i = fails.size(); i--; ) {
if( fails[i] ) if( fails[i]( error ) ) break;
}
recursive = false;
}
}
bool is_asserting() {
bool asserting = false;
assert( asserting |= true );
return asserting;
}
// IS_DEBUG
// IS_RELEASE
bool is_debug() {
return $debug(true) $release(false);
}
bool is_release() {
return !is_debug();
}
bool is_devel() {
return $devel(true) $public(false);
}
bool is_public() {
return !is_devel();
}
// DEBUGGER
#if $on($linux) || $on($apple)
// enable core dumps for debug builds
// after a crash try to do something like 'gdb ./a.out core'
# if defined(NDEBUG) || defined(_NDEBUG)
const bool are_coredumps_enabled = false;
# else
# include <sys/resource.h>
rlimit core_limit = { RLIM_INFINITY, RLIM_INFINITY };
const bool are_coredumps_enabled = setrlimit( RLIMIT_CORE, &core_limit ) == 0;
# endif
struct file {
static bool exists( const std::string &pathfile) {
/*struct stat buffer;
return stat( pathfile.c_str(), &buffer ) == 0; */
return access( pathfile.c_str(), F_OK ) != -1; // _access(fn,0) on win
}
};
bool has( const std::string &app ) {
return file::exists( std::string("/usr/bin/") + app );
}
std::string pipe( const std::string &sys, const std::string &sys2 = std::string() ) {
char buf[512];
std::string out;
FILE *fp = popen( (sys+sys2).c_str(), "r" );
if( fp ) {
while( !std::feof(fp) ) {
if( std::fgets(buf,sizeof(buf),fp) != NULL ) {
out += buf;
}
}
pclose(fp);
}
return out;
}
// gdb apparently opens FD(s) 3,4,5 (whereas a typical prog uses only stdin=0, stdout=1,stderr=2)
// Silviocesare and xorl
bool detect_gdb(void)
{
bool rc = false;
FILE *fd = fopen("/tmp", "r");
if( fileno(fd) > 5 )
rc = true;
fclose(fd);
return rc;
}
#endif
void breakpoint() {
// os based
$windows(
DebugBreak();
)
$linux(
raise(SIGTRAP);
// asm("trap");
// asm("int3");
// kill( getpid(), SIGINT );
/*
kill( getpid(), SIGSTOP );
kill( getpid(), SIGTERM );
kill( getpid(), SIGHUP );
kill( getpid(), SIGTRAP );
*/
// kill( getpid(), SIGSEGV );
// raise(SIGTRAP); //POSIX
// raise(SIGINT); //POSIX
)
$apple(
raise(SIGTRAP);
)
// compiler based
//msvc
$msvc(
// "With native code, I prefer using int 3 vs DebugBreak, because the int 3 occurs right in the same stack frame and module as the code in question, whereas DebugBreak occurs one level down in another DLL, as shown in this callstack:"
// [ref] http://blogs.msdn.com/b/calvin_hsia/archive/2006/08/25/724572.aspx
// __debugbreak();
)
// gnuc
$gnuc(
//__builtin_trap();
//__asm__ __volatile__("int3");
)
// standard
//abort();
//assert( !"<heal/heal.cpp> says: debugger() has been requested" );
// still here? duh, maybe we are in release mode...
// host based
//macosx: asm {trap} ; Halts a program running on PPC32 or PPC64.
//macosx: __asm {int 3} ; Halts a program running on IA-32.
//$x86( // ifdef _M_X86
//__asm int 3;
//)
}
bool debugger( const std::string &reason )
{
if( reason.size() > 0 )
errorbox( reason );
// os based
$windows(
if( IsDebuggerPresent() ) {
return breakpoint(), true;
}
)
$linux(
if( detect_gdb() ) {
return breakpoint(), true;
}
// else try to invoke && attach to current process
static std::string sys, tmpfile;
sys = ( has("ddd") && false ? "/usr/bin/ddd" : ( has("gdb") ? "/usr/bin/gdb" : "" ));
tmpfile = "./heal.tmp.tmp"; //get_pipe("tempfile");
if( !sys.empty() ) {
std::string pid = std::to_string( getpid() );
// [ok]
// eval-command=bt
// -ex "bt full"
// gdb --batch --quiet -ex "thread apply all bt full" -ex "quit" ${exe} ${corefile}
sys = sys + (" --tui -q -ex 'set pagination off' -ex 'shell rm " +tmpfile+ "' -ex 'continue' -ex 'finish' -ex 'finish' -ex 'finish' --pid=") + pid + " --args `cat /proc/" + pid + "/cmdline`";
if( has("xterm") && false ) {
sys = std::string("/usr/bin/xterm 2>/dev/null -maximized -e \"") + sys + "\"";
} else {
//sys = std::string(/*"exec"*/ "/usr/bin/splitvt -upper \"") + sys + "\"";
//sys = std::string("/bin/bash -c \"") + sys + " && /usr/bin/reset\"";
sys = std::string("/bin/bash -c \"") + sys + "\"";
}
pipe( "echo heal.cpp says: waiting for debugger to catch pid > ", tmpfile );
std::thread( system, sys.c_str() ).detach();
while( file::exists(tmpfile) )
usleep( 250000 );
return true;
}
)
//errorbox( "<heal/heal.cpp> says:\n\nDebugger invokation failed.\nPlease attach a debugger now.", "Error!");
return false;
}
// ERRORBOX
namespace {
template<typename T>
std::string to_string( const T &t, int digits = 20 ) {
std::stringstream ss;
ss.precision( digits );
ss << std::fixed << t;
return ss.str();
}
template<>
std::string to_string( const bool &boolean, int digits ) {
return boolean ? "true" : "false";
}
template<>
std::string to_string( const std::istream &is, int digits ) {
std::stringstream ss;
std::streamsize at = is.rdbuf()->pubseekoff(0,is.cur);
ss << is.rdbuf();
is.rdbuf()->pubseekpos(at);
return ss.str();
}
void show( const std::string &body = std::string(), const std::string &head = std::string(), const std::string &title = std::string(), bool is_error = false ) {
std::string headtitle = ( head.size() > 0 ? head + ": " + title : title );
std::string headtitlebody = ( headtitle.size() > 0 ? headtitle + ": " + body : body );
$windows(
$no(
int nButton;
auto icon = is_error ? TD_ERROR_ICON : TD_WARNING_ICON;
// TD_INFORMATION_ICON, TD_SHIELD_ICON
std::wstring wbody( body.begin(), body.end() );
std::wstring whead( head.begin(), head.end() );
std::wstring wtitle( title.begin(), title.end() );
HWND hWnd = ::GetActiveWindow(); // force modal
TaskDialog(hWnd, NULL, wtitle.c_str(), whead.c_str(), wbody.c_str(), TDCBF_OK_BUTTON, icon, &nButton );
)
$yes(
MessageBoxA( 0, body.c_str(), head.size() ? head.c_str() : "", 0 | ( is_error ? MB_ICONERROR : 0 ) | MB_SYSTEMMODAL );
)
return;
)
$linux(
if( has("whiptail") ) {
// gtkdialog3
// xmessage -file ~/.bashrc -buttons "Ok:1, Cancel:2, Help:3" -print -nearmouse
//std::string cmd = std::string("/usr/bin/zenity --information --text \"") + body + std::string("\" --title=\"") + headtitle + "\"";
//std::string cmd = std::string("/usr/bin/dialog --title \"") + headtitle + std::string("\" --msgbox \"") + body + "\" 0 0";
std::string cmd = std::string("/usr/bin/whiptail --title \"") + headtitle + std::string("\" --msgbox \"") + body + "\" 0 0";
//std::string cmd = std::string("/usr/bin/xmessage \"") + headtitle + body + "\"";
std::system( cmd.c_str() );
return;
}
)
// fallback
std::string s;
fprintf( stderr, "%s\n", headtitlebody.c_str() );
std::cout << "Press enter to continue..." << std::endl;
std::getline( std::cin, s );
}
}
void alert( ) { show(); }
void alert( const char *text, const std::string &title ) { show( text, title ); }
void alert( const std::string &text, const std::string &title ) { show( text, title ); }
void alert( const std::istream &text, const std::string &title ) { show( to_string(text), title ); }
void alert( const size_t &text, const std::string &title ) { show( to_string(text), title ); }
void alert( const double &text, const std::string &title ) { show( to_string(text), title ); }
void alert( const float &text, const std::string &title ) { show( to_string(text), title ); }
void alert( const int &text, const std::string &title ) { show( to_string(text), title ); }
void alert( const char &text, const std::string &title ) { show( to_string(text), title ); }
void alert( const bool &text, const std::string &title ) { show( to_string(text), title ); }
void errorbox( const std::string &body, const std::string &title ) { show( body, title, "", true ); }
// DEMANGLE
#if 1
# // Disable optimizations. Nothing gets inlined. You get pleasant stacktraces to work with.
# // This is the default setting.
# ifdef _MSC_VER
# pragma optimize( "gsy", off ) // disable optimizations on msvc
# else
# pragma OPTIMIZE OFF // disable optimizations on gcc 4.4+
# endif
#else
# // Enable optimizations. HEAL performs better. However, functions get inlined (specially new/delete operators).
# // This behaviour is disabled by default, since you may get wrong stacktraces.
# ifdef _MSC_VER
# pragma optimize( "gsy", on ) // enable optimizations on msvc
# else
# pragma GCC optimize // enable optimizations on gcc 4.4+
# pragma optimize // enable optimizations on a few other compilers, hopefully
# endif
#endif
std::string demangle( const std::string &mangled ) {
$apple({
std::stringstream ss;
if( !(ss << mangled) )
return mangled;
std::string number, filename, address, funcname, plus, offset;
if( !(ss >> number >> filename >> address >> funcname >> plus >> offset) )
return mangled;
int status = 0;
char *demangled = abi::__cxa_demangle(funcname.c_str(), NULL, NULL, &status);
heal::sfstring out;
if( status == 0 && demangled ) {
out = std::string() + demangled + " ([" + filename + "]:" + offset + ")";
} else {
out = std::string() + funcname + " ([" + filename + "]:" + offset + ")";
}
if( demangled ) free( demangled );
return out;
})
$linux({
$no( /* c++filt way */
FILE *fp = popen( (std::string("echo -n \"") + mangled + std::string("\" | c++filt" )).c_str(), "r" );
if (!fp) { return mangled; }
char demangled[1024];
char *line_p = fgets(demangled, sizeof(demangled), fp);
pclose(fp);
return demangled;
)
$yes( /* addr2line way. wip & quick proof-of-concept. clean up required. */
heal::sfstring binary = mangled.substr( 0, mangled.find_first_of('(') );
heal::sfstring address = mangled.substr( mangled.find_last_of('[') + 1 );
address.pop_back();
heal::sfstring cmd( "addr2line -e \1 \2", binary, address );
FILE *fp = popen( cmd.c_str(), "r" );
if (!fp) { return mangled; }
char demangled[1024];
char *line_p = fgets(demangled, sizeof(demangled), fp);
pclose(fp);
heal::sfstring demangled_(demangled);
if( demangled_.size() ) demangled_.pop_back(); //remove \n
return demangled_.size() && demangled_.at(0) == '?' ? mangled : demangled_;
)
})
$windows({
char demangled[1024];
return (UnDecorateSymbolName(mangled.c_str(), demangled, sizeof( demangled ), UNDNAME_COMPLETE)) ? std::string(demangled) : mangled;
})
/*
$gnuc({
std::string out;
int status = 0;
char *demangled = abi::__cxa_demangle(mangled.c_str(), 0, 0, &status);
out = ( status == 0 && demangled ? std::string(demangled) : mangled );
if( demangled ) free( demangled );
return out;
})
*/
return mangled;
}
// CALLSTACK
callstack::callstack( bool autosave ) {
if( autosave ) save();
}
size_t callstack::space() const {
return sizeof(frames) + sizeof(void *) * frames.size();
}
void callstack::save( unsigned frames_to_skip ) {
if( frames_to_skip > max_frames )
return;
frames.clear();
frames.resize( max_frames, (void *)0 );
void **out_frames = &frames[0]; // .data();
$windows({
unsigned short capturedFrames = 0;
// RtlCaptureStackBackTrace is only available on Windows XP or newer versions of Windows
typedef WORD(NTAPI FuncRtlCaptureStackBackTrace)(DWORD, DWORD, PVOID *, PDWORD);
static struct raii
{
raii() : module(0), ptrRtlCaptureStackBackTrace(0)
{
module = LoadLibraryA("kernel32.dll");
if( !module )
fail( "<heal/heal.cpp> says: error! cant load kernel32.dll" );
ptrRtlCaptureStackBackTrace = (FuncRtlCaptureStackBackTrace *)GetProcAddress(module, "RtlCaptureStackBackTrace");
if( !ptrRtlCaptureStackBackTrace )
fail( "<heal/heal.cpp> says: error! cant find RtlCaptureStackBackTrace() process address" );
}
~raii() { if(module) FreeLibrary(module); }
HMODULE module;
FuncRtlCaptureStackBackTrace *ptrRtlCaptureStackBackTrace;
} module;
if( module.ptrRtlCaptureStackBackTrace )
capturedFrames = module.ptrRtlCaptureStackBackTrace(frames_to_skip+1, max_frames, out_frames, (DWORD *) 0);
frames.resize( capturedFrames );
std::vector<void *>(frames).swap(frames);
return;
})
$gnuc({
// Ensure the output is cleared
std::memset(out_frames, 0, (sizeof(void *)) * max_frames);
frames.resize( backtrace(out_frames, max_frames) );
std::vector<void *>(frames).swap(frames);
return;
})
}
std::vector<std::string> callstack::unwind( unsigned from, unsigned to ) const
{
if( to == ~0 )
to = this->frames.size();
if( from > to || from > this->frames.size() || to > this->frames.size() )
return std::vector<std::string>();
const size_t num_frames = to - from;
std::vector<std::string> backtraces( num_frames );
void * const * frames = &this->frames[ from ];
const std::string invalid = "????";
$windows({
SymSetOptions(SYMOPT_UNDNAME);
$no(
// polite version. this is how things should be done.
HANDLE process = GetCurrentProcess();
if( SymInitialize( process, NULL, TRUE ) )
)
$yes(
// this is what we have to do because other memory managers are not polite enough. fuck them off
static HANDLE process = GetCurrentProcess();
static int init = SymInitialize( process, NULL, TRUE );
if( !init )
fail( "<heal/heal.cpp> says: cannot initialize Dbghelp.lib" );
)
{
enum { MAXSYMBOLNAME = 512 - sizeof(IMAGEHLP_SYMBOL64) };
char symbol64_buf [ 512 ];
char symbol64_bufblank[ 512 ] = {0};
IMAGEHLP_SYMBOL64 *symbol64 = reinterpret_cast<IMAGEHLP_SYMBOL64*>(symbol64_buf);
IMAGEHLP_SYMBOL64 *symbol64_blank = reinterpret_cast<IMAGEHLP_SYMBOL64*>(symbol64_bufblank);
symbol64_blank->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol64_blank->MaxNameLength = (MAXSYMBOLNAME-1) / 2; //wchar?
IMAGEHLP_LINE64 line64, line64_blank = {0};
line64_blank.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
for( unsigned i = 0; i < num_frames; i++ ) {
*symbol64 = *symbol64_blank;
DWORD64 displacement64 = 0;
if( SymGetSymFromAddr64( process, (DWORD64) frames[i], &displacement64, symbol64 ) ) {
line64 = line64_blank;
DWORD displacement = 0;
if( SymGetLineFromAddr64( process, (DWORD64) frames[i], &displacement, &line64 ) ) {
backtraces[i] = heal::sfstring( "\1 (\2:\3)", symbol64->Name, line64.FileName, line64.LineNumber );
} else {
backtraces[i] = symbol64->Name;
}
} else backtraces[i] = invalid;
}
$no(
// fuck the others. cleanup commented.
SymCleanup(process);
)
}
DWORD error = GetLastError();
return backtraces;
})
$gnuc({
char **strings = backtrace_symbols(frames, num_frames);
// Decode the strings
if( strings ) {
for( unsigned i = 0; i < num_frames; i++ ) {
backtraces[i] = ( strings[i] ? demangle(strings[i]) : invalid );
}
free( strings );
}
return backtraces;
})
return backtraces;
}
std::vector<std::string> callstack::str( const char *format12, size_t skip_begin ) const {
callstack copy = *this;
std::vector<std::string> stacktrace = copy.unwind( skip_begin );
for( size_t i = 0, end = stacktrace.size(); i < end; i++ )
stacktrace[i] = heal::sfstring( format12, i + 1, stacktrace[i] );
return stacktrace;
}
std::string callstack::flat( const char *format12, size_t skip_begin ) const {
std::vector<std::string> vec = str( format12, skip_begin );
std::string str;
for( std::vector<std::string>::const_iterator it = vec.begin(), end = vec.end(); it != end; ++it ) {
str += *it;
}
return str;
}
std::vector<std::string> stacktrace( const char *format12, size_t skip_initial ) {
return callstack(true).str( format12, skip_initial );
}
std::string stackstring( const char *format12, size_t skip_initial ) {
std::string out;
std::vector<std::string> stack = stacktrace( format12, skip_initial );
for( std::vector<std::string>::const_iterator it = stack.begin(), end = stack.end(); it != end; ++it ) {
out += *it;
}
return out;
}
// DIE
void die( const std::string &reason, int errorcode )
{
if( !reason.empty() ) {
fail( reason );
}
$windows(
FatalExit( errorcode );
)
// fallback
std::exit( errorcode );
}
void die( int errorcode, const std::string &reason )
{
die( reason, errorcode );
}
// HEXDUMP
// @todo: maxwidth != 80 doesnt work
std::string hexdump( const void *data, size_t num_bytes, const void *self )
{
# ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable : 4996 )
# define $vsnprintf _vsnprintf
# else
# define $vsnprintf vsnprintf
# endif
struct local {
static std::string format( const char *fmt, ... )
{
int len;
std::string self;
using namespace std;
// Calculate the final length of the formatted string
{
va_list args;
va_start( args, fmt );
len = $vsnprintf( 0, 0, fmt, args );
va_end( args );
}
// Allocate a buffer (including room for null termination
char* target_string = new char[++len];
// Generate the formatted string
{
va_list args;
va_start( args, fmt );
$vsnprintf( target_string, len, fmt, args );
va_end( args );
}
// Assign the formatted string
self.assign( target_string );
// Clean up
delete [] target_string;
return self;
}
};
unsigned maxwidth = 80;
unsigned width = 16; //column width
unsigned width_offset_block = (8 + 1);
unsigned width_chars_block = (width * 3 + 1) + sizeof("asc");
unsigned width_hex_block = (width * 3 + 1) + sizeof("hex");
unsigned width_padding = (std::max)( 0, int( maxwidth - ( width_offset_block + width_chars_block + width_hex_block ) ) );
unsigned blocks = width_padding / ( width_chars_block + width_hex_block ) ;
unsigned dumpsize = ( num_bytes < width * 16 ? num_bytes : width * 16 ); //16 lines max
std::string result;
result += local::format( "%-*s %-.*s [ptr=%p sz=%d]\n", width_offset_block - 1, "offset", width_chars_block - 1, "00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F", self ? self : data, num_bytes );
if( !num_bytes )
return result;
blocks++;
const unsigned char *p = reinterpret_cast<const unsigned char *>( data );
size_t i = 0;