-
-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathThread.cpp
More file actions
1463 lines (1204 loc) · 52.3 KB
/
Thread.cpp
File metadata and controls
1463 lines (1204 loc) · 52.3 KB
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
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "Core.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
HRESULT CLR_RT_SubThread::CreateInstance(
CLR_RT_Thread *th,
CLR_RT_StackFrame *stack,
int priority,
CLR_RT_SubThread *&sthRef)
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_SubThread *sth = EVENTCACHE_EXTRACT_NODE(g_CLR_RT_EventCache, CLR_RT_SubThread, DATATYPE_SUBTHREAD);
CHECK_ALLOCATION(sth);
sth->m_owningThread = th; // CLR_RT_Thread* m_owningThread;
sth->m_owningStackFrame = stack; // CLR_RT_StackFrame* m_owningStackFrame;
sth->m_lockRequestsCount = 0; // CLR_UINT32 m_lockRequestsCount;
//
sth->m_priority = priority; // int m_priority;
sth->m_timeConstraint = TIMEOUT_INFINITE; // CLR_INT64 m_timeConstraint;
sth->m_status = 0; // CLR_UINT32 m_status;
th->m_subThreads.LinkAtBack(sth);
NANOCLR_CLEANUP();
sthRef = sth;
NANOCLR_CLEANUP_END();
}
void CLR_RT_SubThread::DestroyInstance(CLR_RT_Thread *th, CLR_RT_SubThread *sthBase, int flags)
{
NATIVE_PROFILE_CLR_CORE();
//
// You cannot destroy a subthread without destroying all the children subthreads.
//
while (true)
{
CLR_RT_SubThread *sth = th->CurrentSubThread();
if (sth->Prev() == NULL)
break;
//
// Release all the frames for this subthread.
//
while (true)
{
CLR_RT_StackFrame *stack = th->CurrentFrame();
if (stack->Prev() == NULL)
break;
if (stack == sth->m_owningStackFrame)
break;
stack->Pop();
}
//
// Release all the locks for this subthread.
//
NANOCLR_FOREACH_NODE(CLR_RT_HeapBlock_Lock, lock, th->m_locks)
{
lock->DestroyOwner(sth);
}
NANOCLR_FOREACH_NODE_END();
//
// Release all the lock requests.
//
g_CLR_RT_ExecutionEngine.DeleteLockRequests(NULL, sth);
if (sth == sthBase && (flags & CLR_RT_SubThread::MODE_IncludeSelf) == 0)
break;
g_CLR_RT_EventCache.Append_Node(sth);
if (sth == sthBase)
break;
}
}
bool CLR_RT_SubThread::ChangeLockRequestCount(int diff)
{
NATIVE_PROFILE_CLR_CORE();
CLR_RT_Thread *th = m_owningThread;
this->m_lockRequestsCount += diff;
th->m_lockRequestsCount += diff;
if (th->m_lockRequestsCount == 0)
{
th->Restart(false);
return true;
}
else
{
th->m_status = CLR_RT_Thread::TH_S_Waiting;
return false;
}
}
void CLR_RT_Thread::BringExecCounterToDate(int iGlobalExecutionCounter)
{
// Normally the condition is false. It becomes true if thread was out of execution for some time.
// The value of (ThreadPriority::System_Highest + 1) is 33.
// 33 for ThreadPriority::Highest gives up to 16 cycles to catch up.
// 33 for ThreadPriority::Lowest we provide only 1 cycle to catch up.
// If thread was sleeping for some time we forefeet the time it was sleeping and not updating execution counter.
if (m_executionCounter - iGlobalExecutionCounter > (int)((1 << ThreadPriority::System_Highest) + 1))
{
m_executionCounter = iGlobalExecutionCounter + (int)((1 << ThreadPriority::System_Highest) + 1);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool CLR_RT_Thread::IsFinalizerThread()
{
NATIVE_PROFILE_CLR_CORE();
return g_CLR_RT_ExecutionEngine.m_finalizerThread == this;
}
bool CLR_RT_Thread::CanThreadBeReused()
{
NATIVE_PROFILE_CLR_CORE();
return (m_flags & CLR_RT_Thread::TH_F_System) &&
(m_status == CLR_RT_Thread::TH_S_Terminated || m_status == CLR_RT_Thread::TH_S_Unstarted);
}
HRESULT CLR_RT_Thread::PushThreadProcDelegate(CLR_RT_HeapBlock_Delegate *pDelegate)
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_MethodDef_Instance inst{};
#if defined(NANOCLR_APPDOMAINS)
CLR_RT_AppDomain *appDomainSav = g_CLR_RT_ExecutionEngine.SetCurrentAppDomain(pDelegate->m_appDomain);
#endif
if (pDelegate == NULL || pDelegate->DataType() != DATATYPE_DELEGATE_HEAD ||
inst.InitializeFromIndex(pDelegate->DelegateFtn()) == false)
{
NANOCLR_SET_AND_LEAVE(CLR_E_WRONG_TYPE);
}
#if defined(NANOCLR_APPDOMAINS)
if (!pDelegate->m_appDomain->IsLoaded())
{
if (!IsFinalizerThread())
{
NANOCLR_SET_AND_LEAVE(CLR_E_APPDOMAIN_EXITED);
}
m_flags |= CLR_RT_Thread::TH_F_ContainsDoomedAppDomain;
}
#endif
this->m_dlg = pDelegate;
this->m_status = TH_S_Ready;
NANOCLR_CHECK_HRESULT(CLR_RT_StackFrame::Push(this, inst, inst.m_target->numArgs));
if ((inst.m_target->flags & CLR_RECORD_METHODDEF::MD_Static) == 0)
{
CLR_RT_StackFrame *stackTop = this->CurrentFrame();
stackTop->m_arguments[0].Assign(pDelegate->m_object);
}
g_CLR_RT_ExecutionEngine.PutInProperList(this);
NANOCLR_CLEANUP();
#if defined(NANOCLR_APPDOMAINS)
g_CLR_RT_ExecutionEngine.SetCurrentAppDomain(appDomainSav);
#endif
NANOCLR_CLEANUP_END();
}
HRESULT CLR_RT_Thread::CreateInstance(int pid, int priority, CLR_RT_Thread *&th, CLR_UINT32 flags)
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_SubThread *sth;
//--//
th = EVENTCACHE_EXTRACT_NODE(g_CLR_RT_EventCache, CLR_RT_Thread, DATATYPE_THREAD);
CHECK_ALLOCATION(th);
{
CLR_RT_ProtectFromGC gc((void **)&th, CLR_RT_Thread::ProtectFromGCCallback);
th->Initialize();
th->m_pid = pid; // int m_pid;
th->m_status = TH_S_Unstarted; // CLR_UINT32 m_status;
th->m_flags = flags; // CLR_UINT32 m_flags;
th->m_executionCounter = 0; // int m_executionCounter;
th->m_timeQuantumExpired = false; // bool m_timeQuantumExpired;
//
th->m_dlg = NULL; // CLR_RT_HeapBlock_Delegate* m_dlg;
th->m_currentException.SetObjectReference(NULL); // CLR_RT_HeapBlock m_currentException;
// UnwindStack m_nestedExceptions[c_MaxStackUnwindDepth];
th->m_nestedExceptionsPos = 0; // int m_nestedExceptionsPos;
//
// //--//
//
th->m_terminationCallback = NULL; // ThreadTerminationCallback m_terminationCallback;
th->m_terminationParameter = NULL; // void* m_terminationParameter;
//
th->m_waitForEvents = 0; // CLR_UINT32 m_waitForEvents;
th->m_waitForEvents_Timeout = TIMEOUT_INFINITE; // CLR_INT64 m_waitForEvents_Timeout;
th->m_waitForEvents_IdleTimeWorkItem = TIMEOUT_ZERO; // CLR_INT64 m_waitForEvents_IdleTimeWorkItem;
//
th->m_locks.DblLinkedList_Initialize(); // CLR_RT_DblLinkedList m_locks;
th->m_lockRequestsCount = 0; // CLR_UINT32 m_lockRequestsCount;
th->m_waitForObject = NULL;
//
th->m_stackFrames.DblLinkedList_Initialize(); // CLR_RT_DblLinkedList m_stackFrames;
//
th->m_subThreads.DblLinkedList_Initialize(); // CLR_RT_DblLinkedList m_subThreads;
//
#if defined(ENABLE_NATIVE_PROFILER)
th->m_fNativeProfiled = false;
#endif
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
th->m_scratchPad = -1; // int m_scratchPad;
th->m_fHasJMCStepper = false; // bool m_fHasJMCStepper
// For normal threads created in CLR m_realThread points to the thread object.
// If debugger creates managed thread for function evaluation, then m_realThread points to the thread that has
// focus in debugger
th->m_realThread = th; // CLR_RT_Thread* m_realThread
#endif // #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
//--//
NANOCLR_CHECK_HRESULT(CLR_RT_SubThread::CreateInstance(th, NULL, priority, sth));
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (g_CLR_RT_ExecutionEngine.m_breakpointsNum)
{
//
// This needs to happen before the Push
//
g_CLR_RT_ExecutionEngine.Breakpoint_Thread_Created(th);
}
#endif // #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
}
NANOCLR_NOCLEANUP();
}
HRESULT CLR_RT_Thread::CreateInstance(
int pid,
CLR_RT_HeapBlock_Delegate *pDelegate,
int priority,
CLR_RT_Thread *&th,
CLR_UINT32 flags)
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
NANOCLR_CHECK_HRESULT(CreateInstance(pid, priority, th, flags));
if (pDelegate)
{
NANOCLR_CHECK_HRESULT(th->PushThreadProcDelegate(pDelegate));
}
NANOCLR_NOCLEANUP();
}
void CLR_RT_Thread::DestroyInstance()
{
NATIVE_PROFILE_CLR_CORE();
DetachAll();
Passivate();
// Prevent ReleaseWhenDeadEx from keeping the thread alive
if (m_flags & CLR_RT_Thread::TH_F_System)
{
m_flags &= ~CLR_RT_Thread::TH_F_System;
OnThreadTerminated();
}
ReleaseWhenDeadEx();
}
bool CLR_RT_Thread::ReleaseWhenDeadEx()
{
NATIVE_PROFILE_CLR_CORE();
// maybe separate for shutdown....
// These threads live forever?!!?
if (m_flags & CLR_RT_Thread::TH_F_System)
return false;
if (!IsReadyForRelease())
return false;
if (this == g_CLR_RT_ExecutionEngine.m_finalizerThread)
g_CLR_RT_ExecutionEngine.m_finalizerThread = NULL;
if (this == g_CLR_RT_ExecutionEngine.m_interruptThread)
g_CLR_RT_ExecutionEngine.m_interruptThread = NULL;
if (this == g_CLR_RT_ExecutionEngine.m_timerThread)
g_CLR_RT_ExecutionEngine.m_timerThread = NULL;
if (this == g_CLR_RT_ExecutionEngine.m_cctorThread)
g_CLR_RT_ExecutionEngine.m_cctorThread = NULL;
return ReleaseWhenDead();
}
//--//
void CLR_RT_Thread::ProtectFromGCCallback(void *state)
{
NATIVE_PROFILE_CLR_CORE();
CLR_RT_Thread *th = (CLR_RT_Thread *)state;
g_CLR_RT_GarbageCollector.Thread_Mark(th);
}
//--//
HRESULT CLR_RT_Thread::Suspend()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
if ((m_flags & CLR_RT_Thread::TH_F_Suspended) == 0 && m_status != CLR_RT_Thread::TH_S_Terminated)
{
m_flags |= CLR_RT_Thread::TH_F_Suspended;
g_CLR_RT_ExecutionEngine.PutInProperList(this);
}
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT CLR_RT_Thread::Resume()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
if ((m_flags & CLR_RT_Thread::TH_F_Suspended) != 0 && m_status != CLR_RT_Thread::TH_S_Terminated)
{
m_flags &= ~CLR_RT_Thread::TH_F_Suspended;
g_CLR_RT_ExecutionEngine.PutInProperList(this);
}
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT CLR_RT_Thread::Terminate()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
m_status = CLR_RT_Thread::TH_S_Terminated;
// An exception is needed to ensure that StackFrame::Pop does not copy uninitialized data
// to callers evaluation stacks. This would likely be harmless, as the entire thread is about to be killed
// However, this is simply a safeguard to prevent possible problems if it ever happens that
// between the start and end of killing the thread, a GC gets run.
(void)Library_corlib_native_System_Exception::CreateInstance(
m_currentException,
g_CLR_RT_WellKnownTypes.m_ThreadAbortException,
S_OK,
CurrentFrame());
g_CLR_RT_ExecutionEngine.PutInProperList(this);
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT CLR_RT_Thread::Abort()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
//
// Only abort a non-terminated thread...
//
if (m_status != CLR_RT_Thread::TH_S_Terminated)
{
(void)Library_corlib_native_System_Exception::CreateInstance(
m_currentException,
g_CLR_RT_WellKnownTypes.m_ThreadAbortException,
S_OK,
CurrentFrame());
m_flags |= CLR_RT_Thread::TH_F_Aborted;
Restart(true);
}
NANOCLR_NOCLEANUP_NOLABEL();
}
void CLR_RT_Thread::Restart(bool fDeleteEvent)
{
NATIVE_PROFILE_CLR_CORE();
//
// Wake up and queue.
//
m_status = CLR_RT_Thread::TH_S_Ready;
g_CLR_RT_ExecutionEngine.PutInProperList(this);
if (fDeleteEvent)
{
m_waitForEvents = 0;
m_waitForEvents_Timeout = TIMEOUT_INFINITE;
}
}
void CLR_RT_Thread::OnThreadTerminated()
{
NATIVE_PROFILE_CLR_CORE();
SignalAll();
//
// Release all the subthreads.
//
CLR_RT_SubThread::DestroyInstance(this, NULL, 0);
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (g_CLR_RT_ExecutionEngine.m_breakpointsNum)
{
g_CLR_RT_ExecutionEngine.Breakpoint_Thread_Terminated(this);
}
#endif // #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
}
void CLR_RT_Thread::Passivate()
{
NATIVE_PROFILE_CLR_CORE();
m_flags &=
~(CLR_RT_Thread::TH_F_Suspended | CLR_RT_Thread::TH_F_ContainsDoomedAppDomain | CLR_RT_Thread::TH_F_Aborted);
g_CLR_RT_ExecutionEngine.m_threadsZombie.LinkAtFront(this);
m_waitForEvents = 0;
m_waitForEvents_Timeout = TIMEOUT_INFINITE;
//--//
if (m_waitForObject != NULL)
{
g_CLR_RT_EventCache.Append_Node(m_waitForObject);
m_waitForObject = NULL;
}
//--//
if ((m_flags & CLR_RT_Thread::TH_F_System) == 0)
{
m_status = CLR_RT_Thread::TH_S_Terminated;
OnThreadTerminated();
}
else
{
m_status = CLR_RT_Thread::TH_S_Unstarted;
}
m_currentException.SetObjectReference(NULL); // Reset exception flag.
//
// If the thread is associated with a timer, advance the state of the timer.
//
if (m_terminationCallback)
{
ThreadTerminationCallback terminationCallback = m_terminationCallback;
m_terminationCallback = NULL;
terminationCallback(m_terminationParameter);
}
if (m_status == CLR_RT_Thread::TH_S_Terminated || m_status == CLR_RT_Thread::TH_S_Unstarted)
{
// This is used by Static constructor thread.
m_dlg = NULL;
}
ReleaseWhenDeadEx();
}
bool CLR_RT_Thread::CouldBeActivated()
{
NATIVE_PROFILE_CLR_CORE();
if (m_waitForEvents_Timeout != TIMEOUT_INFINITE)
return true;
if (m_waitForEvents)
return true;
return false;
}
void CLR_RT_Thread::RecoverFromGC()
{
NATIVE_PROFILE_CLR_CORE();
CheckAll();
}
void CLR_RT_Thread::Relocate()
{
NATIVE_PROFILE_CLR_CORE();
CLR_RT_GarbageCollector::Heap_Relocate((void **)&m_dlg);
m_currentException.Relocate__HeapBlock();
for (int i = 0; i < m_nestedExceptionsPos; i++)
{
UnwindStack &us = m_nestedExceptions[i];
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_stack);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_handlerStack);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_exception);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_ip);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_currentBlockStart);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_currentBlockEnd);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_handlerBlockStart);
CLR_RT_GarbageCollector::Heap_Relocate((void **)&us.m_handlerBlockEnd);
}
}
//--//
#if defined(NANOCLR_TRACE_CALLS)
void CLR_RT_Thread::DumpStack()
{
NATIVE_PROFILE_CLR_CORE();
const char *szStatus;
switch (m_status)
{
case TH_S_Ready:
szStatus = "Ready";
break;
case TH_S_Waiting:
szStatus = "Waiting";
break;
case TH_S_Terminated:
szStatus = "Terminated";
break;
default:
szStatus = "";
break;
}
CLR_Debug::Printf(
"Thread: %d %d %s %s\r\n",
m_pid,
GetThreadPriority(),
szStatus,
(m_flags & CLR_RT_Thread::TH_F_Suspended) ? "Suspended" : "");
NANOCLR_FOREACH_NODE_BACKWARD(CLR_RT_StackFrame, stack, m_stackFrames)
{
CLR_Debug::Printf(" ");
CLR_RT_DUMP::METHOD(stack->m_call);
CLR_Debug::Printf(" [IP: %04x]\r\n", (stack->m_IP - stack->m_IPstart));
}
NANOCLR_FOREACH_NODE_BACKWARD_END();
}
#endif
//--//
void CLR_RT_Thread::ProcessException_FilterPseudoFrameCopyVars(CLR_RT_StackFrame *to, CLR_RT_StackFrame *from)
{
NATIVE_PROFILE_CLR_CORE();
CLR_UINT8 numArgs = from->m_call.m_target->numArgs;
if (numArgs)
{
memcpy(to->m_arguments, from->m_arguments, sizeof(struct CLR_RT_HeapBlock) * numArgs);
}
if (from->m_call.m_target->numLocals)
{
memcpy(to->m_locals, from->m_locals, sizeof(struct CLR_RT_HeapBlock) * from->m_call.m_target->numLocals);
}
}
HRESULT CLR_RT_Thread::ProcessException_EndFilter()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
bool fBreakpointsDisabledSav = false;
#endif
CLR_RT_StackFrame *stack = CurrentFrame();
CLR_INT32 choice = stack->PopValue().NumericByRef().s4;
UnwindStack &us = m_nestedExceptions[m_nestedExceptionsPos - 1];
ProcessException_FilterPseudoFrameCopyVars(us.m_handlerStack, stack);
// Clear the stack variable so Pop doesn't remove us from the UnwindStack.
us.m_stack = NULL;
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions))
{
// We don't want to send any breakpoints until after we set the IP appropriately
fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled);
CLR_EE_DBG_SET(BreakpointsDisabled);
}
#endif
stack->Pop();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && !fBreakpointsDisabledSav)
{
CLR_EE_DBG_CLR(BreakpointsDisabled);
}
#endif
if (choice == 1)
{
// The filter signaled that it will handle this exception. Update the phase state
us.SetPhase(UnwindStack::p_2_RunningFinallys_0);
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions))
{
g_CLR_RT_ExecutionEngine.Breakpoint_Exception(
us.m_handlerStack,
CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_HANDLER_FOUND,
us.m_handlerBlockStart);
}
#endif
}
else
{
// Store the IP so Phase1/FindEhBlock knows to start looking from the point of the filter we were executing.
us.m_ip = us.m_currentBlockStart;
}
// Signal that this is a continuation of processing for the handler on top of the unwind stack.
us.m_flags |= UnwindStack::c_ContinueExceptionHandler;
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
// We must stop if we sent out a Catch Handler found message.
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && CLR_EE_DBG_IS(Stopped))
{ // If the debugger stopped because of the messages we sent, then we should break out of Execute_IL, drop down,
// and wait for the debugger to continue.
m_currentException.SetObjectReference(us.m_exception);
NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION);
}
#endif
(void)ProcessException();
// Swap results around. ProcessException must return a success code in Thread::Execute and set m_currentException to
// continue processing. Execute_IL must get a FAILED hr in order to break outside of the execution loop.
if (m_currentException.Dereference() == NULL)
{
// Return S_OK because exception handling is complete or handling is in-flight and needs to execute IL to
// continue.
NANOCLR_SET_AND_LEAVE(S_OK);
}
else
{
// Return PROCESS_EXCEPTION to break out of the IL loop to rerun ProcessException and/or abort from an unhandled
// exception
NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION);
}
NANOCLR_NOCLEANUP();
}
HRESULT CLR_RT_Thread::ProcessException_EndFinally()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_StackFrame *stack = CurrentFrame();
UnwindStack &us = m_nestedExceptions[m_nestedExceptionsPos - 1];
if (us.m_ip)
{
CLR_PMETADATA ipLeave = us.m_ip;
CLR_RT_ExceptionHandler eh;
if (FindEhBlock(stack, stack->m_IP - 1, ipLeave, eh, true))
{
us.m_stack = stack;
us.m_exception = NULL;
us.m_ip = ipLeave;
us.m_currentBlockStart = eh.m_handlerStart;
us.m_currentBlockEnd = eh.m_handlerEnd;
// Leave is not valid to leave a finally block, and is the only thing that leaves m_ip set when executing
// IL. Therefore if we're here then we are not interfering with an unhandled exception and flags can be
// safely set.
us.SetPhase(UnwindStack::p_4_NormalCleanup);
stack->m_IP = eh.m_handlerStart;
}
else
{ // We're truely done with finally's for now. Pop off the handler
m_nestedExceptionsPos--;
stack->m_IP = ipLeave;
}
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && stack->m_flags & CLR_RT_StackFrame::c_HasBreakpoint)
{
g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Step(stack, stack->m_IP);
}
#endif
NANOCLR_SET_AND_LEAVE(S_OK);
}
else if (us.m_exception)
{
// This finally block was executed because an exception was thrown inside its protected block.
// Signal that this is a continuation of an already existing EH process.
us.m_flags |= UnwindStack::c_ContinueExceptionHandler;
(void)ProcessException();
// Similar to EndFilter, we need to swap the return codes around. Thread::Execute needs a success code or the
// thread will be aborted. ExecuteIL needs a failure code or we'll continue to execute IL when we possibly
// shouldn't.
if (m_currentException.Dereference() == NULL)
{
// Return S_OK because exception handling is complete or handling is in-flight and needs to execute IL to
// continue.
NANOCLR_SET_AND_LEAVE(S_OK);
}
else
{
// Return PROCESS_EXCEPTION to break out of the IL loop to rerun ProcessException and/or abort from an
// unhandled exception
NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION);
}
}
NANOCLR_NOCLEANUP();
}
HRESULT CLR_RT_Thread::ProcessException_Phase1()
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
bool fBreakpointsDisabledSav = false;
#endif
// Load the UnwindStack entry to process, as created/loaded by ProcessException
UnwindStack &us = m_nestedExceptions[m_nestedExceptionsPos - 1];
CLR_RT_ExceptionHandler eh;
// If we were executing a filter that returned false, there's not much point checking the stack frames above the
// point of the filter. Try to resume from the frame of the last filter executed.
CLR_RT_StackFrame *stack = us.m_handlerStack;
#ifndef NANOCLR_NO_IL_INLINE
CLR_RT_InlineFrame tmpInline;
memset(&tmpInline, 0, sizeof(tmpInline));
#endif
// If this is the first pass through _Phase1 then start at the top.
if (!stack)
{
stack = CurrentFrame();
}
// Search for a willing catch handler.
while (stack->Caller() != NULL)
{
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && g_CLR_RT_ExecutionEngine.m_breakpointsNum &&
us.GetPhase() < UnwindStack::p_1_SearchingForHandler_2_SentUsersChance && stack->m_IP)
{
// We have a debugger attached and we need to send some messages before we start searching.
// These messages should only get sent when the search reaches managed code. Stack::Push sets m_IP to NULL
// for native code, so therefore we need IP to be non-NULL
us.m_handlerStack = stack;
if (us.GetPhase() < UnwindStack::p_1_SearchingForHandler_1_SentFirstChance)
{
g_CLR_RT_ExecutionEngine.Breakpoint_Exception(
stack,
CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_FIRST_CHANCE,
NULL);
us.SetPhase(UnwindStack::p_1_SearchingForHandler_1_SentFirstChance);
// Break out here, because of synchronization issues (false positives) with JMC checking.
if (CLR_EE_DBG_IS(Stopped))
{
goto ContinueAndExit;
}
}
// In order to send the User's first chance message, we have to know that we're in JMC
// Do we have thread synchronization issues here? The debugger is sending out 3 Not My Code messages for a
// function, presumably the one on the top of the stack, but when we execute this, we're reading true.
if (stack->m_call.DebuggingInfo().IsJMC())
{
g_CLR_RT_ExecutionEngine.Breakpoint_Exception(
stack,
CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_USERS_CHANCE,
NULL);
us.SetPhase(UnwindStack::p_1_SearchingForHandler_2_SentUsersChance);
if (CLR_EE_DBG_IS(Stopped))
{
goto ContinueAndExit;
}
}
}
#endif // #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (stack->m_call.m_target->flags & CLR_RECORD_METHODDEF::MD_HasExceptionHandlers)
{
CLR_PMETADATA ip;
if (us.m_ip)
{
ip = us.m_ip; // Use the IP set by endfilter
us.m_ip = NULL; // Reset to prevent catch block & PopEH issues via 'leave' or 'endfinally'
}
else
{
ip = stack->m_IP; // Normal case: use the IP where the exception was thrown.
}
if (ip) // No IP? Either out of memory during allocation of stack frame or native method.
{
if (FindEhBlock(stack, ip, NULL, eh, false))
{ // There are two cases here:
// 1. We found a catch block... in this case, we want to break out and go to phase 2.
// 2. We found a filter... in this case, we want to duplicate the stack and execute the filter.
// Store the handler block address and stack frame.
// It's needed in Phase2 for when finally's are finished and we execute the catch handler
us.m_handlerBlockStart = eh.m_handlerStart;
us.m_handlerBlockEnd = eh.m_handlerEnd;
us.m_handlerStack = stack;
#ifndef NANOCLR_NO_IL_INLINE
if (tmpInline.m_IP)
{
us.m_flags |= UnwindStack::c_MagicCatchForInline;
}
#endif
if (eh.IsFilter())
{
CLR_RT_StackFrame *newStack = NULL;
// Store the IP range that we're currently executing so leave/PopEH doesn't accidentally pop the
// filter off.
us.m_currentBlockStart = eh.m_userFilterStart;
us.m_currentBlockEnd = eh.m_handlerStart;
// Create a pseudo-frame at the top of the stack so the filter can call other functions.
CLR_UINT8 numArgs = stack->m_call.m_target->numArgs;
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions))
{
// We don't want to send any breakpoints until after we set the IP appropriately
fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled);
CLR_EE_DBG_SET(BreakpointsDisabled);
}
#endif
hr = CLR_RT_StackFrame::Push(stack->m_owningThread, stack->m_call, numArgs);
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && !fBreakpointsDisabledSav)
{
CLR_EE_DBG_CLR(BreakpointsDisabled);
}
#endif
if (FAILED(hr))
{ // We probably ran out of memory. In either case, don't run this handler.
// Set the IP so we'll try the next catch block.
us.m_ip = us.m_currentBlockStart;
continue;
}
// stack is the original filter stack frame; newStack is the new pseudoframe
newStack = CurrentFrame();
newStack->m_flags |= CLR_RT_StackFrame::c_PseudoStackFrameForFilter;
us.m_stack = newStack;
// Copy local variables and arguments so the filter has access to them.
if (numArgs)
{
memcpy(
newStack->m_arguments,
stack->m_arguments,
sizeof(struct CLR_RT_HeapBlock) * numArgs);
}
if (stack->m_call.m_target->numLocals)
{
memcpy(
newStack->m_locals,
stack->m_locals,
sizeof(struct CLR_RT_HeapBlock) * stack->m_call.m_target->numLocals);
}
newStack->PushValueAndAssign(m_currentException);
// Set the ip to the handler
newStack->m_IP = eh.m_userFilterStart;
// We are willing to execute IL again so clear the m_currentException flag.
m_currentException.SetObjectReference(NULL);
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions))
{
g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Push(
newStack,
CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_STEP_INTERCEPT);
}
#endif
// Return a success value to break out of ProcessException and to signal that execution of IL
// can continue.
NANOCLR_SET_AND_LEAVE(S_OK);
}
else
{ // We found a normal Catch or CatchAll block. We are all set to proceed onto the Unwinding phase.
// Note that we found a catch handler so we don't look for it again for this exception.
us.SetPhase(UnwindStack::p_2_RunningFinallys_0);
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && g_CLR_RT_ExecutionEngine.m_breakpointsNum)
{
g_CLR_RT_ExecutionEngine.Breakpoint_Exception(
stack,
CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_HANDLER_FOUND,
eh.m_handlerStart);
if (CLR_EE_DBG_IS(Stopped))
{
goto ContinueAndExit;
}
}
#endif
// We want to continue running EH "goo" code so leave m_currentException set and return
// PROCESS_EXCEPTION
NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION);
}
}
}
}
// We didn't find a catch block at this level...
// Check to see if we trickled up to a pseudoStack frame that we created to execute a handler
// Both of these shouldn't be set at once because of the two-pass handling mechanism.
if (stack->m_flags & CLR_RT_StackFrame::c_AppDomainTransition)
{
us.m_handlerStack = NULL;
us.SetPhase(UnwindStack::p_2_RunningFinallys_0);
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if (CLR_EE_DBG_IS_NOT(NoStackTraceInExceptions) && g_CLR_RT_ExecutionEngine.m_breakpointsNum)
{
// Send the IP offset -1 for a catch handler in the case of an appdomain transition to mimic the
// desktop.
g_CLR_RT_ExecutionEngine.Breakpoint_Exception(
stack,
CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_HANDLER_FOUND,
stack->m_IPstart - 1);
if (CLR_EE_DBG_IS(Stopped))
{