File: Future.cpp

package info (click to toggle)
storm-lang 0.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,028 kB
  • sloc: ansic: 261,471; cpp: 140,432; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (520 lines) | stat: -rw-r--r-- 14,111 bytes parent folder | download
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
#include "stdafx.h"
#include "Future.h"
#include "PtrThrowable.h"
#include "UThread.h"
#include "Utils/TIB.h"

namespace os {

	FutureBase::FutureBase(FutureMode::Mode mode)
		: ptrException(null), resultPosted(resultEmpty), resultRead(readNone), mode(mode), notified(false) {}

	FutureBase::~FutureBase() {
		// Warn about uncaught exceptions if we didn't throw it yet.
		if (resultRead == readNone) {
			switch (atomicRead(resultPosted)) {
			case resultError:
				try {
					throwError();
				} catch (const ::Exception &e) {
					PLN(L"Unhandled exception from abandoned future:\n" << e);
				} catch (const PtrThrowable *e) {
					PLN(L"Unhandled exception from abandoned future:\n" << e->toCStr());
				} catch (...) {
					PLN(L"Unknown unhandled exception from abandoned future.");
				}
				break;
			case resultErrorPtr:
				if (ptrException) {
					PLN(L"Unhandled exception from abandoned future:\n" << ptrException->toCStr());
				} else {
					PLN(L"Unhandled exception from abandoned future.");
				}
				break;
			}

			resultRead = readOnce;
		}

		// OS specific cleanup.
		cleanError();
	}

	void FutureBase::result() {
		result(null, null);
	}

	void FutureBase::result(InterceptFn fn, void *env) {
		// Block the first thread, and allow any subsequent threads to enter.
		wait();
		atomicWrite(resultRead, readOnce);

		switch (atomicRead(resultPosted)) {
		case resultError:
			throwError();
			break;
		case resultErrorPtr:
			throwPtrError(fn, env);
			break;
		}
	}

	void FutureBase::warnDetachedError() {
		switch (atomicRead(resultPosted)) {
		case resultError:
			try {
				throwError();
			} catch (const ::Exception &e) {
				PLN(L"Unhandled exception from detached future:\n" << e);
			} catch (const PtrThrowable *e) {
				PLN(L"Unhandled exception from detached future:\n" << e->toCStr());
			} catch (...) {
				PLN(L"Unknown unhandled exception from detached future.");
			}
			break;
		case resultErrorPtr:
			if (ptrException) {
				PLN(L"Unhandled exception from detached future:\n" << ptrException->toCStr());
			} else {
				PLN(L"Unhandled exception from detached future.");
			}
			break;
		}
	}

	void FutureBase::detach() {
		nat oldRead = atomicCAS(resultRead, readNone, readDetached);
		if (oldRead == readNone) {
			// Note: Since we don't check 'resultRead' and 'resultPosted' as a unit, this might give
			// us two warnings in rare cases. As this is not very harmful, it is not really worth
			// the effort to ensure atomicity here.
			warnDetachedError();
		}
	}

	bool FutureBase::anyPosted() {
		return atomicRead(resultPosted) != resultEmpty;
	}

	bool FutureBase::dataPosted() {
		return atomicRead(resultPosted) == resultValue;
	}

	void FutureBase::posted() {
		nat p = atomicCAS(resultPosted, resultEmpty, resultValue);
		assert(p == 0, L"A future may not be used more than once! this=" + ::toHex(this));
		(void)p; // Avoid warning in release mode.
		notify();
	}

	void FutureBase::error() {
		try {
			throw;
		} catch (const PtrThrowable *ex) {
			// Save the exception pointer directly. It may be GC:d.
			nat p = atomicCAS(resultPosted, resultEmpty, resultErrorPtr);
			assert(p == resultEmpty, L"A future may not be used more than once! this=" + ::toHex(this));
			(void)p; // Avoid warning in release mode.
			savePtrError(ex);
		} catch (...) {
			// Fall back on exception_ptr or similar.
			nat p = atomicCAS(resultPosted, resultEmpty, resultError);
			assert(p == resultEmpty, L"A future may not be used more than once! this=" + ::toHex(this));
			(void)p; // Avoid warning in release mode.
			saveError();
		}
		notify();

		if (atomicRead(resultRead) == readDetached) {
			// Not really atomic, worst case is that we get the warning twice. See comment in "detach".
			warnDetachedError();
		}
	}

	void FutureBase::notify() {
		// Keep lists locally in case the thread(s) we wake deallocate this future once they wake up.
		InlineList<UThreadData> local;

		{
			util::Lock::L z(lock);
			notified = true;

			while (UThreadData *wake = waitingThreads.pop())
				local.push(wake);
		}

		while (UThreadData *wake = local.pop())
			wake->owner()->wake(wake);
	}

	void FutureBase::wait() {
		UThreadState *state = null;

		{
			util::Lock::L z(lock);

			if (notified)
				return;

			state = UThreadState::current();
			waitingThreads.push(state->runningThread());
		}

		// If 'exclusive' is true, we only allow high priority threads to run.
		state->wait(exclusive());
	}

#ifdef CUSTOM_EXCEPTION_PTR

	/**
	 * Implementation more or less copied from Boost exception_ptr.
	 */

	const nat cppExceptionCode = 0xE06D7363;
	const nat cppExceptionMagic = 0x19930520;
#if defined(X86)
	const nat cppExceptionParams = 3;

#if _MSC_VER == 1310
	const nat exceptionInfoOffset = 0x74;
#elif (_MSC_VER == 1400 || _MSC_VER == 1500)
	const nat exceptionInfoOffset = 0x80;
#else
#error "Unknown MSC version."
#endif

#elif defined(X64)
	const nat cppExceptionParams = 4;

#if _MSC_VER==1310
	const nat exceptionInfoOffset = /* probably 0xE0 - 0xC*2, but untested */;
#elif (_MSC_VER == 1400 || _MSC_VER == 1500)
	const nat exceptionInfoOffset = 0xE0;
#else
#error "Unknown MSC version."
#endif

#endif


	struct DummyException {};
	typedef int(DummyException::*CopyCtor)(void * src);
	typedef int(DummyException::*VirtualCopyCtor)(void * src, void * dst); // virtual base
	typedef void(DummyException::*Dtor)();

	union CppCopyCtor {
		CopyCtor normal;
		VirtualCopyCtor virtualCtor;
	};

	enum CppTypeFlags {
		simpleType = 1,
		virtualBaseType = 4,
	};

	// Note: pointers below are offsets relative to the HINSTANCE on 64-bit systems.

	struct CppTypeInfo {
		unsigned flags;
		DWORD typeInfoOffset;
		int thisOffset;
		int vbaseDescr;
		int vbaseOffset;
		unsigned int size;
		DWORD copyCtorOffset;

		std::type_info *typeInfo(HINSTANCE instance) const {
			return (std::type_info *)(size_t(instance) + size_t(typeInfoOffset));
		}
		CppCopyCtor copyCtor(HINSTANCE instance) const {
			size_t ptr = size_t(instance) + size_t(copyCtorOffset);
			CppCopyCtor result;
			result.normal = asMemberPtr<CopyCtor>((void *)ptr);
			return result;
		}
	};

	struct CppTypeInfoTable {
		unsigned count;
		DWORD infoOffset[1];

		const CppTypeInfo *info(HINSTANCE instance) const {
			return (const CppTypeInfo *)(size_t(instance) + size_t(infoOffset[0]));
		}
	};

	struct CppExceptionType {
		unsigned flags;
		DWORD dtorOffset;
		DWORD handlerOffset; // void (*handler)()
		DWORD tableOffset;

		Dtor dtor(HINSTANCE instance) const {
			return asMemberPtr<Dtor>((void *)(size_t(instance) + size_t(dtorOffset)));
		}
		const CppTypeInfoTable *table(HINSTANCE instance) const {
			return (const CppTypeInfoTable *)(size_t(instance) + size_t(tableOffset));
		}
	};

	static const CppTypeInfo *getCppTypeInfo(const CppExceptionType *t, HINSTANCE instance) {
		const CppTypeInfo *info = t->table(instance)->info(instance);
		assert(info);
		return info;
	}

	static void copyException(void *to, void *from, const CppTypeInfo *info, HINSTANCE instance) {
		CppCopyCtor copy = info->copyCtor(instance);

		bool useCopyCtor = (info->flags & simpleType) == 0;
		useCopyCtor &= copy.normal != null;

		if (useCopyCtor) {
			DummyException *p = (DummyException *)to;
			if (info->flags & virtualBaseType)
				(p->*(copy.virtualCtor))(from, to);
			else
				(p->*(copy.normal))(from);
		} else {
			memmove(to, from, info->size);
		}
	}

	FutureBase::ExceptionPtr::ExceptionPtr() : data(null), type(null), instance(null) {}

	FutureBase::ExceptionPtr::~ExceptionPtr() {
		clear();
	}

	void FutureBase::ExceptionPtr::clear() {
		if (data) {
			Dtor dtor = type->dtor(instance);
			if (dtor) {
				DummyException *p = (DummyException *)data;
				(p->*dtor)();
			}
			free(data);
		}
		data = null;
		type = null;
		instance = null;
	}

	void FutureBase::ExceptionPtr::rethrow() {
		// It is safe to keep stuff at the stack here. catch-blocks are executed
		// on top of this stack, ie this stack frame will not be reclaimed until
		// the catch-blocks have been executed.
		const CppTypeInfo *info = getCppTypeInfo(type, instance);
		void *dst = _alloca(info->size);
		copyException(dst, data, info, instance);
		ULONG_PTR args[cppExceptionParams];
		args[0] = cppExceptionMagic;
		args[1] = (ULONG_PTR)dst;
		args[2] = (ULONG_PTR)type;
		if (cppExceptionParams >= 4)
			args[3] = (ULONG_PTR)instance;
		RaiseException(cppExceptionCode, EXCEPTION_NONCONTINUABLE, cppExceptionParams, args);
	}

	void FutureBase::ExceptionPtr::rethrowPtr(PtrThrowable *&store) {
		// Make a copy on the stack so that we don't accidentally point somewhere unsafe.
		PtrThrowable *copy = store;
		ULONG_PTR args[cppExceptionParams];
		args[0] = cppExceptionMagic;
		args[1] = (ULONG_PTR)&copy;
		args[2] = (ULONG_PTR)type;
		if (cppExceptionParams >= 4)
			args[3] = (ULONG_PTR)instance;
		RaiseException(cppExceptionCode, EXCEPTION_NONCONTINUABLE, cppExceptionParams, args);
	}

	void FutureBase::ExceptionPtr::set(void *src, const CppExceptionType *type, HINSTANCE instance) {
		clear();

		this->type = type;
		this->instance = instance;
		const CppTypeInfo *ti = getCppTypeInfo(type, instance);
		data = malloc(ti->size);
		try {
			copyException(data, src, ti, instance);
		} catch (...) {
			free(data);
			throw;
		}
	}

	void FutureBase::ExceptionPtr::setPtr(void *src, const CppExceptionType *type, HINSTANCE instance, PtrThrowable *&store) {
		clear();

		// Indicate that we need an external pointer for this!
		data = null;
		this->type = type;
		this->instance = instance;
		store = *(PtrThrowable **)src;
	}

	static bool isCppException(EXCEPTION_RECORD *record) {
		return record
			&& record->ExceptionCode == cppExceptionCode
			&& record->NumberParameters == cppExceptionParams
			&& record->ExceptionInformation[0] == cppExceptionMagic;
	}

	int FutureBase::filter(EXCEPTION_POINTERS *info, bool pointer) {
		EXCEPTION_RECORD *record = info->ExceptionRecord;

		if (!isCppException(record)) {
			WARNING(L"Thrown exception is not a C++ exception!");
			return EXCEPTION_CONTINUE_SEARCH;
		}

		if (!record->ExceptionInformation[2]) {
			// It was a re-throw. We need to go look up the exception record from tls!
			byte *base = (byte *)_errno();
			record = *(EXCEPTION_RECORD **)(base + exceptionInfoOffset);
		}

		if (!isCppException(record)) {
			WARNING(L"Thrown exception is a C++ exception, but stored is not.");
		}
		assert(record->ExceptionInformation[2]);

		HINSTANCE instance = 0;
#ifdef X64
		instance = (HINSTANCE)record->ExceptionInformation[3];
#endif

		if (pointer)
			exceptionData.setPtr((void *)record->ExceptionInformation[1],
								(const CppExceptionType *)record->ExceptionInformation[2],
								instance,
								ptrException);
		else
			exceptionData.set((void *)record->ExceptionInformation[1],
							(const CppExceptionType *)record->ExceptionInformation[2],
							instance);

		return EXCEPTION_EXECUTE_HANDLER;
	}

	void FutureBase::saveError() {
		__try {
			throw;
		} __except (filter(GetExceptionInformation(), false)) {
		}
	}

	void FutureBase::savePtrError(const PtrThrowable *) {
		__try {
			throw;
		} __except (filter(GetExceptionInformation(), true)) {
		}
	}


	void FutureBase::throwError() {
		exceptionData.rethrow();
	}

	void FutureBase::throwPtrError(InterceptFn fn, void *env) {
		if (fn) {
			PtrThrowable *modified = (*fn)(ptrException, env);
			exceptionData.rethrowPtr(modified);
		} else {
			exceptionData.rethrowPtr(ptrException);
		}
	}

	void FutureBase::cleanError() {}

#elif defined(POSIX)

	void FutureBase::throwError() {
		void *data = exceptionData;
		std::rethrow_exception(*(std::exception_ptr *)data);
	}

	extern "C" void *__cxa_allocate_exception(size_t size);
	extern "C" void __cxa_throw(void *exception, std::type_info *type, void (*dtor)(void *));

	void FutureBase::throwPtrError(InterceptFn fn, void *env) {
		void *mem = __cxa_allocate_exception(sizeof(void *));
		if (fn) {
			*(void **)mem = (*fn)(ptrException, env);
		} else {
			*(void **)mem = ptrException;
		}
		__cxa_throw(mem, (std::type_info *)exceptionData[0], null);
	}

	void FutureBase::saveError() {
		new (exceptionData) std::exception_ptr(std::current_exception());
	}

	void FutureBase::savePtrError(const PtrThrowable *) {
		std::exception_ptr ptr = std::current_exception();

		// Store the exception type.
		exceptionData[0] = (size_t)ptr.__cxa_exception_type();

		// Store the exception itself.
		// Note: std::exception_ptr is just a pointer to the thrown object, which is a pointer in this case.
		void *internal = *(void **)&ptr;
		ptrException = *(PtrThrowable **)internal;
	}

	void FutureBase::cleanError() {
		if (resultPosted == resultError) {
			// Destroy it properly.
			void *data = exceptionData;
			std::exception_ptr *ePtr = (std::exception_ptr *)data;
			ePtr->~exception_ptr();
		}
	}

#else

	void FutureBase::throwError() {
		std::rethrow_exception(exceptionData);
	}

	int FutureBase::filter(EXCEPTION_POINTERS *ptrs, InterceptFn fn, void *env) {
		// Modify the thrown object in-flight. This should be fine as we are the first one to see
		// the object, and since the object is generally copied to the stack before being thrown (if
		// not, we don't care about the old value anyway, but could be problematic if multiple
		// threads re-throw simultaneously).
		// It seems like the exception is copied to the stack, but this needs more investigation.
		PtrThrowable **ePtr = (PtrThrowable **)ptrs->ExceptionRecord->ExceptionInformation[1];
		if (fn) {
			*ePtr = (*fn)(ptrException, env);
		} else {
			*ePtr = ptrException;
		}
		return EXCEPTION_CONTINUE_SEARCH;
	}

	void FutureBase::throwPtrError(InterceptFn fn, void *env) {
		__try {
			throwError();
		} __except (filter(GetExceptionInformation(), fn, env)) {
		}
	}

	void FutureBase::saveError() {
		exceptionData = std::current_exception();
	}

	void FutureBase::savePtrError(const PtrThrowable *exception) {
		exceptionData = std::current_exception();
		ptrException = const_cast<PtrThrowable *>(exception);
	}

	void FutureBase::cleanError() {
		ptrException = null;
		exceptionData = std::exception_ptr();
	}


#endif

}