Welcome to mirror list, hosted at ThFree Co, Russian Federation.

exception.c « metadata « mono - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: db668d23f65830ad2e6666c864cbcd0489f67ea2 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
/**
 * \file
 * Exception handling
 *
 * Authors:
 *	Paolo Molaro    (lupus@ximian.com)
 *	Dietmar Maurer  (dietmar@ximian.com)
 *	Dick Porter     (dick@ximian.com)
 *      Miguel de Icaza (miguel@ximian.com)
 *
 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
 */

#include <glib.h>
#include <config.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/mono-debug.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <string.h>
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#include "class-init.h"
#include "icall-decl.h"

static MonoUnhandledExceptionFunc unhandled_exception_hook = NULL;
static gpointer unhandled_exception_hook_data = NULL;

static MonoExceptionHandle
mono_exception_new_by_name_domain (MonoDomain *domain, MonoImage *image,
				const char* name_space, const char *name, MonoError *error);

static MonoExceptionHandle
mono_exception_new_argument_internal (const char *type, const char *arg, const char *msg, MonoError *error);

/**
 * mono_exception_new_by_name:
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 *
 * Creates an exception of the given namespace/name class in the
 * current domain.
 *
 * \returns the initialized exception instance.
 */
static MonoExceptionHandle
mono_exception_new_by_name (MonoImage *image, const char *name_space, const char *name, MonoError *error)
{
	return mono_exception_new_by_name_domain (mono_domain_get (), image, name_space, name, error);
}

/**
 * mono_exception_from_name:
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 *
 * Creates an exception of the given namespace/name class in the
 * current domain.
 *
 * \returns the initialized exception instance.
 */
MonoException *
mono_exception_from_name (MonoImage *image, const char *name_space,
			  const char *name)
{
	return mono_exception_from_name_domain (mono_domain_get (), image, name_space, name);
}

/**
 * mono_exception_new_by_name_domain:
 * \param domain Domain where the return object will be created.
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 *
 * Creates an exception object of the given namespace/name class on
 * the given domain.
 *
 * \returns the initialized exception instance.
 */
static MonoExceptionHandle
mono_exception_new_by_name_domain (MonoDomain *domain, MonoImage *image,
				 const char* name_space, const char *name, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoDomain * const caller_domain = mono_domain_get ();

	MonoClass * const klass = mono_class_load_from_name (image, name_space, name);

	MonoObjectHandle o = mono_object_new_handle (domain, klass, error);
	goto_if_nok (error, return_null);

	if (domain != caller_domain)
		mono_domain_set_internal_with_options (domain, TRUE);

	mono_runtime_object_init_handle (o, error);
	mono_error_assert_ok (error);

	// Restore domain in success and error path.
	if (domain != caller_domain)
		mono_domain_set_internal_with_options (caller_domain, TRUE);

	goto_if_ok (error, exit);
return_null:
	MONO_HANDLE_ASSIGN (o, NULL_HANDLE);
exit:
	HANDLE_FUNCTION_RETURN_REF (MonoException, MONO_HANDLE_CAST (MonoException, o));
}

/**
 * mono_exception_from_name_domain:
 * \param domain Domain where the return object will be created.
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 *
 * Creates an exception object of the given namespace/name class on
 * the given domain.
 *
 * \returns the initialized exception instance.
 */
MonoException *
mono_exception_from_name_domain (MonoDomain *domain, MonoImage *image, 
				 const char* name_space, const char *name)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MonoExceptionHandle ret = mono_exception_new_by_name_domain (domain, image, name_space, name, error);
	mono_error_assert_ok (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_exception_from_token:
 * \param image the Mono image where to look for the class
 * \param token The type token of the class
 *
 * Creates an exception of the type given by \p token.
 *
 * \returns the initialized exception instance.
 */
MonoException *
mono_exception_from_token (MonoImage *image, guint32 token)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MonoClass *klass;

	klass = mono_class_get_checked (image, token, error);
	mono_error_assert_ok (error);

	MonoObjectHandle o = mono_object_new_handle (mono_domain_get (), klass, error);
	mono_error_assert_ok (error);

	mono_runtime_object_init_handle (o, error);
	mono_error_assert_ok (error);

	HANDLE_FUNCTION_RETURN_OBJ (MONO_HANDLE_CAST (MonoException, o));
}

static MonoExceptionHandle
create_exception_two_strings (MonoClass *klass, MonoStringHandle a1, MonoStringHandle a2, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoMethod *method = NULL;
	int const count = 1 + !MONO_HANDLE_IS_NULL (a2);
	gpointer iter;
	MonoMethod *m;
	
	MonoObjectHandle o = mono_object_new_handle (mono_domain_get (), klass, error);
	mono_error_assert_ok (error);

	iter = NULL;
	while ((m = mono_class_get_methods (klass, &iter))) {
		MonoMethodSignature *sig;
		
		if (strcmp (".ctor", mono_method_get_name (m)))
			continue;
		sig = mono_method_signature_internal (m);
		if (sig->param_count != count)
			continue;

		if (sig->params [0]->type != MONO_TYPE_STRING)
			continue;
		if (count == 2 && sig->params [1]->type != MONO_TYPE_STRING)
			continue;
		method = m;
		break;
	}
	g_assert (method);

	gpointer args [ ] = { MONO_HANDLE_RAW (a1), MONO_HANDLE_RAW (a2) };

	mono_runtime_invoke_handle_void (method, o, args, error);
	if (!is_ok (error))
		o = mono_new_null ();

	HANDLE_FUNCTION_RETURN_REF (MonoException, MONO_HANDLE_CAST (MonoException, o));
}

/**
 * mono_exception_from_name_two_strings:
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 * \param a1 first string argument to pass
 * \param a2 second string argument to pass
 *
 * Creates an exception from a constructor that takes two string
 * arguments.
 *
 * \returns the initialized exception instance.
 */
MonoException *
mono_exception_from_name_two_strings (MonoImage *image, const char *name_space,
				      const char *name, MonoString *a1_raw, MonoString *a2_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MONO_HANDLE_DCL (MonoString, a1);
	MONO_HANDLE_DCL (MonoString, a2);
	MonoExceptionHandle ret = mono_exception_from_name_two_strings_checked (image, name_space, name, a1, a2, error);
	mono_error_cleanup (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_exception_from_name_two_strings_checked:
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 * \param a1 first string argument to pass
 * \param a2 second string argument to pass
 * \param error set on error
 *
 * Creates an exception from a constructor that takes two string
 * arguments.
 *
 * \returns the initialized exception instance. On failure returns
 * NULL and sets \p error.
 */
MonoExceptionHandle
mono_exception_from_name_two_strings_checked (MonoImage *image, const char *name_space,
					      const char *name, MonoStringHandle a1, MonoStringHandle a2,
					      MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoClass *klass;

	error_init (error);
	klass = mono_class_load_from_name (image, name_space, name);

	HANDLE_FUNCTION_RETURN_REF (MonoException, create_exception_two_strings (klass, a1, a2, error));
}

/**
 * mono_exception_new_by_name_msg:
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 * \param msg the message to embed inside the exception
 *
 * Creates an exception and initializes its message field.
 *
 * \returns the initialized exception instance.
 */
MonoExceptionHandle
mono_exception_new_by_name_msg (MonoImage *image, const char *name_space,
			      const char *name, const char *msg, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoExceptionHandle ex = mono_exception_new_by_name (image, name_space, name, error);
	goto_if_nok (error, return_null);

	if (msg) {
		MonoStringHandle msg_str = mono_string_new_handle (MONO_HANDLE_DOMAIN (ex), msg, error);
		// FIXME? Maybe just ignore this error, the exception is close to correct.
		goto_if_nok (error, return_null);
		// ex->message = msg_str;
		MONO_HANDLE_SET (ex, message, msg_str);
	}
	goto exit;
return_null:
	MONO_HANDLE_ASSIGN (ex, NULL_HANDLE);
exit:
	HANDLE_FUNCTION_RETURN_REF (MonoException, ex)
}

/**
 * mono_exception_from_name_msg:
 * \param image the Mono image where to look for the class
 * \param name_space the namespace for the class
 * \param name class name
 * \param msg the message to embed inside the exception
 *
 * Creates an exception and initializes its message field.
 *
 * \returns the initialized exception instance.
 */
MonoException *
mono_exception_from_name_msg (MonoImage *image, const char *name_space,
			      const char *name, const char *msg)
{
	HANDLE_FUNCTION_ENTER ();
	MonoExceptionHandle ex;
	MONO_ENTER_GC_UNSAFE;
	ERROR_DECL (error);
	ex = mono_exception_new_by_name_msg (image, name_space, name, msg, error);
	mono_error_cleanup (error);
	MONO_EXIT_GC_UNSAFE;
	HANDLE_FUNCTION_RETURN_OBJ (ex);
}

/**
 * mono_exception_from_token_two_strings:
 *
 *   Same as mono_exception_from_name_two_strings, but lookup the exception class using
 * IMAGE and TOKEN.
 */
MonoException *
mono_exception_from_token_two_strings (MonoImage *image, guint32 token, MonoString *arg1_raw, MonoString *arg2_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MONO_HANDLE_DCL (MonoString, arg1);
	MONO_HANDLE_DCL (MonoString, arg2);
	MonoExceptionHandle ret = mono_exception_from_token_two_strings_checked (image, token, arg1, arg2, error);
	mono_error_cleanup (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_exception_from_token_two_strings_checked:
 *
 *   Same as mono_exception_from_name_two_strings, but lookup the exception class using
 * IMAGE and TOKEN.
 */
MonoExceptionHandle
mono_exception_from_token_two_strings_checked (MonoImage *image, guint32 token,
					       MonoStringHandle a1, MonoStringHandle a2,
					       MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoClass *klass;

	error_init (error);

	klass = mono_class_get_checked (image, token, error);
	mono_error_assert_ok (error); /* FIXME handle the error. */

	HANDLE_FUNCTION_RETURN_REF (MonoException, create_exception_two_strings (klass, a1, a2, error));
}

/**
 * mono_get_exception_divide_by_zero:
 * \returns a new instance of the \c System.DivideByZeroException
 */
MonoException *
mono_get_exception_divide_by_zero (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System",
					 "DivideByZeroException");
}

/**
 * mono_get_exception_security:
 * \returns a new instance of the \c System.Security.SecurityException
 */
MonoException *
mono_get_exception_security (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System.Security",
					 "SecurityException");
}

/**
 * mono_exception_new_thread_abort:
 * \returns a new instance of the \c System.Threading.ThreadAbortException
 */
MonoExceptionHandle
mono_exception_new_thread_abort (MonoError *error)
{
	return mono_exception_new_by_name (mono_get_corlib (), "System.Threading", "ThreadAbortException", error);
}

/**
 * mono_get_exception_thread_abort:
 * \returns a new instance of the \c System.Threading.ThreadAbortException
 */
MonoException *
mono_get_exception_thread_abort (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System.Threading",
					 "ThreadAbortException");
}

/**
 * mono_exception_new_thread_interrupted:
 * \returns a new instance of the \c System.Threading.ThreadInterruptedException
 */
MonoExceptionHandle
mono_exception_new_thread_interrupted (MonoError *error)
{
	return mono_exception_new_by_name (mono_get_corlib (), "System.Threading", "ThreadInterruptedException", error);
}

/**
 * mono_get_exception_thread_interrupted:
 * \returns a new instance of the \c System.Threading.ThreadInterruptedException
 */
MonoException *
mono_get_exception_thread_interrupted (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System.Threading",
					 "ThreadInterruptedException");
}

/**
 * mono_get_exception_arithmetic:
 * \returns a new instance of the \c System.ArithmeticException
 */
MonoException *
mono_get_exception_arithmetic (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System",
					 "ArithmeticException");
}

/**
 * mono_get_exception_overflow:
 * \returns a new instance of the \c System.OverflowException
 */
MonoException *
mono_get_exception_overflow (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System",
					 "OverflowException");
}

/**
 * mono_get_exception_null_reference:
 * \returns a new instance of the \c System.NullReferenceException
 */
MonoException *
mono_get_exception_null_reference (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System",
					 "NullReferenceException");
}

/**
 * mono_get_exception_execution_engine:
 * \param msg the message to pass to the user
 * \returns a new instance of the \c System.ExecutionEngineException
 */
MonoException *
mono_get_exception_execution_engine (const char *msg)
{
	MonoException *result;
	MONO_ENTER_GC_UNSAFE;
	result = mono_exception_from_name_msg (mono_get_corlib (), "System", "ExecutionEngineException", msg);
	MONO_EXIT_GC_UNSAFE;
	return result;
}

/**
 * mono_get_exception_serialization:
 * \param msg the message to pass to the user
 * \returns a new instance of the \c System.Runtime.Serialization.SerializationException
 */
MonoException *
mono_get_exception_serialization (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System.Runtime.Serialization", "SerializationException", msg);
}

/**
 * mono_get_exception_invalid_cast:
 * \returns a new instance of the \c System.InvalidCastException
 */
MonoException *
mono_get_exception_invalid_cast ()
{
	return mono_exception_from_name (mono_get_corlib (), "System", "InvalidCastException");
}

/**
 * mono_get_exception_invalid_operation:
 * \param msg the message to pass to the user
 * \returns a new instance of the \c System.InvalidOperationException
 */
MonoException *
mono_get_exception_invalid_operation (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System",
					"InvalidOperationException", msg);
}

MonoExceptionHandle
mono_exception_new_invalid_operation (const char *msg, MonoError *error)
{
	return mono_exception_new_by_name_msg (mono_get_corlib (), "System",
					"InvalidOperationException", msg, error);
}

/**
 * mono_get_exception_index_out_of_range:
 * \returns a new instance of the \c System.IndexOutOfRangeException
 */
MonoException *
mono_get_exception_index_out_of_range ()
{
	return mono_exception_from_name (mono_get_corlib (), "System",
					 "IndexOutOfRangeException");
}

/**
 * mono_get_exception_array_type_mismatch:
 * \returns a new instance of the \c System.ArrayTypeMismatchException
 */
MonoException *
mono_get_exception_array_type_mismatch (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System",
					 "ArrayTypeMismatchException");
}

/**
 * mono_get_exception_type_load:
 * \param class_name the name of the class that could not be loaded
 * \param assembly_name the assembly where the class was looked up.
 * \returns a new instance of the \c System.TypeLoadException
 */
MonoException *
mono_get_exception_type_load (MonoString *class_name_raw, char *assembly_name)
{
	ERROR_DECL (error);
	HANDLE_FUNCTION_ENTER ();
	MONO_HANDLE_DCL (MonoString, class_name);
	MonoStringHandle s = NULL_HANDLE_STRING;
	MonoDomain * const domain = mono_domain_get ();
	if (assembly_name) {
		s = mono_string_new_handle (domain, assembly_name, error);
		mono_error_assert_ok (error);
	} else
		s = mono_string_empty_handle (domain);

	MonoExceptionHandle ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
								   "TypeLoadException", class_name, s, error);
	mono_error_assert_ok (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_get_exception_not_implemented:
 * \param msg the message to pass to the user
 * \returns a new instance of the \c System.NotImplementedException
 */
MonoException *
mono_get_exception_not_implemented (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotImplementedException", msg);
}

/**
 * mono_get_exception_not_supported:
 * \param msg the message to pass to the user
 * \returns a new instance of the \c System.NotSupportedException
 */
MonoException *
mono_get_exception_not_supported (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System", "NotSupportedException", msg);
}

/**
 * mono_get_exception_missing_member:
 * \param exception_type the specific exception type for the specific member type, i.e. field or method
 * \param class_name the class where the lookup was performed.
 * \param member_name the name of the missing method.
 * \returns a new instance of the \c exception_type (MissingFieldException or MissingMethodException)
 */
static MonoException*
mono_get_exception_missing_member (const char *exception_type, const char *class_name, const char *member_name)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MonoDomain * const domain = mono_domain_get ();
	MonoStringHandle s1 = mono_string_new_handle (domain, class_name, error);
	mono_error_assert_ok (error);
	MonoStringHandle s2 = mono_string_new_handle (domain, member_name, error);
	mono_error_assert_ok (error);

	MonoExceptionHandle ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System",
									   exception_type, s1, s2, error);
	mono_error_assert_ok (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_get_exception_missing_method:
 * \param class_name the class where the lookup was performed.
 * \param member_name the name of the missing method.
 * \returns a new instance of the \c System.MissingMethodException
 */
MonoException *
mono_get_exception_missing_method (const char *class_name, const char *member_name)
{
	return mono_get_exception_missing_member ("MissingMethodException", class_name, member_name);
}

/**
 * mono_get_exception_missing_field:
 * \param class_name the class where the lookup was performed
 * \param member_name the name of the missing field.
 * \returns a new instance of the \c System.MissingFieldException
 */
MonoException *
mono_get_exception_missing_field (const char *class_name, const char *member_name)
{
	return mono_get_exception_missing_member ("MissingFieldException", class_name, member_name);
}

/**
 * mono_get_exception_argument_internal:
 * \param type the actual type
 * \param arg the name of the argument that is invalid or null, etc.
 * \param msg optional message
 * \returns a new instance of the \c System.ArgumentException or derived
 */
static MonoException*
mono_get_exception_argument_internal (const char *type, const char *arg, const char *msg)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MonoExceptionHandle ex = mono_exception_new_argument_internal (type, arg, msg, error);
	mono_error_cleanup (error);
	HANDLE_FUNCTION_RETURN_OBJ (ex);
}

/**
 * mono_get_exception_argument_null:
 * \param arg the name of the argument that is null
 * \returns a new instance of the \c System.ArgumentNullException
 */
MonoException*
mono_get_exception_argument_null (const char *arg)
{
	MonoException *ex;
	MONO_ENTER_GC_UNSAFE;
	ex = mono_get_exception_argument_internal ("ArgumentNullException", arg, NULL);
	MONO_EXIT_GC_UNSAFE;
	return ex;
}

/**
 * mono_get_exception_argument:
 * \param arg the name of the invalid argument.
 * \returns a new instance of the \c System.ArgumentException
 */
MonoException *
mono_get_exception_argument (const char *arg, const char *msg)
{
	return mono_get_exception_argument_internal ("ArgumentException", arg, msg);
}

#ifndef ENABLE_NETCORE
TYPED_HANDLE_DECL (MonoArgumentException);
#endif

static MonoExceptionHandle
mono_exception_new_argument_internal (const char *type, const char *arg, const char *msg, MonoError *error)
{
#ifdef ENABLE_NETCORE
	MonoStringHandle arg_str = arg ? mono_string_new_handle (mono_domain_get (), arg, error) : NULL_HANDLE_STRING;
	MonoStringHandle msg_str = msg ? mono_string_new_handle (mono_domain_get (), msg, error) : NULL_HANDLE_STRING;

	if (!strcmp (type, "ArgumentException"))
		return mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System", type, msg_str, arg_str, error);
	else
		return mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System", type, arg_str, msg_str, error);
#else
	MonoExceptionHandle ex = mono_exception_new_by_name_msg (mono_get_corlib (), "System", type, msg, error);

	if (arg && !MONO_HANDLE_IS_NULL (ex)) {
		MonoArgumentExceptionHandle argex = MONO_HANDLE_CAST (MonoArgumentException, ex);
		MonoStringHandle arg_str = mono_string_new_handle (MONO_HANDLE_DOMAIN (ex), arg, error);
		MONO_HANDLE_SET (argex, param_name, arg_str);
	}
	return ex;
#endif
}

MonoExceptionHandle
mono_exception_new_argument (const char *arg, const char *msg, MonoError *error)
{
	return mono_exception_new_argument_internal ("ArgumentException", arg, msg, error);
}

MonoExceptionHandle
mono_exception_new_argument_null (const char *arg, MonoError *error)
{
	return mono_exception_new_argument_internal ("ArgumentNullException", arg, NULL, error);
}

MonoExceptionHandle
mono_exception_new_argument_out_of_range(const char *arg, const char *msg, MonoError *error)
{
	return mono_exception_new_argument_internal ("ArgumentOutOfRangeException", arg, msg, error);
}

MonoExceptionHandle
mono_exception_new_serialization (const char *msg, MonoError *error)
{
	return mono_exception_new_by_name_msg (mono_get_corlib (),
		"System.Runtime.Serialization", "SerializationException",
		"Could not serialize unhandled exception.", error);
}

/**
 * mono_get_exception_argument_out_of_range:
 * \param arg the name of the out of range argument.
 * \returns a new instance of the \c System.ArgumentOutOfRangeException
 */
MonoException *
mono_get_exception_argument_out_of_range (const char *arg)
{
	return mono_get_exception_argument_internal ("ArgumentOutOfRangeException", arg, NULL);
}

/**
 * mono_get_exception_thread_state:
 * \param msg the message to present to the user
 * \returns a new instance of the \c System.Threading.ThreadStateException
 */
MonoException *
mono_get_exception_thread_state (const char *msg)
{
	return mono_exception_from_name_msg (
		mono_get_corlib (), "System.Threading", "ThreadStateException", msg);
}

/**
 * mono_get_exception_io:
 * \param msg the message to present to the user
 * \returns a new instance of the \c System.IO.IOException
 */
MonoException *
mono_get_exception_io (const char *msg)
{
	return mono_exception_from_name_msg (
		mono_get_corlib (), "System.IO", "IOException", msg);
}

/**
 * mono_get_exception_file_not_found:
 * \param fname the name of the file not found.
 * \returns a new instance of the \c System.IO.FileNotFoundException
 */
MonoException *
mono_get_exception_file_not_found (MonoString *fname_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MONO_HANDLE_DCL (MonoString, fname);
	MonoExceptionHandle ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System.IO", "FileNotFoundException", fname, fname, error);
	mono_error_assert_ok (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_get_exception_file_not_found2:
 * \param msg an informative message for the user.
 * \param fname the name of the file not found.
 * \returns a new instance of the \c System.IO.FileNotFoundException
 */
MonoException *
mono_get_exception_file_not_found2 (const char *msg, MonoString *fname_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MONO_HANDLE_DCL (MonoString, fname);
	MonoStringHandle s = NULL_HANDLE_STRING;
	if (msg) {
		s = mono_string_new_handle (mono_domain_get (), msg, error);
		mono_error_assert_ok (error);
	}
	MonoExceptionHandle ret = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System.IO", "FileNotFoundException", s, fname, error);
	mono_error_assert_ok (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_get_exception_type_initialization:
 * \param type_name the name of the type that failed to initialize.
 * \param inner the inner exception.
 * \returns a new instance of the \c System.TypeInitializationException
 */
MonoException *
mono_get_exception_type_initialization (const gchar *type_name, MonoException* inner_raw)
{
	HANDLE_FUNCTION_ENTER ();
	MONO_HANDLE_DCL (MonoException, inner);
	ERROR_DECL (error);
	MonoExceptionHandle ret = mono_get_exception_type_initialization_handle (type_name, inner, error);
	if (!is_ok (error)) {
		ret = MONO_HANDLE_CAST (MonoException, mono_new_null ());
		mono_error_cleanup (error);
	}
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

MonoExceptionHandle
mono_get_exception_type_initialization_handle (const gchar *type_name, MonoExceptionHandle inner, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoClass *klass;
	MonoMethod *method;
	gpointer iter;

	error_init (error);

	klass = mono_class_load_from_name (mono_get_corlib (), "System", "TypeInitializationException");

	mono_class_init_internal (klass);

	iter = NULL;
	while ((method = mono_class_get_methods (klass, &iter))) {
		if (!strcmp (".ctor", mono_method_get_name (method))) {
			MonoMethodSignature *sig = mono_method_signature_internal (method);

			if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_STRING && mono_class_from_mono_type_internal (sig->params [1]) == mono_defaults.exception_class)
				break;
		}
		method = NULL;
	}
	g_assert (method);

	MonoDomain * const domain = mono_domain_get ();
	MonoStringHandle type_name_str = mono_string_new_handle (domain, type_name, error);
	mono_error_assert_ok (error);
	gpointer args [ ] = { MONO_HANDLE_RAW (type_name_str), MONO_HANDLE_RAW (inner) };

	MonoObjectHandle exc = mono_object_new_handle (domain, klass, error);
	mono_error_assert_ok (error);

	mono_runtime_invoke_handle_void (method, exc, args, error);
	goto_if_nok (error, return_null);
	goto exit;
return_null:
	exc = mono_new_null ();
exit:
	HANDLE_FUNCTION_RETURN_REF (MonoException, MONO_HANDLE_CAST (MonoException, exc));
}

/**
 * mono_get_exception_synchronization_lock:
 * \param inner the inner exception.
 * \returns a new instance of the \c System.SynchronizationLockException
 */
MonoException *
mono_get_exception_synchronization_lock (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System.Threading", "SynchronizationLockException", msg);
}

/**
 * mono_get_exception_cannot_unload_appdomain:
 * \param inner the inner exception.
 * \returns a new instance of the \c System.CannotUnloadAppDomainException
 */
MonoException *
mono_get_exception_cannot_unload_appdomain (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System", "CannotUnloadAppDomainException", msg);
}

/**
 * mono_get_exception_appdomain_unloaded
 * \returns a new instance of the \c System.AppDomainUnloadedException
 */
MonoException *
mono_get_exception_appdomain_unloaded (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System", "AppDomainUnloadedException");
}

/**
 * mono_get_exception_bad_image_format:
 * \param msg an informative message for the user.
 * \returns a new instance of the \c System.BadImageFormatException
 */
MonoException *
mono_get_exception_bad_image_format (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System", "BadImageFormatException", msg);
}	

/**
 * mono_get_exception_bad_image_format2:
 * \param msg an informative message for the user.
 * \param fname The full name of the file with the invalid image.
 * \returns a new instance of the \c System.BadImageFormatException
 */
MonoException *
mono_get_exception_bad_image_format2 (const char *msg, MonoString *fname_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MonoStringHandle s = NULL_HANDLE_STRING;
	MONO_HANDLE_DCL (MonoString, fname);

	if (msg) {
		s = mono_string_new_handle (mono_domain_get (), msg, error);
		mono_error_assert_ok (error);
	}

	MonoExceptionHandle ret = mono_exception_from_name_two_strings_checked (
		mono_get_corlib (), "System", "BadImageFormatException", s, fname, error);
	mono_error_assert_ok (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

/**
 * mono_get_exception_stack_overflow:
 * \returns a new instance of the \c System.StackOverflowException
 */
MonoException *
mono_get_exception_stack_overflow (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System", "StackOverflowException");	
}

/**
 * mono_get_exception_out_of_memory:
 * \returns a new instance of the \c System.OutOfMemoryException
 */
MonoException *
mono_get_exception_out_of_memory (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System", "OutOfMemoryException");
}

MonoExceptionHandle
mono_get_exception_out_of_memory_handle (void)
{
	return MONO_HANDLE_NEW (MonoException, mono_exception_from_name (mono_get_corlib (), "System", "OutOfMemoryException"));
}

/**
 * mono_get_exception_field_access:
 * \returns a new instance of the \c System.FieldAccessException
 */
MonoException *
mono_get_exception_field_access (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System", "FieldAccessException");
}

/**
 * mono_get_exception_field_access2:
 * \param msg an informative message for the user.
 * \returns a new instance of the \c System.FieldAccessException
 */
MonoException *
mono_get_exception_field_access_msg (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System", "FieldAccessException", msg);
}

/**
 * mono_get_exception_method_access:
 * \returns a new instance of the \c System.MethodAccessException
 */
MonoException *
mono_get_exception_method_access (void)
{
	return mono_exception_from_name (mono_get_corlib (), "System", "MethodAccessException");
}

/**
 * mono_get_exception_method_access2:
 * \param msg an informative message for the user.
 * \returns a new instance of the \c System.MethodAccessException
 */
MonoException *
mono_get_exception_method_access_msg (const char *msg)
{
	return mono_exception_from_name_msg (mono_get_corlib (), "System", "MethodAccessException", msg);
}

/**
 * mono_get_exception_reflection_type_load:
 * \param types an array of types that were defined in the moduled loaded.
 * \param exceptions an array of exceptions that were thrown during the type loading.
 * \returns a new instance of the \c System.Reflection.ReflectionTypeLoadException
 */
MonoException *
mono_get_exception_reflection_type_load (MonoArray *types_raw, MonoArray *exceptions_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MONO_HANDLE_DCL (MonoArray, types);
	MONO_HANDLE_DCL (MonoArray, exceptions);
	MonoExceptionHandle ret = mono_get_exception_reflection_type_load_checked (types, exceptions, error);
	if (!is_ok (error))
		ret = MONO_HANDLE_CAST (MonoException, mono_new_null ());
	mono_error_cleanup (error);
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

MonoExceptionHandle
mono_get_exception_reflection_type_load_checked (MonoArrayHandle types, MonoArrayHandle exceptions, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoClass *klass;
	MonoMethod *method;
	gpointer iter;

	error_init (error);

	klass = mono_class_load_from_name (mono_get_corlib (), "System.Reflection", "ReflectionTypeLoadException");

	mono_class_init_internal (klass);

	/* Find the Type[], Exception[] ctor */
	iter = NULL;
	while ((method = mono_class_get_methods (klass, &iter))) {
		if (!strcmp (".ctor", mono_method_get_name (method))) {
			MonoMethodSignature *sig = mono_method_signature_internal (method);

			if (sig->param_count == 2 && sig->params [0]->type == MONO_TYPE_SZARRAY && sig->params [1]->type == MONO_TYPE_SZARRAY)
				break;
		}
		method = NULL;
	}
	g_assert (method);

	MonoExceptionHandle exc = MONO_HANDLE_CAST (MonoException, MONO_HANDLE_NEW (MonoObject, mono_object_new_checked (mono_domain_get (), klass, error)));
	mono_error_assert_ok (error);

	gpointer args [ ] = { MONO_HANDLE_RAW (types), MONO_HANDLE_RAW (exceptions) };

	mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (exc), args, error);
	goto_if_nok (error, return_null);
	goto exit;
return_null:
	exc = MONO_HANDLE_CAST (MonoException, mono_new_null ());
exit:
	HANDLE_FUNCTION_RETURN_REF (MonoException, exc);
}

/**
 * mono_get_exception_runtime_wrapped:
 */
MonoException *
mono_get_exception_runtime_wrapped (MonoObject *wrapped_exception_raw)
{
	HANDLE_FUNCTION_ENTER ();
	ERROR_DECL (error);
	MONO_HANDLE_DCL (MonoObject, wrapped_exception);
	MonoExceptionHandle ret = mono_get_exception_runtime_wrapped_handle (wrapped_exception, error);
	if (!is_ok (error)) {
		mono_error_cleanup (error);
		ret = MONO_HANDLE_CAST (MonoException, mono_new_null ());
	}
	HANDLE_FUNCTION_RETURN_OBJ (ret);
}

MonoExceptionHandle
mono_get_exception_runtime_wrapped_handle (MonoObjectHandle wrapped_exception, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoClass *klass;
	MonoMethod *method;

	klass = mono_class_load_from_name (mono_get_corlib (), "System.Runtime.CompilerServices", "RuntimeWrappedException");

	MonoObjectHandle o = mono_object_new_handle (mono_domain_get (), klass, error);
	mono_error_assert_ok (error);
	g_assert (!MONO_HANDLE_IS_NULL (o));

	method = mono_class_get_method_from_name_checked (klass, ".ctor", 1, 0, error);
	mono_error_assert_ok (error);
	g_assert (method);

	gpointer args [ ] = { MONO_HANDLE_RAW (wrapped_exception) };

	mono_runtime_invoke_handle_void (method, o, args, error);
	goto_if_nok (error, return_null);
	goto exit;
return_null:
	o = mono_new_null ();
exit:
	HANDLE_FUNCTION_RETURN_REF (MonoException, MONO_HANDLE_CAST (MonoException, o));
}

typedef struct {
	GString *text;
	const char *prefix;
} AppendFrameData;

static gboolean
append_frame_and_continue (MonoMethod *method, gpointer ip, size_t native_offset, gboolean managed, gpointer user_data)
{
	MONO_ENTER_GC_UNSAFE;
	MonoDomain *domain = mono_domain_get ();
	AppendFrameData *data = (AppendFrameData *)user_data;

	if (data->prefix)
		g_string_append (data->text, data->prefix);
	if (method) {
		char *msg = mono_debug_print_stack_frame (method, native_offset, domain);
		g_string_append_printf (data->text, "%s\n", msg);
		g_free (msg);
	} else {
		g_string_append_printf (data->text, "at <unknown native frame 0x%p>\n", ip);
	}
	MONO_EXIT_GC_UNSAFE;
	return FALSE;
}

gboolean
mono_exception_try_get_managed_backtrace (MonoException *exc, const char *prefix, char **result)
{
	AppendFrameData data;

	data.text = g_string_new_len (NULL, 20);
	data.prefix = prefix;

	if (!mono_get_eh_callbacks ()->mono_exception_walk_trace (exc, append_frame_and_continue, &data)) {
		g_string_free (data.text, TRUE);
		*result = NULL;
		return FALSE;
	}

	*result = g_string_free (data.text, FALSE);
	return TRUE;
}

char *
mono_exception_get_managed_backtrace (MonoException *exc)
{
	char *result;

	if (!mono_exception_try_get_managed_backtrace (exc, NULL, &result))
		return g_strdup ("managed backtrace not available\n");

	return result;
}

char *
mono_exception_handle_get_native_backtrace (MonoExceptionHandle exc)
{
#ifdef HAVE_BACKTRACE_SYMBOLS
	MonoDomain *domain;
	MonoArrayHandle arr = MONO_HANDLE_NEW(MonoArray, NULL);
	int i, len;
	GString *text;
	char **messages;

	MONO_HANDLE_GET (arr, exc, native_trace_ips);

	if (MONO_HANDLE_IS_NULL(arr))
		return g_strdup ("");
	domain = mono_domain_get ();
	len = mono_array_handle_length (arr);
	text = g_string_new_len (NULL, len * 20);
	MonoGCHandle gchandle;
	gpointer *addr = MONO_ARRAY_HANDLE_PIN (arr, gpointer, 0, &gchandle);
	MONO_ENTER_GC_SAFE;
	messages = backtrace_symbols (addr, len);
	MONO_EXIT_GC_SAFE;
	mono_gchandle_free_internal (gchandle);

	for (i = 0; i < len; ++i) {
		gpointer ip;
		MONO_HANDLE_ARRAY_GETVAL (ip, arr, gpointer, i);
		MonoJitInfo *ji = mono_jit_info_table_find (domain, ip);
		if (ji) {
			char *msg = mono_debug_print_stack_frame (mono_jit_info_get_method (ji), (char*)ip - (char*)ji->code_start, domain);
			g_string_append_printf (text, "%s\n", msg);
			g_free (msg);
		} else {
			g_string_append_printf (text, "%s\n", messages [i]);
		}
	}

	g_free (messages);
	return g_string_free (text, FALSE);
#else
	return g_strdup ("");
#endif
}

MonoStringHandle
ves_icall_Mono_Runtime_GetNativeStackTrace (MonoExceptionHandle exc, MonoError *error)
{
	char *trace;
	MonoStringHandle res;
	error_init (error);

	if (MONO_HANDLE_IS_NULL (exc)) {
		mono_error_set_argument_null (error, "exception", "");
		return NULL_HANDLE_STRING;
	}

	trace = mono_exception_handle_get_native_backtrace (exc);
	res = mono_string_new_handle (mono_domain_get (), trace, error);
	g_free (trace);
	return res;
}

/**
 * mono_error_raise_exception_deprecated:
 * \param target_error the exception to raise
 *
 * Raises the exception of \p target_error.
 * Does nothing if \p target_error has a success error code.
 * Aborts in case of a double fault. This happens when it can't recover from an error caused by trying
 * to construct the first exception object.
 * The error object \p target_error is cleaned up.
*/
void
mono_error_raise_exception_deprecated (MonoError *target_error)
{
	MonoException *ex = mono_error_convert_to_exception (target_error);
	if (ex)
		mono_raise_exception_deprecated (ex);
}

/**
 * mono_error_set_pending_exception_slow:
 * \param error The error
 * If \p error is set, convert it to an exception and set the pending exception for the current icall.
 * \returns TRUE if \p error was set, or FALSE otherwise, so that you can write:
 *    if (mono_error_set_pending_exception (error)) {
 *      { ... cleanup code ... }
 *      return;
 *    }
 */
// For efficiency, call mono_error_set_pending_exception instead of mono_error_set_pending_exception_slow.
gboolean
mono_error_set_pending_exception_slow (MonoError *error)
{
	if (is_ok (error))
		return FALSE;

	HANDLE_FUNCTION_ENTER ();

	MonoExceptionHandle ex = mono_error_convert_to_exception_handle (error);
	gboolean const result = !MONO_HANDLE_IS_NULL (ex);
	if (result)
		mono_set_pending_exception_handle (ex);

	HANDLE_FUNCTION_RETURN_VAL (result);
}

void
mono_install_unhandled_exception_hook (MonoUnhandledExceptionFunc func, void *user_data)
{
	unhandled_exception_hook = func;
	unhandled_exception_hook_data = user_data;
}

void
mono_invoke_unhandled_exception_hook (MonoObject *exc)
{
	if (unhandled_exception_hook) {
		unhandled_exception_hook (exc, unhandled_exception_hook_data);
	} else {
		ERROR_DECL (inner_error);
		MonoObject *other = NULL;
		MonoString *str = mono_object_try_to_string (exc, &other, inner_error);
		char *msg = NULL;
		
		if (str && is_ok (inner_error)) {
			msg = mono_string_to_utf8_checked_internal (str, inner_error);
			if (!is_ok (inner_error)) {
				msg = g_strdup_printf ("Nested exception while formatting original exception");
				mono_error_cleanup (inner_error);
			}
		} else if (other) {
			char *original_backtrace = mono_exception_get_managed_backtrace ((MonoException*)exc);
			char *nested_backtrace = mono_exception_get_managed_backtrace ((MonoException*)other);

			msg = g_strdup_printf ("Nested exception detected.\nOriginal Exception: %s\nNested exception:%s\n",
				original_backtrace, nested_backtrace);

			g_free (original_backtrace);
			g_free (nested_backtrace);
		} else {
			msg = g_strdup ("Nested exception trying to figure out what went wrong");
		}
		mono_runtime_printf_err ("[ERROR] FATAL UNHANDLED EXCEPTION: %s", msg);
		g_free (msg);
#if defined(HOST_IOS)
		g_assertion_message ("Terminating runtime due to unhandled exception");
#else
		exit (mono_environment_exitcode_get ());
#endif
	}

	g_assert_not_reached ();
}

MonoExceptionHandle
mono_corlib_exception_new_with_args (const char *name_space, const char *name, const char *arg_0, const char *arg_1, MonoError *error)
{
	HANDLE_FUNCTION_ENTER ();

	MonoStringHandle str_0 = NULL_HANDLE_STRING;
	MonoStringHandle str_1 = NULL_HANDLE_STRING;
	MonoExceptionHandle ex = MONO_HANDLE_CAST (MonoException, NULL_HANDLE);
	MonoDomain * const domain = mono_domain_get ();

	str_0 = arg_0 ? mono_string_new_handle (domain, arg_0, error) : NULL_HANDLE_STRING;
	goto_if_nok (error, return_null);

	str_1 = arg_1 ? mono_string_new_handle (domain, arg_1, error) : NULL_HANDLE_STRING;
	goto_if_nok (error, return_null);

	ex = mono_exception_from_name_two_strings_checked (mono_defaults.corlib, name_space, name, str_0, str_1, error);
	goto exit;
return_null:
	ex = MONO_HANDLE_CAST (MonoException, mono_new_null ());
exit:
	HANDLE_FUNCTION_RETURN_REF (MonoException, ex);
}

void
mono_error_set_field_missing (MonoError *error, MonoClass *klass, const char *field_name, MonoType *sig, const char *reason, ...)
{
	char *result;
	GString *res;

	res = g_string_new ("Field not found: ");


	if (sig) {
		mono_type_get_desc (res, sig, TRUE);
		g_string_append_c (res, ' ');
	}

	if (klass) {
		if (m_class_get_name_space (klass)) {
			g_string_append (res, m_class_get_name_space (klass));
			g_string_append_c (res, '.');
		}
		g_string_append (res, m_class_get_name (klass));
	}
	else {
		g_string_append (res, "<unknown type>");
	}

	g_string_append_c (res, '.');

	if (field_name)
		g_string_append (res, field_name);
	else
		g_string_append (res, "<unknown field>");

	if (reason && *reason) {
		va_list args;
		va_start (args, reason);

		g_string_append (res, " Due to: ");
		g_string_append_vprintf (res, reason, args);
		va_end (args);
	}
	result = res->str;
	g_string_free (res, FALSE);

	mono_error_set_specific (error, MONO_ERROR_MISSING_FIELD, result);
}

/*
 * Sets @error to a method missing error.
 */
void
mono_error_set_method_missing (MonoError *error, MonoClass *klass, const char *method_name, MonoMethodSignature *sig, const char *reason, ...)
{
	int i;
	char *result;
	GString *res;

	res = g_string_new ("Method not found: ");

	if (sig) {
		mono_type_get_desc (res, sig->ret, TRUE);

		g_string_append_c (res, ' ');
	}

	if (klass) {
		if (m_class_get_name_space (klass)) {
			g_string_append (res, m_class_get_name_space (klass));
			g_string_append_c (res, '.');
		}
		g_string_append (res, m_class_get_name (klass));
	}
	else {
		g_string_append (res, "<unknown type>");
	}

	g_string_append_c (res, '.');

	if (method_name)
		g_string_append (res, method_name);
	else
		g_string_append (res, "<unknown method>");

	if (sig) {
		if (sig->generic_param_count) {
			g_string_append_c (res, '<');
			for (i = 0; i < sig->generic_param_count; ++i) {
				if (i > 0)
					g_string_append (res, ",");
				g_string_append_printf (res, "!%d", i);
			}
			g_string_append_c (res, '>');
		}

		g_string_append_c (res, '(');
		for (i = 0; i < sig->param_count; ++i) {
			if (i > 0)
				g_string_append_c (res, ',');
			mono_type_get_desc (res, sig->params [i], TRUE);
		}
		g_string_append_c (res, ')');
	}

	if (reason && *reason) {
		va_list args;
		va_start (args, reason);

		g_string_append (res, " Due to: ");
		g_string_append_vprintf (res, reason, args);
		va_end (args);
	}
	result = res->str;
	g_string_free (res, FALSE);

	mono_error_set_specific (error, MONO_ERROR_MISSING_METHOD, result);
}

#define SET_ERROR_MSG(STR_VAR, FMT_STR) do {	\
	va_list __args;	\
	va_start (__args, FMT_STR);	\
	STR_VAR = g_strdup_vprintf (FMT_STR, __args);	\
	va_end(__args);	\
} while (0);

/**
 * \p image_name argument will be g_strdup'd. Called must free passed value
 */
void
mono_error_set_bad_image_by_name (MonoError *error, const char *image_name, const char *msg_format, ...)
{
	char *str;
	SET_ERROR_MSG (str, msg_format);

	mono_error_set_specific (error, MONO_ERROR_BAD_IMAGE, str);
	if (image_name)
		mono_error_set_first_argument (error, image_name);
}

void
mono_error_set_bad_image (MonoError *error, MonoImage *image, const char *msg_format, ...)
{
	char *str;
	SET_ERROR_MSG (str, msg_format);

	mono_error_set_specific (error, MONO_ERROR_BAD_IMAGE, str);
	if (image)
		mono_error_set_first_argument (error, mono_image_get_name (image));
}

void
mono_error_set_file_not_found (MonoError *error, const char *file_name, const char *msg_format, ...)
{
	char *str;
	SET_ERROR_MSG (str, msg_format);

	mono_error_set_specific (error, MONO_ERROR_FILE_NOT_FOUND, str);
	if (file_name)
		mono_error_set_first_argument (error, file_name);
}

void
mono_error_set_simple_file_not_found (MonoError *error, const char *file_name, gboolean refection_only)
{
	if (refection_only)
		mono_error_set_file_not_found (error, file_name, "Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", file_name);
	else
		mono_error_set_file_not_found (error, file_name, "Could not load file or assembly '%s' or one of its dependencies.", file_name);
}

void
mono_error_set_argument_out_of_range (MonoError *error, const char *param_name, const char *msg_format, ...)
{
	char *str;
	SET_ERROR_MSG (str, msg_format);
	mono_error_set_specific (error, MONO_ERROR_ARGUMENT_OUT_OF_RANGE, str);
	if (param_name)
		mono_error_set_first_argument (error, param_name);
}

MonoExceptionHandle
mono_error_convert_to_exception_handle (MonoError *error)
{
	//FIXMEcoop mono_error_convert_to_exception is raw pointer
	// The "optimization" here is important to significantly reduce handle usage.
	return is_ok (error) ? MONO_HANDLE_CAST (MonoException, NULL_HANDLE)
		: MONO_HANDLE_NEW (MonoException, mono_error_convert_to_exception (error));
}