forked from GoSSIP-SJTU/Armariris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExceptionDemo.cpp
2036 lines (1685 loc) · 70.3 KB
/
ExceptionDemo.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
//===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Demo program which implements an example LLVM exception implementation, and
// shows several test cases including the handling of foreign exceptions.
// It is run with type info types arguments to throw. A test will
// be run for each given type info type. While type info types with the value
// of -1 will trigger a foreign C++ exception to be thrown; type info types
// <= 6 and >= 1 will cause the associated generated exceptions to be thrown
// and caught by generated test functions; and type info types > 6
// will result in exceptions which pass through to the test harness. All other
// type info types are not supported and could cause a crash. In all cases,
// the "finally" blocks of every generated test functions will executed
// regardless of whether or not that test function ignores or catches the
// thrown exception.
//
// examples:
//
// ExceptionDemo
//
// causes a usage to be printed to stderr
//
// ExceptionDemo 2 3 7 -1
//
// results in the following cases:
// - Value 2 causes an exception with a type info type of 2 to be
// thrown and caught by an inner generated test function.
// - Value 3 causes an exception with a type info type of 3 to be
// thrown and caught by an outer generated test function.
// - Value 7 causes an exception with a type info type of 7 to be
// thrown and NOT be caught by any generated function.
// - Value -1 causes a foreign C++ exception to be thrown and not be
// caught by any generated function
//
// Cases -1 and 7 are caught by a C++ test harness where the validity of
// of a C++ catch(...) clause catching a generated exception with a
// type info type of 7 is explained by: example in rules 1.6.4 in
// http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22)
//
// This code uses code from the llvm compiler-rt project and the llvm
// Kaleidoscope project.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Verifier.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
// FIXME: Although all systems tested with (Linux, OS X), do not need this
// header file included. A user on ubuntu reported, undefined symbols
// for stderr, and fprintf, and the addition of this include fixed the
// issue for them. Given that LLVM's best practices include the goal
// of reducing the number of redundant header files included, the
// correct solution would be to find out why these symbols are not
// defined for the system in question, and fix the issue by finding out
// which LLVM header file, if any, would include these symbols.
#include <cstdio>
#include <sstream>
#include <stdexcept>
#include <inttypes.h>
#ifndef USE_GLOBAL_STR_CONSTS
#define USE_GLOBAL_STR_CONSTS true
#endif
// System C++ ABI unwind types from:
// http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22)
extern "C" {
typedef enum {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8
} _Unwind_Reason_Code;
typedef enum {
_UA_SEARCH_PHASE = 1,
_UA_CLEANUP_PHASE = 2,
_UA_HANDLER_FRAME = 4,
_UA_FORCE_UNWIND = 8,
_UA_END_OF_STACK = 16
} _Unwind_Action;
struct _Unwind_Exception;
typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
struct _Unwind_Exception *);
struct _Unwind_Exception {
uint64_t exception_class;
_Unwind_Exception_Cleanup_Fn exception_cleanup;
uintptr_t private_1;
uintptr_t private_2;
// @@@ The IA-64 ABI says that this structure must be double-word aligned.
// Taking that literally does not make much sense generically. Instead
// we provide the maximum alignment required by any type for the machine.
} __attribute__((__aligned__));
struct _Unwind_Context;
typedef struct _Unwind_Context *_Unwind_Context_t;
extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
} // extern "C"
//
// Example types
//
/// This is our simplistic type info
struct OurExceptionType_t {
/// type info type
int type;
};
/// This is our Exception class which relies on a negative offset to calculate
/// pointers to its instances from pointers to its unwindException member.
///
/// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
/// on a double word boundary. This is necessary to match the standard:
/// http://mentorembedded.github.com/cxx-abi/abi-eh.html
struct OurBaseException_t {
struct OurExceptionType_t type;
// Note: This is properly aligned in unwind.h
struct _Unwind_Exception unwindException;
};
// Note: Not needed since we are C++
typedef struct OurBaseException_t OurException;
typedef struct _Unwind_Exception OurUnwindException;
//
// Various globals used to support typeinfo and generatted exceptions in
// general
//
static std::map<std::string, llvm::Value*> namedValues;
int64_t ourBaseFromUnwindOffset;
const unsigned char ourBaseExcpClassChars[] =
{'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
static uint64_t ourBaseExceptionClass = 0;
static std::vector<std::string> ourTypeInfoNames;
static std::map<int, std::string> ourTypeInfoNamesIndex;
static llvm::StructType *ourTypeInfoType;
static llvm::StructType *ourCaughtResultType;
static llvm::StructType *ourExceptionType;
static llvm::StructType *ourUnwindExceptionType;
static llvm::ConstantInt *ourExceptionNotThrownState;
static llvm::ConstantInt *ourExceptionThrownState;
static llvm::ConstantInt *ourExceptionCaughtState;
typedef std::vector<std::string> ArgNames;
typedef std::vector<llvm::Type*> ArgTypes;
//
// Code Generation Utilities
//
/// Utility used to create a function, both declarations and definitions
/// @param module for module instance
/// @param retType function return type
/// @param theArgTypes function's ordered argument types
/// @param theArgNames function's ordered arguments needed if use of this
/// function corresponds to a function definition. Use empty
/// aggregate for function declarations.
/// @param functName function name
/// @param linkage function linkage
/// @param declarationOnly for function declarations
/// @param isVarArg function uses vararg arguments
/// @returns function instance
llvm::Function *createFunction(llvm::Module &module,
llvm::Type *retType,
const ArgTypes &theArgTypes,
const ArgNames &theArgNames,
const std::string &functName,
llvm::GlobalValue::LinkageTypes linkage,
bool declarationOnly,
bool isVarArg) {
llvm::FunctionType *functType =
llvm::FunctionType::get(retType, theArgTypes, isVarArg);
llvm::Function *ret =
llvm::Function::Create(functType, linkage, functName, &module);
if (!ret || declarationOnly)
return(ret);
namedValues.clear();
unsigned i = 0;
for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
i != theArgNames.size();
++argIndex, ++i) {
argIndex->setName(theArgNames[i]);
namedValues[theArgNames[i]] = argIndex;
}
return(ret);
}
/// Create an alloca instruction in the entry block of
/// the parent function. This is used for mutable variables etc.
/// @param function parent instance
/// @param varName stack variable name
/// @param type stack variable type
/// @param initWith optional constant initialization value
/// @returns AllocaInst instance
static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
const std::string &varName,
llvm::Type *type,
llvm::Constant *initWith = 0) {
llvm::BasicBlock &block = function.getEntryBlock();
llvm::IRBuilder<> tmp(&block, block.begin());
llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
if (initWith)
tmp.CreateStore(initWith, ret);
return(ret);
}
//
// Code Generation Utilities End
//
//
// Runtime C Library functions
//
// Note: using an extern "C" block so that static functions can be used
extern "C" {
// Note: Better ways to decide on bit width
//
/// Prints a 32 bit number, according to the format, to stderr.
/// @param intToPrint integer to print
/// @param format printf like format to use when printing
void print32Int(int intToPrint, const char *format) {
if (format) {
// Note: No NULL check
fprintf(stderr, format, intToPrint);
}
else {
// Note: No NULL check
fprintf(stderr, "::print32Int(...):NULL arg.\n");
}
}
// Note: Better ways to decide on bit width
//
/// Prints a 64 bit number, according to the format, to stderr.
/// @param intToPrint integer to print
/// @param format printf like format to use when printing
void print64Int(long int intToPrint, const char *format) {
if (format) {
// Note: No NULL check
fprintf(stderr, format, intToPrint);
}
else {
// Note: No NULL check
fprintf(stderr, "::print64Int(...):NULL arg.\n");
}
}
/// Prints a C string to stderr
/// @param toPrint string to print
void printStr(char *toPrint) {
if (toPrint) {
fprintf(stderr, "%s", toPrint);
}
else {
fprintf(stderr, "::printStr(...):NULL arg.\n");
}
}
/// Deletes the true previously allocated exception whose address
/// is calculated from the supplied OurBaseException_t::unwindException
/// member address. Handles (ignores), NULL pointers.
/// @param expToDelete exception to delete
void deleteOurException(OurUnwindException *expToDelete) {
#ifdef DEBUG
fprintf(stderr,
"deleteOurException(...).\n");
#endif
if (expToDelete &&
(expToDelete->exception_class == ourBaseExceptionClass)) {
free(((char*) expToDelete) + ourBaseFromUnwindOffset);
}
}
/// This function is the struct _Unwind_Exception API mandated delete function
/// used by foreign exception handlers when deleting our exception
/// (OurException), instances.
/// @param reason See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html
/// @unlink
/// @param expToDelete exception instance to delete
void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
OurUnwindException *expToDelete) {
#ifdef DEBUG
fprintf(stderr,
"deleteFromUnwindOurException(...).\n");
#endif
deleteOurException(expToDelete);
}
/// Creates (allocates on the heap), an exception (OurException instance),
/// of the supplied type info type.
/// @param type type info type
OurUnwindException *createOurException(int type) {
size_t size = sizeof(OurException);
OurException *ret = (OurException*) memset(malloc(size), 0, size);
(ret->type).type = type;
(ret->unwindException).exception_class = ourBaseExceptionClass;
(ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
return(&(ret->unwindException));
}
/// Read a uleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readULEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*data = p;
return result;
}
/// Read a sleb128 encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static uintptr_t readSLEB128(const uint8_t **data) {
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
const uint8_t *p = *data;
do {
byte = *p++;
result |= (byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*data = p;
if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
result |= (~0 << shift);
}
return result;
}
unsigned getEncodingSize(uint8_t Encoding) {
if (Encoding == llvm::dwarf::DW_EH_PE_omit)
return 0;
switch (Encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
return sizeof(uintptr_t);
case llvm::dwarf::DW_EH_PE_udata2:
return sizeof(uint16_t);
case llvm::dwarf::DW_EH_PE_udata4:
return sizeof(uint32_t);
case llvm::dwarf::DW_EH_PE_udata8:
return sizeof(uint64_t);
case llvm::dwarf::DW_EH_PE_sdata2:
return sizeof(int16_t);
case llvm::dwarf::DW_EH_PE_sdata4:
return sizeof(int32_t);
case llvm::dwarf::DW_EH_PE_sdata8:
return sizeof(int64_t);
default:
// not supported
abort();
}
}
/// Read a pointer encoded value and advance pointer
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @param encoding dwarf encoding type
/// @returns decoded value
static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
uintptr_t result = 0;
const uint8_t *p = *data;
if (encoding == llvm::dwarf::DW_EH_PE_omit)
return(result);
// first get value
switch (encoding & 0x0F) {
case llvm::dwarf::DW_EH_PE_absptr:
result = *((uintptr_t*)p);
p += sizeof(uintptr_t);
break;
case llvm::dwarf::DW_EH_PE_uleb128:
result = readULEB128(&p);
break;
// Note: This case has not been tested
case llvm::dwarf::DW_EH_PE_sleb128:
result = readSLEB128(&p);
break;
case llvm::dwarf::DW_EH_PE_udata2:
result = *((uint16_t*)p);
p += sizeof(uint16_t);
break;
case llvm::dwarf::DW_EH_PE_udata4:
result = *((uint32_t*)p);
p += sizeof(uint32_t);
break;
case llvm::dwarf::DW_EH_PE_udata8:
result = *((uint64_t*)p);
p += sizeof(uint64_t);
break;
case llvm::dwarf::DW_EH_PE_sdata2:
result = *((int16_t*)p);
p += sizeof(int16_t);
break;
case llvm::dwarf::DW_EH_PE_sdata4:
result = *((int32_t*)p);
p += sizeof(int32_t);
break;
case llvm::dwarf::DW_EH_PE_sdata8:
result = *((int64_t*)p);
p += sizeof(int64_t);
break;
default:
// not supported
abort();
break;
}
// then add relative offset
switch (encoding & 0x70) {
case llvm::dwarf::DW_EH_PE_absptr:
// do nothing
break;
case llvm::dwarf::DW_EH_PE_pcrel:
result += (uintptr_t)(*data);
break;
case llvm::dwarf::DW_EH_PE_textrel:
case llvm::dwarf::DW_EH_PE_datarel:
case llvm::dwarf::DW_EH_PE_funcrel:
case llvm::dwarf::DW_EH_PE_aligned:
default:
// not supported
abort();
break;
}
// then apply indirection
if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
result = *((uintptr_t*)result);
}
*data = p;
return result;
}
/// Deals with Dwarf actions matching our type infos
/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
/// action matches the supplied exception type. If such a match succeeds,
/// the resultAction argument will be set with > 0 index value. Only
/// corresponding llvm.eh.selector type info arguments, cleanup arguments
/// are supported. Filters are not supported.
/// See Variable Length Data in:
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// Also see @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
/// @param resultAction reference variable which will be set with result
/// @param classInfo our array of type info pointers (to globals)
/// @param actionEntry index into above type info array or 0 (clean up).
/// We do not support filters.
/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
/// of thrown exception.
/// @param exceptionObject thrown _Unwind_Exception instance.
/// @returns whether or not a type info was found. False is returned if only
/// a cleanup was found
static bool handleActionValue(int64_t *resultAction,
uint8_t TTypeEncoding,
const uint8_t *ClassInfo,
uintptr_t actionEntry,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject) {
bool ret = false;
if (!resultAction ||
!exceptionObject ||
(exceptionClass != ourBaseExceptionClass))
return(ret);
struct OurBaseException_t *excp = (struct OurBaseException_t*)
(((char*) exceptionObject) + ourBaseFromUnwindOffset);
struct OurExceptionType_t *excpType = &(excp->type);
int type = excpType->type;
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...): exceptionObject = <%p>, "
"excp = <%p>.\n",
(void*)exceptionObject,
(void*)excp);
#endif
const uint8_t *actionPos = (uint8_t*) actionEntry,
*tempActionPos;
int64_t typeOffset = 0,
actionOffset;
for (int i = 0; true; ++i) {
// Each emitted dwarf action corresponds to a 2 tuple of
// type info address offset, and action offset to the next
// emitted action.
typeOffset = readSLEB128(&actionPos);
tempActionPos = actionPos;
actionOffset = readSLEB128(&tempActionPos);
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):typeOffset: <%" PRIi64 ">, "
"actionOffset: <%" PRIi64 ">.\n",
typeOffset,
actionOffset);
#endif
assert((typeOffset >= 0) &&
"handleActionValue(...):filters are not supported.");
// Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
// argument has been matched.
if (typeOffset > 0) {
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):actionValue <%d> found.\n",
i);
#endif
unsigned EncSize = getEncodingSize(TTypeEncoding);
const uint8_t *EntryP = ClassInfo - typeOffset * EncSize;
uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);
struct OurExceptionType_t *ThisClassInfo =
reinterpret_cast<struct OurExceptionType_t *>(P);
if (ThisClassInfo->type == type) {
*resultAction = i + 1;
ret = true;
break;
}
}
#ifdef DEBUG
fprintf(stderr,
"handleActionValue(...):actionValue not found.\n");
#endif
if (!actionOffset)
break;
actionPos += actionOffset;
}
return(ret);
}
/// Deals with the Language specific data portion of the emitted dwarf code.
/// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
/// @param version unsupported (ignored), unwind version
/// @param lsda language specific data area
/// @param _Unwind_Action actions minimally supported unwind stage
/// (forced specifically not supported)
/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
/// of thrown exception.
/// @param exceptionObject thrown _Unwind_Exception instance.
/// @param context unwind system context
/// @returns minimally supported unwinding control indicator
static _Unwind_Reason_Code handleLsda(int version,
const uint8_t *lsda,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject,
_Unwind_Context_t context) {
_Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
if (!lsda)
return(ret);
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...):lsda is non-zero.\n");
#endif
// Get the current instruction pointer and offset it before next
// instruction in the current frame which threw the exception.
uintptr_t pc = _Unwind_GetIP(context)-1;
// Get beginning current frame's code (as defined by the
// emitted dwarf code)
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t pcOffset = pc - funcStart;
const uint8_t *ClassInfo = NULL;
// Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
// dwarf emission
// Parse LSDA header.
uint8_t lpStartEncoding = *lsda++;
if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
readEncodedPointer(&lsda, lpStartEncoding);
}
uint8_t ttypeEncoding = *lsda++;
uintptr_t classInfoOffset;
if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
// Calculate type info locations in emitted dwarf code which
// were flagged by type info arguments to llvm.eh.selector
// intrinsic
classInfoOffset = readULEB128(&lsda);
ClassInfo = lsda + classInfoOffset;
}
// Walk call-site table looking for range that
// includes current PC.
uint8_t callSiteEncoding = *lsda++;
uint32_t callSiteTableLength = readULEB128(&lsda);
const uint8_t *callSiteTableStart = lsda;
const uint8_t *callSiteTableEnd = callSiteTableStart +
callSiteTableLength;
const uint8_t *actionTableStart = callSiteTableEnd;
const uint8_t *callSitePtr = callSiteTableStart;
while (callSitePtr < callSiteTableEnd) {
uintptr_t start = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t length = readEncodedPointer(&callSitePtr,
callSiteEncoding);
uintptr_t landingPad = readEncodedPointer(&callSitePtr,
callSiteEncoding);
// Note: Action value
uintptr_t actionEntry = readULEB128(&callSitePtr);
if (exceptionClass != ourBaseExceptionClass) {
// We have been notified of a foreign exception being thrown,
// and we therefore need to execute cleanup landing pads
actionEntry = 0;
}
if (landingPad == 0) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): No landing pad found.\n");
#endif
continue; // no landing pad for this entry
}
if (actionEntry) {
actionEntry += ((uintptr_t) actionTableStart) - 1;
}
else {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...):No action table found.\n");
#endif
}
bool exceptionMatched = false;
if ((start <= pcOffset) && (pcOffset < (start + length))) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): Landing pad found.\n");
#endif
int64_t actionValue = 0;
if (actionEntry) {
exceptionMatched = handleActionValue(&actionValue,
ttypeEncoding,
ClassInfo,
actionEntry,
exceptionClass,
exceptionObject);
}
if (!(actions & _UA_SEARCH_PHASE)) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): installed landing pad "
"context.\n");
#endif
// Found landing pad for the PC.
// Set Instruction Pointer to so we re-enter function
// at landing pad. The landing pad is created by the
// compiler to take two parameters in registers.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(0),
(uintptr_t)exceptionObject);
// Note: this virtual register directly corresponds
// to the return of the llvm.eh.selector intrinsic
if (!actionEntry || !exceptionMatched) {
// We indicate cleanup only
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
0);
}
else {
// Matched type info index of llvm.eh.selector intrinsic
// passed here.
_Unwind_SetGR(context,
__builtin_eh_return_data_regno(1),
actionValue);
}
// To execute landing pad set here
_Unwind_SetIP(context, funcStart + landingPad);
ret = _URC_INSTALL_CONTEXT;
}
else if (exceptionMatched) {
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): setting handler found.\n");
#endif
ret = _URC_HANDLER_FOUND;
}
else {
// Note: Only non-clean up handlers are marked as
// found. Otherwise the clean up handlers will be
// re-found and executed during the clean up
// phase.
#ifdef DEBUG
fprintf(stderr,
"handleLsda(...): cleanup handler found.\n");
#endif
}
break;
}
}
return(ret);
}
/// This is the personality function which is embedded (dwarf emitted), in the
/// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
/// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
/// @param version unsupported (ignored), unwind version
/// @param _Unwind_Action actions minimally supported unwind stage
/// (forced specifically not supported)
/// @param exceptionClass exception class (_Unwind_Exception::exception_class)
/// of thrown exception.
/// @param exceptionObject thrown _Unwind_Exception instance.
/// @param context unwind system context
/// @returns minimally supported unwinding control indicator
_Unwind_Reason_Code ourPersonality(int version,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject,
_Unwind_Context_t context) {
#ifdef DEBUG
fprintf(stderr,
"We are in ourPersonality(...):actions is <%d>.\n",
actions);
if (actions & _UA_SEARCH_PHASE) {
fprintf(stderr, "ourPersonality(...):In search phase.\n");
}
else {
fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
}
#endif
const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
#ifdef DEBUG
fprintf(stderr,
"ourPersonality(...):lsda = <%p>.\n",
(void*)lsda);
#endif
// The real work of the personality function is captured here
return(handleLsda(version,
lsda,
actions,
exceptionClass,
exceptionObject,
context));
}
/// Generates our _Unwind_Exception class from a given character array.
/// thereby handling arbitrary lengths (not in standard), and handling
/// embedded \0s.
/// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
/// @param classChars char array to encode. NULL values not checkedf
/// @param classCharsSize number of chars in classChars. Value is not checked.
/// @returns class value
uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
{
uint64_t ret = classChars[0];
for (unsigned i = 1; i < classCharsSize; ++i) {
ret <<= 8;
ret += classChars[i];
}
return(ret);
}
} // extern "C"
//
// Runtime C Library functions End
//
//
// Code generation functions
//
/// Generates code to print given constant string
/// @param context llvm context
/// @param module code for module instance
/// @param builder builder instance
/// @param toPrint string to print
/// @param useGlobal A value of true (default) indicates a GlobalValue is
/// generated, and is used to hold the constant string. A value of
/// false indicates that the constant string will be stored on the
/// stack.
void generateStringPrint(llvm::LLVMContext &context,
llvm::Module &module,
llvm::IRBuilder<> &builder,
std::string toPrint,
bool useGlobal = true) {
llvm::Function *printFunct = module.getFunction("printStr");
llvm::Value *stringVar;
llvm::Constant *stringConstant =
llvm::ConstantDataArray::getString(context, toPrint);
if (useGlobal) {
// Note: Does not work without allocation
stringVar =
new llvm::GlobalVariable(module,
stringConstant->getType(),
true,
llvm::GlobalValue::PrivateLinkage,
stringConstant,
"");
}
else {
stringVar = builder.CreateAlloca(stringConstant->getType());
builder.CreateStore(stringConstant, stringVar);
}
llvm::Value *cast = builder.CreatePointerCast(stringVar,
builder.getInt8PtrTy());
builder.CreateCall(printFunct, cast);
}
/// Generates code to print given runtime integer according to constant
/// string format, and a given print function.
/// @param context llvm context
/// @param module code for module instance
/// @param builder builder instance
/// @param printFunct function used to "print" integer
/// @param toPrint string to print
/// @param format printf like formating string for print
/// @param useGlobal A value of true (default) indicates a GlobalValue is
/// generated, and is used to hold the constant string. A value of
/// false indicates that the constant string will be stored on the
/// stack.
void generateIntegerPrint(llvm::LLVMContext &context,
llvm::Module &module,
llvm::IRBuilder<> &builder,
llvm::Function &printFunct,
llvm::Value &toPrint,
std::string format,
bool useGlobal = true) {
llvm::Constant *stringConstant =
llvm::ConstantDataArray::getString(context, format);
llvm::Value *stringVar;
if (useGlobal) {
// Note: Does not seem to work without allocation
stringVar =
new llvm::GlobalVariable(module,
stringConstant->getType(),
true,
llvm::GlobalValue::PrivateLinkage,
stringConstant,
"");
}
else {
stringVar = builder.CreateAlloca(stringConstant->getType());
builder.CreateStore(stringConstant, stringVar);
}
llvm::Value *cast = builder.CreateBitCast(stringVar,
builder.getInt8PtrTy());
builder.CreateCall(&printFunct, {&toPrint, cast});
}
/// Generates code to handle finally block type semantics: always runs
/// regardless of whether a thrown exception is passing through or the
/// parent function is simply exiting. In addition to printing some state
/// to stderr, this code will resume the exception handling--runs the
/// unwind resume block, if the exception has not been previously caught
/// by a catch clause, and will otherwise execute the end block (terminator
/// block). In addition this function creates the corresponding function's
/// stack storage for the exception pointer and catch flag status.
/// @param context llvm context
/// @param module code for module instance
/// @param builder builder instance
/// @param toAddTo parent function to add block to
/// @param blockName block name of new "finally" block.
/// @param functionId output id used for printing
/// @param terminatorBlock terminator "end" block
/// @param unwindResumeBlock unwind resume block
/// @param exceptionCaughtFlag reference exception caught/thrown status storage
/// @param exceptionStorage reference to exception pointer storage
/// @param caughtResultStorage reference to landingpad result storage
/// @returns newly created block
static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
llvm::Module &module,