dotnetanywhere-wb /dna/Thread.c

Language C Lines 263
MD5 Hash fd0301eed2d422b63aa572667bf60865 Estimated Cost $4,568 (why?)
Repository https://bitbucket.org/cosi2/dotnetanywhere-wb.git View Raw File
  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
// Copyright (c) 2009 DotNetAnywhere
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "Compat.h"
#include "Sys.h"

#include "Thread.h"

#include "MethodState.h"
#include "Heap.h"
#include "Type.h"

static tThread *pAllThreads = NULL;
static tThread *pCurrentThread;

tThread* Thread() {
	static U32 threadID = 0;
	tThread *pThis;

	// Create thread and initial method state. This is allocated on the managed heap, and
	// mark as undeletable. When the thread exits, it was marked as deletable.
	pThis = (tThread*)Heap_AllocType(types[TYPE_SYSTEM_THREADING_THREAD]);
	Heap_MakeUndeletable((HEAP_PTR)pThis);
	pThis->threadID = ++threadID;
	pThis->pCurrentMethodState = NULL;
	pThis->threadExitValue = 0;
	pThis->nextFinallyUnwindStack = 0;
	pThis->pAsync = NULL;
	pThis->hasParam = 0;

	pThis->startDelegate = NULL;
	pThis->param = NULL;
	pThis->state = THREADSTATE_UNSTARTED;

	// Allocate the first chunk of thread-local stack
	pThis->pThreadStack = TMALLOC(tThreadStack);
	pThis->pThreadStack->ofs = 0;
	pThis->pThreadStack->pNext = NULL;

	// Add to list of all thread
	pThis->pNextThread = pAllThreads;
	pAllThreads = pThis;

	return pThis;
}

void* Thread_StackAlloc(tThread *pThread, U32 size) {
	tThreadStack *pStack = pThread->pThreadStack;
	void *pAddr = pStack->memory + pStack->ofs;
#if _DEBUG
	*(U32*)pAddr = 0xabababab;
	((U32*)pAddr)++;
	pStack->ofs += 4;
#endif
	pStack->ofs += size;
	if (pStack->ofs > THREADSTACK_CHUNK_SIZE) {
		Crash("Thread-local stack is too large");
	}
#if _DEBUG
	memset(pAddr, 0xcd, size);
	*(U32*)(((char*)pAddr) + size) = 0xfbfbfbfb;
	pStack->ofs += 4;
#endif
	return pAddr;
}

void Thread_StackFree(tThread *pThread, void *pAddr) {
	tThreadStack *pStack = pThread->pThreadStack;
#if _DEBUG
	((U32*)pAddr)--;
	memset(pAddr, 0xfe, pStack->ofs - (U32)(((unsigned char*)pAddr) - pStack->memory));
#endif
	pStack->ofs = (U32)(((unsigned char*)pAddr) - pStack->memory);
}

void Thread_SetEntryPoint(tThread *pThis, tMetaData *pMetaData, IDX_TABLE entryPointToken, PTR params, U32 paramBytes) {
	// Set up the initial MethodState
	pThis->pCurrentMethodState = MethodState(pThis, pMetaData, entryPointToken, NULL);
	// Insert initial parameters (if any)
	if (paramBytes > 0) {
		memcpy(pThis->pCurrentMethodState->pParamsLocals, params, paramBytes);
	}
}

static void Thread_Delete(tThread *pThis) {
	tThreadStack *pStack = pThis->pThreadStack;
	while (pStack != NULL) {
		tThreadStack *pNextStack = pStack->pNext;
		free(pStack);
		pStack = pNextStack;
	}
	Heap_MakeDeletable((HEAP_PTR)pThis);
}

I32 Thread_Execute() {
	tThread *pThread, *pPrevThread;
	U32 status;

	pThread = pAllThreads;
	// Set the initial thread to the RUNNING state.
	pThread->state = THREADSTATE_RUNNING;
	// Set the initial CurrentThread
	pCurrentThread = pThread;

	for (;;) {
		U32 minSleepTime = 0xffffffff;
		I32 threadExitValue;

		status = JIT_Execute(pThread, 100);
		switch (status) {
		case THREAD_STATUS_EXIT:
			threadExitValue = pThread->threadExitValue;
			log_f(1, "Thread ID#%d exited. Return value: %d\n", (int)pThread->threadID, (int)threadExitValue);
			// Remove the current thread from the running threads list.
			// Note that this list may have changed since before the call to JIT_Execute().
			{
				tThread **ppThread = &pAllThreads;
				while (*ppThread != pThread) {
					ppThread = &((*ppThread)->pNextThread);
				}
				*ppThread = (*ppThread)->pNextThread;
			}
			// Delete the current thread
			Thread_Delete(pThread);
			// If there are no more threads left running, then exit application (by returning)
			// Threads that are unstarted or background do not stop the exit
			{
				tThread *pThread = pAllThreads;
				U32 canExit = 1;
				while (pThread != NULL) {
					if ((!(pThread->state & THREADSTATE_BACKGROUND)) && ((pThread->state & (~THREADSTATE_BACKGROUND)) != THREADSTATE_UNSTARTED)) {
						canExit = 0;
						break;
					}
					pThread = pThread->pNextThread;
				}
				if (canExit) {
					return threadExitValue;
				}
			}
			pThread = pAllThreads; // This is not really correct, but it'll work for the time being
			break;
		case THREAD_STATUS_RUNNING:
		case THREAD_STATUS_LOCK_EXIT:
			// Nothing to do
			break;
		case THREAD_STATUS_ASYNC:
			pThread->pAsync->startTime = msTime();
			break;		
		}

		// Move on to the next thread.
		// Find the next thread that isn't sleeping or blocked on IO
		pPrevThread = pThread;
		for (;;) {
			pThread = pThread->pNextThread;
			if (pThread == NULL) {
				pThread = pAllThreads;
			}
			// Set the CurrentThread correctly
			pCurrentThread = pThread;
			if ((pThread->state & (~THREADSTATE_BACKGROUND)) != 0) {
				// Thread is not running
				continue;
			}
			if (pThread->pAsync != NULL) {
				// Discover if whatever is being waited for is finished
				tAsyncCall *pAsync = pThread->pAsync;
				if (pAsync->sleepTime >= 0) {
					// This is a sleep
					U64 nowTime = msTime();
					I32 msSleepRemaining = pAsync->sleepTime - (I32)(nowTime - pAsync->startTime);
					if (msSleepRemaining <= 0) {
						// Sleep is finished
						break;
					}
					// Sleep is not finished, so continue to next thread
					if ((U32)msSleepRemaining < minSleepTime) {
						minSleepTime = msSleepRemaining;
					}
				} else {
					// This is blocking IO, or a lock
					tMethodState *pMethodState = pThread->pCurrentMethodState;
					PTR pThis;
					U32 thisOfs;
					U32 unblocked;

					if (METHOD_ISSTATIC(pMethodState->pMethod)) {
						pThis = NULL;
						thisOfs = 0;
					} else {
						pThis = *(PTR*)pMethodState->pParamsLocals;
						thisOfs = 4;
					}
					unblocked = pAsync->checkFn(pThis, pMethodState->pParamsLocals + thisOfs, pMethodState->pEvalStack, pAsync);
					if (unblocked) {
						// The IO has unblocked, and the return value is ready.
						// So delete the async object.
						// TODO: The async->state object needs to be deleted somehow (maybe)
						free(pAsync);
						// And remove it from the thread
						pThread->pAsync = NULL;
						break;
					}
					minSleepTime = 5;
				}
			} else {
				// Thread is ready to run
				break;
			}
			if (pThread == pPrevThread) {
				// When it gets here, it means that all threads are currently blocked.
				//printf("All blocked; sleep(%d)\n", minSleepTime);
				SleepMS(minSleepTime);
			}
		}
	}

}

tThread* Thread_GetCurrent() {
	return pCurrentThread;
}

void Thread_GetHeapRoots(tHeapRoots *pHeapRoots) {
	tThread *pThread;

	pThread = pAllThreads;
	while (pThread != NULL) {
		tMethodState *pMethodState;

		pMethodState = pThread->pCurrentMethodState;
		while (pMethodState != NULL) {
			// Put the evaluation stack on the roots
			Heap_SetRoots(pHeapRoots, pMethodState->pEvalStack, pMethodState->pMethod->pJITted->maxStack);
			// Put the params/locals on the roots
			Heap_SetRoots(pHeapRoots, pMethodState->pParamsLocals,
				pMethodState->pMethod->parameterStackSize+pMethodState->pMethod->pJITted->localsStackSize);

			pMethodState = pMethodState->pCaller;
		}

		pThread = pThread->pNextThread;
	}
}
Back to Top