| 1 |
/** |
| 2 |
* Base fiber module provides OS-indepedent part of lightweight threads aka fibers. |
| 3 |
* |
| 4 |
* Copyright: Copyright Sean Kelly 2005 - 2012. |
| 5 |
* License: Distributed under the |
| 6 |
* $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0). |
| 7 |
* (See accompanying file LICENSE) |
| 8 |
* Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak |
| 9 |
* Source: $(DRUNTIMESRC core/thread/fiber/base.d) |
| 10 |
*/ |
| 11 |
|
| 12 |
/* NOTE: This file has been patched from the original DMD distribution to |
| 13 |
* work with the GDC compiler. |
| 14 |
*/ |
| 15 |
module core.thread.fiber.base; |
| 16 |
|
| 17 |
package: |
| 18 |
version (GNU) |
| 19 |
import gcc.config; |
| 20 |
|
| 21 |
import core.thread.fiber; |
| 22 |
import core.thread.threadbase; |
| 23 |
import core.thread.threadgroup; |
| 24 |
import core.thread.types; |
| 25 |
import core.thread.context; |
| 26 |
|
| 27 |
import core.memory : pageSize; |
| 28 |
|
| 29 |
package |
| 30 |
{ |
| 31 |
import core.atomic : atomicStore, cas, MemoryOrder; |
| 32 |
import core.exception : onOutOfMemoryError; |
| 33 |
import core.stdc.stdlib : abort; |
| 34 |
|
| 35 |
extern (C) void fiber_entryPoint() nothrow |
| 36 |
{ |
| 37 |
FiberBase obj = FiberBase.getThis(); |
| 38 |
assert( obj ); |
| 39 |
|
| 40 |
assert( ThreadBase.getThis().m_curr is obj.m_ctxt ); |
| 41 |
atomicStore!(MemoryOrder.raw)(*cast(shared)&ThreadBase.getThis().m_lock, false); |
| 42 |
obj.m_ctxt.tstack = obj.m_ctxt.bstack; |
| 43 |
obj.m_state = FiberBase.State.EXEC; |
| 44 |
|
| 45 |
try |
| 46 |
{ |
| 47 |
obj.run(); |
| 48 |
} |
| 49 |
catch ( Throwable t ) |
| 50 |
{ |
| 51 |
obj.m_unhandled = t; |
| 52 |
} |
| 53 |
|
| 54 |
static if ( __traits( compiles, ucontext_t ) ) |
| 55 |
obj.m_ucur = &obj.m_utxt; |
| 56 |
|
| 57 |
obj.m_state = Fiber.State.TERM; |
| 58 |
obj.switchOut(); |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
/////////////////////////////////////////////////////////////////////////////// |
| 63 |
// Fiber |
| 64 |
/////////////////////////////////////////////////////////////////////////////// |
| 65 |
/* |
| 66 |
* Documentation of Fiber internals: |
| 67 |
* |
| 68 |
* The main routines to implement when porting Fibers to new architectures are |
| 69 |
* fiber_switchContext and initStack. Some version constants have to be defined |
| 70 |
* for the new platform as well, search for "Fiber Platform Detection and Memory Allocation". |
| 71 |
* |
| 72 |
* Fibers are based on a concept called 'Context'. A Context describes the execution |
| 73 |
* state of a Fiber or main thread which is fully described by the stack, some |
| 74 |
* registers and a return address at which the Fiber/Thread should continue executing. |
| 75 |
* Please note that not only each Fiber has a Context, but each thread also has got a |
| 76 |
* Context which describes the threads stack and state. If you call Fiber fib; fib.call |
| 77 |
* the first time in a thread you switch from Threads Context into the Fibers Context. |
| 78 |
* If you call fib.yield in that Fiber you switch out of the Fibers context and back |
| 79 |
* into the Thread Context. (However, this is not always the case. You can call a Fiber |
| 80 |
* from within another Fiber, then you switch Contexts between the Fibers and the Thread |
| 81 |
* Context is not involved) |
| 82 |
* |
| 83 |
* In all current implementations the registers and the return address are actually |
| 84 |
* saved on a Contexts stack. |
| 85 |
* |
| 86 |
* The fiber_switchContext routine has got two parameters: |
| 87 |
* void** a: This is the _location_ where we have to store the current stack pointer, |
| 88 |
* the stack pointer of the currently executing Context (Fiber or Thread). |
| 89 |
* void* b: This is the pointer to the stack of the Context which we want to switch into. |
| 90 |
* Note that we get the same pointer here as the one we stored into the void** a |
| 91 |
* in a previous call to fiber_switchContext. |
| 92 |
* |
| 93 |
* In the simplest case, a fiber_switchContext rountine looks like this: |
| 94 |
* fiber_switchContext: |
| 95 |
* push {return Address} |
| 96 |
* push {registers} |
| 97 |
* copy {stack pointer} into {location pointed to by a} |
| 98 |
* //We have now switch to the stack of a different Context! |
| 99 |
* copy {b} into {stack pointer} |
| 100 |
* pop {registers} |
| 101 |
* pop {return Address} |
| 102 |
* jump to {return Address} |
| 103 |
* |
| 104 |
* The GC uses the value returned in parameter a to scan the Fibers stack. It scans from |
| 105 |
* the stack base to that value. As the GC dislikes false pointers we can actually optimize |
| 106 |
* this a little: By storing registers which can not contain references to memory managed |
| 107 |
* by the GC outside of the region marked by the stack base pointer and the stack pointer |
| 108 |
* saved in fiber_switchContext we can prevent the GC from scanning them. |
| 109 |
* Such registers are usually floating point registers and the return address. In order to |
| 110 |
* implement this, we return a modified stack pointer from fiber_switchContext. However, |
| 111 |
* we have to remember that when we restore the registers from the stack! |
| 112 |
* |
| 113 |
* --------------------------- <= Stack Base |
| 114 |
* | Frame | <= Many other stack frames |
| 115 |
* | Frame | |
| 116 |
* |-------------------------| <= The last stack frame. This one is created by fiber_switchContext |
| 117 |
* | registers with pointers | |
| 118 |
* | | <= Stack pointer. GC stops scanning here |
| 119 |
* | return address | |
| 120 |
* |floating point registers | |
| 121 |
* --------------------------- <= Real Stack End |
| 122 |
* |
| 123 |
* fiber_switchContext: |
| 124 |
* push {registers with pointers} |
| 125 |
* copy {stack pointer} into {location pointed to by a} |
| 126 |
* push {return Address} |
| 127 |
* push {Floating point registers} |
| 128 |
* //We have now switch to the stack of a different Context! |
| 129 |
* copy {b} into {stack pointer} |
| 130 |
* //We now have to adjust the stack pointer to point to 'Real Stack End' so we can pop |
| 131 |
* //the FP registers |
| 132 |
* //+ or - depends on if your stack grows downwards or upwards |
| 133 |
* {stack pointer} = {stack pointer} +- ({FPRegisters}.sizeof + {return address}.sizeof} |
| 134 |
* pop {Floating point registers} |
| 135 |
* pop {return Address} |
| 136 |
* pop {registers with pointers} |
| 137 |
* jump to {return Address} |
| 138 |
* |
| 139 |
* So the question now is which registers need to be saved? This depends on the specific |
| 140 |
* architecture ABI of course, but here are some general guidelines: |
| 141 |
* - If a register is callee-save (if the callee modifies the register it must saved and |
| 142 |
* restored by the callee) it needs to be saved/restored in switchContext |
| 143 |
* - If a register is caller-save it needn't be saved/restored. (Calling fiber_switchContext |
| 144 |
* is a function call and the compiler therefore already must save these registers before |
| 145 |
* calling fiber_switchContext) |
| 146 |
* - Argument registers used for passing parameters to functions needn't be saved/restored |
| 147 |
* - The return register needn't be saved/restored (fiber_switchContext hasn't got a return type) |
| 148 |
* - All scratch registers needn't be saved/restored |
| 149 |
* - The link register usually needn't be saved/restored (but sometimes it must be cleared - |
| 150 |
* see below for details) |
| 151 |
* - The frame pointer register - if it exists - is usually callee-save |
| 152 |
* - All current implementations do not save control registers |
| 153 |
* |
| 154 |
* What happens on the first switch into a Fiber? We never saved a state for this fiber before, |
| 155 |
* but the initial state is prepared in the initStack routine. (This routine will also be called |
| 156 |
* when a Fiber is being resetted). initStack must produce exactly the same stack layout as the |
| 157 |
* part of fiber_switchContext which saves the registers. Pay special attention to set the stack |
| 158 |
* pointer correctly if you use the GC optimization mentioned before. the return Address saved in |
| 159 |
* initStack must be the address of fiber_entrypoint. |
| 160 |
* |
| 161 |
* There's now a small but important difference between the first context switch into a fiber and |
| 162 |
* further context switches. On the first switch, Fiber.call is used and the returnAddress in |
| 163 |
* fiber_switchContext will point to fiber_entrypoint. The important thing here is that this jump |
| 164 |
* is a _function call_, we call fiber_entrypoint by jumping before it's function prologue. On later |
| 165 |
* calls, the user used yield() in a function, and therefore the return address points into a user |
| 166 |
* function, after the yield call. So here the jump in fiber_switchContext is a _function return_, |
| 167 |
* not a function call! |
| 168 |
* |
| 169 |
* The most important result of this is that on entering a function, i.e. fiber_entrypoint, we |
| 170 |
* would have to provide a return address / set the link register once fiber_entrypoint |
| 171 |
* returns. Now fiber_entrypoint does never return and therefore the actual value of the return |
| 172 |
* address / link register is never read/used and therefore doesn't matter. When fiber_switchContext |
| 173 |
* performs a _function return_ the value in the link register doesn't matter either. |
| 174 |
* However, the link register will still be saved to the stack in fiber_entrypoint and some |
| 175 |
* exception handling / stack unwinding code might read it from this stack location and crash. |
| 176 |
* The exact solution depends on your architecture, but see the ARM implementation for a way |
| 177 |
* to deal with this issue. |
| 178 |
* |
| 179 |
* The ARM implementation is meant to be used as a kind of documented example implementation. |
| 180 |
* Look there for a concrete example. |
| 181 |
* |
| 182 |
* FIXME: fiber_entrypoint might benefit from a @noreturn attribute, but D doesn't have one. |
| 183 |
*/ |
| 184 |
|
| 185 |
/** |
| 186 |
* This class provides a cooperative concurrency mechanism integrated with the |
| 187 |
* threading and garbage collection functionality. Calling a fiber may be |
| 188 |
* considered a blocking operation that returns when the fiber yields (via |
| 189 |
* Fiber.yield()). Execution occurs within the context of the calling thread |
| 190 |
* so synchronization is not necessary to guarantee memory visibility so long |
| 191 |
* as the same thread calls the fiber each time. Please note that there is no |
| 192 |
* requirement that a fiber be bound to one specific thread. Rather, fibers |
| 193 |
* may be freely passed between threads so long as they are not currently |
| 194 |
* executing. Like threads, a new fiber thread may be created using either |
| 195 |
* derivation or composition, as in the following example. |
| 196 |
* |
| 197 |
* Warning: |
| 198 |
* Status registers are not saved by the current implementations. This means |
| 199 |
* floating point exception status bits (overflow, divide by 0), rounding mode |
| 200 |
* and similar stuff is set per-thread, not per Fiber! |
| 201 |
* |
| 202 |
* Warning: |
| 203 |
* On ARM FPU registers are not saved if druntime was compiled as ARM_SoftFloat. |
| 204 |
* If such a build is used on a ARM_SoftFP system which actually has got a FPU |
| 205 |
* and other libraries are using the FPU registers (other code is compiled |
| 206 |
* as ARM_SoftFP) this can cause problems. Druntime must be compiled as |
| 207 |
* ARM_SoftFP in this case. |
| 208 |
* |
| 209 |
* Authors: Based on a design by Mikola Lysenko. |
| 210 |
*/ |
| 211 |
class FiberBase |
| 212 |
{ |
| 213 |
/** |
| 214 |
* Initializes a fiber object which is associated with a static |
| 215 |
* D function. |
| 216 |
* |
| 217 |
* Params: |
| 218 |
* fn = The fiber function. |
| 219 |
* sz = The stack size for this fiber. |
| 220 |
* guardPageSize = size of the guard page to trap fiber's stack |
| 221 |
* overflows. Beware that using this will increase |
| 222 |
* the number of mmaped regions on platforms using mmap |
| 223 |
* so an OS-imposed limit may be hit. |
| 224 |
* |
| 225 |
* In: |
| 226 |
* fn must not be null. |
| 227 |
*/ |
| 228 |
this( void function() fn, size_t sz, size_t guardPageSize ) nothrow |
| 229 |
in |
| 230 |
{ |
| 231 |
assert( fn ); |
| 232 |
} |
| 233 |
do |
| 234 |
{ |
| 235 |
allocStack( sz, guardPageSize ); |
| 236 |
reset( fn ); |
| 237 |
} |
| 238 |
|
| 239 |
|
| 240 |
/** |
| 241 |
* Initializes a fiber object which is associated with a dynamic |
| 242 |
* D function. |
| 243 |
* |
| 244 |
* Params: |
| 245 |
* dg = The fiber function. |
| 246 |
* sz = The stack size for this fiber. |
| 247 |
* guardPageSize = size of the guard page to trap fiber's stack |
| 248 |
* overflows. Beware that using this will increase |
| 249 |
* the number of mmaped regions on platforms using mmap |
| 250 |
* so an OS-imposed limit may be hit. |
| 251 |
* |
| 252 |
* In: |
| 253 |
* dg must not be null. |
| 254 |
*/ |
| 255 |
this( void delegate() dg, size_t sz, size_t guardPageSize ) nothrow |
| 256 |
{ |
| 257 |
allocStack( sz, guardPageSize ); |
| 258 |
reset( cast(void delegate() const) dg ); |
| 259 |
} |
| 260 |
|
| 261 |
|
| 262 |
/** |
| 263 |
* Cleans up any remaining resources used by this object. |
| 264 |
*/ |
| 265 |
~this() nothrow @nogc |
| 266 |
{ |
| 267 |
// NOTE: A live reference to this object will exist on its associated |
| 268 |
// stack from the first time its call() method has been called |
| 269 |
// until its execution completes with State.TERM. Thus, the only |
| 270 |
// times this dtor should be called are either if the fiber has |
| 271 |
// terminated (and therefore has no active stack) or if the user |
| 272 |
// explicitly deletes this object. The latter case is an error |
| 273 |
// but is not easily tested for, since State.HOLD may imply that |
| 274 |
// the fiber was just created but has never been run. There is |
| 275 |
// not a compelling case to create a State.INIT just to offer a |
| 276 |
// means of ensuring the user isn't violating this object's |
| 277 |
// contract, so for now this requirement will be enforced by |
| 278 |
// documentation only. |
| 279 |
freeStack(); |
| 280 |
} |
| 281 |
|
| 282 |
|
| 283 |
/////////////////////////////////////////////////////////////////////////// |
| 284 |
// General Actions |
| 285 |
/////////////////////////////////////////////////////////////////////////// |
| 286 |
|
| 287 |
|
| 288 |
/** |
| 289 |
* Transfers execution to this fiber object. The calling context will be |
| 290 |
* suspended until the fiber calls Fiber.yield() or until it terminates |
| 291 |
* via an unhandled exception. |
| 292 |
* |
| 293 |
* Params: |
| 294 |
* rethrow = Rethrow any unhandled exception which may have caused this |
| 295 |
* fiber to terminate. |
| 296 |
* |
| 297 |
* In: |
| 298 |
* This fiber must be in state HOLD. |
| 299 |
* |
| 300 |
* Throws: |
| 301 |
* Any exception not handled by the joined thread. |
| 302 |
* |
| 303 |
* Returns: |
| 304 |
* Any exception not handled by this fiber if rethrow = false, null |
| 305 |
* otherwise. |
| 306 |
*/ |
| 307 |
// Not marked with any attributes, even though `nothrow @nogc` works |
| 308 |
// because it calls arbitrary user code. Most of the implementation |
| 309 |
// is already `@nogc nothrow`, but in order for `Fiber.call` to |
| 310 |
// propagate the attributes of the user's function, the Fiber |
| 311 |
// class needs to be templated. |
| 312 |
final Throwable call( Rethrow rethrow = Rethrow.yes ) |
| 313 |
{ |
| 314 |
return rethrow ? call!(Rethrow.yes)() : call!(Rethrow.no); |
| 315 |
} |
| 316 |
|
| 317 |
/// ditto |
| 318 |
final Throwable call( Rethrow rethrow )() |
| 319 |
{ |
| 320 |
callImpl(); |
| 321 |
if ( m_unhandled ) |
| 322 |
{ |
| 323 |
Throwable t = m_unhandled; |
| 324 |
m_unhandled = null; |
| 325 |
static if ( rethrow ) |
| 326 |
throw t; |
| 327 |
else |
| 328 |
return t; |
| 329 |
} |
| 330 |
return null; |
| 331 |
} |
| 332 |
|
| 333 |
private void callImpl() nothrow @nogc |
| 334 |
in |
| 335 |
{ |
| 336 |
assert( m_state == State.HOLD ); |
| 337 |
} |
| 338 |
do |
| 339 |
{ |
| 340 |
FiberBase cur = getThis(); |
| 341 |
|
| 342 |
static if ( __traits( compiles, ucontext_t ) ) |
| 343 |
m_ucur = cur ? &cur.m_utxt : &Fiber.sm_utxt; |
| 344 |
|
| 345 |
setThis( this ); |
| 346 |
this.switchIn(); |
| 347 |
setThis( cur ); |
| 348 |
|
| 349 |
static if ( __traits( compiles, ucontext_t ) ) |
| 350 |
m_ucur = null; |
| 351 |
|
| 352 |
// NOTE: If the fiber has terminated then the stack pointers must be |
| 353 |
// reset. This ensures that the stack for this fiber is not |
| 354 |
// scanned if the fiber has terminated. This is necessary to |
| 355 |
// prevent any references lingering on the stack from delaying |
| 356 |
// the collection of otherwise dead objects. The most notable |
| 357 |
// being the current object, which is referenced at the top of |
| 358 |
// fiber_entryPoint. |
| 359 |
if ( m_state == State.TERM ) |
| 360 |
{ |
| 361 |
m_ctxt.tstack = m_ctxt.bstack; |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
/// Flag to control rethrow behavior of $(D $(LREF call)) |
| 366 |
enum Rethrow : bool { no, yes } |
| 367 |
|
| 368 |
/** |
| 369 |
* Resets this fiber so that it may be re-used, optionally with a |
| 370 |
* new function/delegate. This routine should only be called for |
| 371 |
* fibers that have terminated, as doing otherwise could result in |
| 372 |
* scope-dependent functionality that is not executed. |
| 373 |
* Stack-based classes, for example, may not be cleaned up |
| 374 |
* properly if a fiber is reset before it has terminated. |
| 375 |
* |
| 376 |
* In: |
| 377 |
* This fiber must be in state TERM or HOLD. |
| 378 |
*/ |
| 379 |
final void reset() nothrow @nogc |
| 380 |
in |
| 381 |
{ |
| 382 |
assert( m_state == State.TERM || m_state == State.HOLD ); |
| 383 |
} |
| 384 |
do |
| 385 |
{ |
| 386 |
m_ctxt.tstack = m_ctxt.bstack; |
| 387 |
m_state = State.HOLD; |
| 388 |
initStack(); |
| 389 |
m_unhandled = null; |
| 390 |
} |
| 391 |
|
| 392 |
/// ditto |
| 393 |
final void reset( void function() fn ) nothrow @nogc |
| 394 |
{ |
| 395 |
reset(); |
| 396 |
m_call = fn; |
| 397 |
} |
| 398 |
|
| 399 |
/// ditto |
| 400 |
final void reset( void delegate() dg ) nothrow @nogc |
| 401 |
{ |
| 402 |
reset(); |
| 403 |
m_call = dg; |
| 404 |
} |
| 405 |
|
| 406 |
/////////////////////////////////////////////////////////////////////////// |
| 407 |
// General Properties |
| 408 |
/////////////////////////////////////////////////////////////////////////// |
| 409 |
|
| 410 |
|
| 411 |
/// A fiber may occupy one of three states: HOLD, EXEC, and TERM. |
| 412 |
enum State |
| 413 |
{ |
| 414 |
/** The HOLD state applies to any fiber that is suspended and ready to |
| 415 |
be called. */ |
| 416 |
HOLD, |
| 417 |
/** The EXEC state will be set for any fiber that is currently |
| 418 |
executing. */ |
| 419 |
EXEC, |
| 420 |
/** The TERM state is set when a fiber terminates. Once a fiber |
| 421 |
terminates, it must be reset before it may be called again. */ |
| 422 |
TERM |
| 423 |
} |
| 424 |
|
| 425 |
|
| 426 |
/** |
| 427 |
* Gets the current state of this fiber. |
| 428 |
* |
| 429 |
* Returns: |
| 430 |
* The state of this fiber as an enumerated value. |
| 431 |
*/ |
| 432 |
final @property State state() const @safe pure nothrow @nogc |
| 433 |
{ |
| 434 |
return m_state; |
| 435 |
} |
| 436 |
|
| 437 |
|
| 438 |
/////////////////////////////////////////////////////////////////////////// |
| 439 |
// Actions on Calling Fiber |
| 440 |
/////////////////////////////////////////////////////////////////////////// |
| 441 |
|
| 442 |
|
| 443 |
/** |
| 444 |
* Forces a context switch to occur away from the calling fiber. |
| 445 |
*/ |
| 446 |
static void yield() nothrow @nogc |
| 447 |
{ |
| 448 |
FiberBase cur = getThis(); |
| 449 |
assert( cur, "Fiber.yield() called with no active fiber" ); |
| 450 |
assert( cur.m_state == State.EXEC ); |
| 451 |
|
| 452 |
static if ( __traits( compiles, ucontext_t ) ) |
| 453 |
cur.m_ucur = &cur.m_utxt; |
| 454 |
|
| 455 |
cur.m_state = State.HOLD; |
| 456 |
cur.switchOut(); |
| 457 |
cur.m_state = State.EXEC; |
| 458 |
} |
| 459 |
|
| 460 |
|
| 461 |
/** |
| 462 |
* Forces a context switch to occur away from the calling fiber and then |
| 463 |
* throws obj in the calling fiber. |
| 464 |
* |
| 465 |
* Params: |
| 466 |
* t = The object to throw. |
| 467 |
* |
| 468 |
* In: |
| 469 |
* t must not be null. |
| 470 |
*/ |
| 471 |
static void yieldAndThrow( Throwable t ) nothrow @nogc |
| 472 |
in |
| 473 |
{ |
| 474 |
assert( t ); |
| 475 |
} |
| 476 |
do |
| 477 |
{ |
| 478 |
FiberBase cur = getThis(); |
| 479 |
assert( cur, "Fiber.yield() called with no active fiber" ); |
| 480 |
assert( cur.m_state == State.EXEC ); |
| 481 |
|
| 482 |
static if ( __traits( compiles, ucontext_t ) ) |
| 483 |
cur.m_ucur = &cur.m_utxt; |
| 484 |
|
| 485 |
cur.m_unhandled = t; |
| 486 |
cur.m_state = State.HOLD; |
| 487 |
cur.switchOut(); |
| 488 |
cur.m_state = State.EXEC; |
| 489 |
} |
| 490 |
|
| 491 |
|
| 492 |
/////////////////////////////////////////////////////////////////////////// |
| 493 |
// Fiber Accessors |
| 494 |
/////////////////////////////////////////////////////////////////////////// |
| 495 |
|
| 496 |
|
| 497 |
/** |
| 498 |
* Provides a reference to the calling fiber or null if no fiber is |
| 499 |
* currently active. |
| 500 |
* |
| 501 |
* Returns: |
| 502 |
* The fiber object representing the calling fiber or null if no fiber |
| 503 |
* is currently active within this thread. The result of deleting this object is undefined. |
| 504 |
*/ |
| 505 |
static FiberBase getThis() @safe nothrow @nogc |
| 506 |
{ |
| 507 |
version (GNU) pragma(inline, false); |
| 508 |
return sm_this; |
| 509 |
} |
| 510 |
|
| 511 |
|
| 512 |
private: |
| 513 |
|
| 514 |
// |
| 515 |
// Fiber entry point. Invokes the function or delegate passed on |
| 516 |
// construction (if any). |
| 517 |
// |
| 518 |
final void run() |
| 519 |
{ |
| 520 |
m_call(); |
| 521 |
} |
| 522 |
|
| 523 |
// |
| 524 |
// Standard fiber data |
| 525 |
// |
| 526 |
Callable m_call; |
| 527 |
bool m_isRunning; |
| 528 |
Throwable m_unhandled; |
| 529 |
State m_state; |
| 530 |
|
| 531 |
|
| 532 |
protected: |
| 533 |
/////////////////////////////////////////////////////////////////////////// |
| 534 |
// Stack Management |
| 535 |
/////////////////////////////////////////////////////////////////////////// |
| 536 |
|
| 537 |
|
| 538 |
// |
| 539 |
// Allocate a new stack for this fiber. |
| 540 |
// |
| 541 |
abstract void allocStack( size_t sz, size_t guardPageSize ) nothrow; |
| 542 |
|
| 543 |
|
| 544 |
// |
| 545 |
// Free this fiber's stack. |
| 546 |
// |
| 547 |
abstract void freeStack() nothrow @nogc; |
| 548 |
|
| 549 |
|
| 550 |
// |
| 551 |
// Initialize the allocated stack. |
| 552 |
// Look above the definition of 'class Fiber' for some information about the implementation of this routine |
| 553 |
// |
| 554 |
abstract void initStack() nothrow @nogc; |
| 555 |
|
| 556 |
|
| 557 |
StackContext* m_ctxt; |
| 558 |
size_t m_size; |
| 559 |
void* m_pmem; |
| 560 |
|
| 561 |
static if ( __traits( compiles, ucontext_t ) ) |
| 562 |
{ |
| 563 |
// NOTE: The static ucontext instance is used to represent the context |
| 564 |
// of the executing thread. |
| 565 |
static ucontext_t sm_utxt = void; |
| 566 |
ucontext_t m_utxt = void; |
| 567 |
package ucontext_t* m_ucur = null; |
| 568 |
} |
| 569 |
else static if (GNU_Enable_CET) |
| 570 |
{ |
| 571 |
// When libphobos was built with --enable-cet, these fields need to |
| 572 |
// always be present in the Fiber class layout. |
| 573 |
import core.sys.posix.ucontext; |
| 574 |
static ucontext_t sm_utxt = void; |
| 575 |
ucontext_t m_utxt = void; |
| 576 |
package ucontext_t* m_ucur = null; |
| 577 |
} |
| 578 |
|
| 579 |
|
| 580 |
private: |
| 581 |
/////////////////////////////////////////////////////////////////////////// |
| 582 |
// Storage of Active Fiber |
| 583 |
/////////////////////////////////////////////////////////////////////////// |
| 584 |
|
| 585 |
|
| 586 |
// |
| 587 |
// Sets a thread-local reference to the current fiber object. |
| 588 |
// |
| 589 |
static void setThis( FiberBase f ) nothrow @nogc |
| 590 |
{ |
| 591 |
sm_this = f; |
| 592 |
} |
| 593 |
|
| 594 |
static FiberBase sm_this; |
| 595 |
|
| 596 |
|
| 597 |
private: |
| 598 |
/////////////////////////////////////////////////////////////////////////// |
| 599 |
// Context Switching |
| 600 |
/////////////////////////////////////////////////////////////////////////// |
| 601 |
|
| 602 |
|
| 603 |
// |
| 604 |
// Switches into the stack held by this fiber. |
| 605 |
// |
| 606 |
final void switchIn() nothrow @nogc |
| 607 |
{ |
| 608 |
ThreadBase tobj = ThreadBase.getThis(); |
| 609 |
void** oldp = &tobj.m_curr.tstack; |
| 610 |
void* newp = m_ctxt.tstack; |
| 611 |
|
| 612 |
// NOTE: The order of operations here is very important. The current |
| 613 |
// stack top must be stored before m_lock is set, and pushContext |
| 614 |
// must not be called until after m_lock is set. This process |
| 615 |
// is intended to prevent a race condition with the suspend |
| 616 |
// mechanism used for garbage collection. If it is not followed, |
| 617 |
// a badly timed collection could cause the GC to scan from the |
| 618 |
// bottom of one stack to the top of another, or to miss scanning |
| 619 |
// a stack that still contains valid data. The old stack pointer |
| 620 |
// oldp will be set again before the context switch to guarantee |
| 621 |
// that it points to exactly the correct stack location so the |
| 622 |
// successive pop operations will succeed. |
| 623 |
*oldp = getStackTop(); |
| 624 |
atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, true); |
| 625 |
tobj.pushContext( m_ctxt ); |
| 626 |
|
| 627 |
fiber_switchContext( oldp, newp ); |
| 628 |
|
| 629 |
// NOTE: As above, these operations must be performed in a strict order |
| 630 |
// to prevent Bad Things from happening. |
| 631 |
tobj.popContext(); |
| 632 |
atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, false); |
| 633 |
tobj.m_curr.tstack = tobj.m_curr.bstack; |
| 634 |
} |
| 635 |
|
| 636 |
|
| 637 |
// |
| 638 |
// Switches out of the current stack and into the enclosing stack. |
| 639 |
// |
| 640 |
final void switchOut() nothrow @nogc |
| 641 |
{ |
| 642 |
ThreadBase tobj = ThreadBase.getThis(); |
| 643 |
void** oldp = &m_ctxt.tstack; |
| 644 |
void* newp = tobj.m_curr.within.tstack; |
| 645 |
|
| 646 |
// NOTE: The order of operations here is very important. The current |
| 647 |
// stack top must be stored before m_lock is set, and pushContext |
| 648 |
// must not be called until after m_lock is set. This process |
| 649 |
// is intended to prevent a race condition with the suspend |
| 650 |
// mechanism used for garbage collection. If it is not followed, |
| 651 |
// a badly timed collection could cause the GC to scan from the |
| 652 |
// bottom of one stack to the top of another, or to miss scanning |
| 653 |
// a stack that still contains valid data. The old stack pointer |
| 654 |
// oldp will be set again before the context switch to guarantee |
| 655 |
// that it points to exactly the correct stack location so the |
| 656 |
// successive pop operations will succeed. |
| 657 |
*oldp = getStackTop(); |
| 658 |
atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, true); |
| 659 |
|
| 660 |
fiber_switchContext( oldp, newp ); |
| 661 |
|
| 662 |
// NOTE: As above, these operations must be performed in a strict order |
| 663 |
// to prevent Bad Things from happening. |
| 664 |
// NOTE: If use of this fiber is multiplexed across threads, the thread |
| 665 |
// executing here may be different from the one above, so get the |
| 666 |
// current thread handle before unlocking, etc. |
| 667 |
tobj = ThreadBase.getThis(); |
| 668 |
atomicStore!(MemoryOrder.raw)(*cast(shared)&tobj.m_lock, false); |
| 669 |
tobj.m_curr.tstack = tobj.m_curr.bstack; |
| 670 |
} |
| 671 |
} |
| 672 |
|
| 673 |
/// |
| 674 |
unittest { |
| 675 |
int counter; |
| 676 |
|
| 677 |
class DerivedFiber : Fiber |
| 678 |
{ |
| 679 |
this() |
| 680 |
{ |
| 681 |
super( &run ); |
| 682 |
} |
| 683 |
|
| 684 |
private : |
| 685 |
void run() |
| 686 |
{ |
| 687 |
counter += 2; |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
void fiberFunc() |
| 692 |
{ |
| 693 |
counter += 4; |
| 694 |
Fiber.yield(); |
| 695 |
counter += 8; |
| 696 |
} |
| 697 |
|
| 698 |
// create instances of each type |
| 699 |
Fiber derived = new DerivedFiber(); |
| 700 |
Fiber composed = new Fiber( &fiberFunc ); |
| 701 |
|
| 702 |
assert( counter == 0 ); |
| 703 |
|
| 704 |
derived.call(); |
| 705 |
assert( counter == 2, "Derived fiber increment." ); |
| 706 |
|
| 707 |
composed.call(); |
| 708 |
assert( counter == 6, "First composed fiber increment." ); |
| 709 |
|
| 710 |
counter += 16; |
| 711 |
assert( counter == 22, "Calling context increment." ); |
| 712 |
|
| 713 |
composed.call(); |
| 714 |
assert( counter == 30, "Second composed fiber increment." ); |
| 715 |
|
| 716 |
// since each fiber has run to completion, each should have state TERM |
| 717 |
assert( derived.state == Fiber.State.TERM ); |
| 718 |
assert( composed.state == Fiber.State.TERM ); |
| 719 |
} |
| 720 |
|
| 721 |
version (unittest) |
| 722 |
{ |
| 723 |
import core.thread.fiber: Fiber; |
| 724 |
} |
| 725 |
|
| 726 |
version (CoreUnittest) |
| 727 |
{ |
| 728 |
class TestFiber : Fiber |
| 729 |
{ |
| 730 |
this() |
| 731 |
{ |
| 732 |
super(&run); |
| 733 |
} |
| 734 |
|
| 735 |
void run() |
| 736 |
{ |
| 737 |
foreach (i; 0 .. 1000) |
| 738 |
{ |
| 739 |
sum += i; |
| 740 |
Fiber.yield(); |
| 741 |
} |
| 742 |
} |
| 743 |
|
| 744 |
enum expSum = 1000 * 999 / 2; |
| 745 |
size_t sum; |
| 746 |
} |
| 747 |
|
| 748 |
void runTen() |
| 749 |
{ |
| 750 |
TestFiber[10] fibs; |
| 751 |
foreach (ref fib; fibs) |
| 752 |
fib = new TestFiber(); |
| 753 |
|
| 754 |
bool cont; |
| 755 |
do { |
| 756 |
cont = false; |
| 757 |
foreach (fib; fibs) { |
| 758 |
if (fib.state == Fiber.State.HOLD) |
| 759 |
{ |
| 760 |
fib.call(); |
| 761 |
cont |= fib.state != Fiber.State.TERM; |
| 762 |
} |
| 763 |
} |
| 764 |
} while (cont); |
| 765 |
|
| 766 |
foreach (fib; fibs) |
| 767 |
{ |
| 768 |
assert(fib.sum == TestFiber.expSum); |
| 769 |
} |
| 770 |
} |
| 771 |
} |
| 772 |
|
| 773 |
|
| 774 |
// Single thread running separate fibers |
| 775 |
unittest |
| 776 |
{ |
| 777 |
runTen(); |
| 778 |
} |
| 779 |
|
| 780 |
|
| 781 |
// Multiple threads running separate fibers |
| 782 |
unittest |
| 783 |
{ |
| 784 |
auto group = new ThreadGroup(); |
| 785 |
foreach (_; 0 .. 4) |
| 786 |
{ |
| 787 |
group.create(&runTen); |
| 788 |
} |
| 789 |
group.joinAll(); |
| 790 |
} |
| 791 |
|
| 792 |
|
| 793 |
// Multiple threads running shared fibers |
| 794 |
version (PPC) version = UnsafeFiberMigration; |
| 795 |
version (PPC64) version = UnsafeFiberMigration; |
| 796 |
version (OSX) |
| 797 |
{ |
| 798 |
version (X86) version = UnsafeFiberMigration; |
| 799 |
version (X86_64) version = UnsafeFiberMigration; |
| 800 |
version (AArch64) version = UnsafeFiberMigration; |
| 801 |
} |
| 802 |
|
| 803 |
version (UnsafeFiberMigration) |
| 804 |
{ |
| 805 |
// XBUG: core.thread fibers are supposed to be safe to migrate across |
| 806 |
// threads, however, there is a problem: GCC always assumes that the |
| 807 |
// address of thread-local variables don't change while on a given stack. |
| 808 |
// In consequence, migrating fibers between threads currently is an unsafe |
| 809 |
// thing to do, and will break on some targets (possibly PR26461). |
| 810 |
} |
| 811 |
else |
| 812 |
{ |
| 813 |
version = FiberMigrationUnittest; |
| 814 |
} |
| 815 |
|
| 816 |
version (FiberMigrationUnittest) |
| 817 |
unittest |
| 818 |
{ |
| 819 |
shared bool[10] locks; |
| 820 |
TestFiber[10] fibs; |
| 821 |
|
| 822 |
void runShared() |
| 823 |
{ |
| 824 |
bool cont; |
| 825 |
do { |
| 826 |
cont = false; |
| 827 |
foreach (idx; 0 .. 10) |
| 828 |
{ |
| 829 |
if (cas(&locks[idx], false, true)) |
| 830 |
{ |
| 831 |
if (fibs[idx].state == Fiber.State.HOLD) |
| 832 |
{ |
| 833 |
fibs[idx].call(); |
| 834 |
cont |= fibs[idx].state != Fiber.State.TERM; |
| 835 |
} |
| 836 |
locks[idx] = false; |
| 837 |
} |
| 838 |
else |
| 839 |
{ |
| 840 |
cont = true; |
| 841 |
} |
| 842 |
} |
| 843 |
} while (cont); |
| 844 |
} |
| 845 |
|
| 846 |
foreach (ref fib; fibs) |
| 847 |
{ |
| 848 |
fib = new TestFiber(); |
| 849 |
} |
| 850 |
|
| 851 |
auto group = new ThreadGroup(); |
| 852 |
foreach (_; 0 .. 4) |
| 853 |
{ |
| 854 |
group.create(&runShared); |
| 855 |
} |
| 856 |
group.joinAll(); |
| 857 |
|
| 858 |
foreach (fib; fibs) |
| 859 |
{ |
| 860 |
assert(fib.sum == TestFiber.expSum); |
| 861 |
} |
| 862 |
} |
| 863 |
|
| 864 |
|
| 865 |
// Test exception handling inside fibers. |
| 866 |
unittest |
| 867 |
{ |
| 868 |
enum MSG = "Test message."; |
| 869 |
string caughtMsg; |
| 870 |
(new Fiber({ |
| 871 |
try |
| 872 |
{ |
| 873 |
throw new Exception(MSG); |
| 874 |
} |
| 875 |
catch (Exception e) |
| 876 |
{ |
| 877 |
caughtMsg = e.msg; |
| 878 |
} |
| 879 |
})).call(); |
| 880 |
assert(caughtMsg == MSG); |
| 881 |
} |
| 882 |
|
| 883 |
|
| 884 |
unittest |
| 885 |
{ |
| 886 |
int x = 0; |
| 887 |
|
| 888 |
(new Fiber({ |
| 889 |
x++; |
| 890 |
})).call(); |
| 891 |
assert( x == 1 ); |
| 892 |
} |
| 893 |
|
| 894 |
nothrow unittest |
| 895 |
{ |
| 896 |
new Fiber({}).call!(Fiber.Rethrow.no)(); |
| 897 |
} |
| 898 |
|
| 899 |
unittest |
| 900 |
{ |
| 901 |
new Fiber({}).call(Fiber.Rethrow.yes); |
| 902 |
new Fiber({}).call(Fiber.Rethrow.no); |
| 903 |
} |
| 904 |
|
| 905 |
unittest |
| 906 |
{ |
| 907 |
enum MSG = "Test message."; |
| 908 |
|
| 909 |
try |
| 910 |
{ |
| 911 |
(new Fiber(function() { |
| 912 |
throw new Exception( MSG ); |
| 913 |
})).call(); |
| 914 |
assert( false, "Expected rethrown exception." ); |
| 915 |
} |
| 916 |
catch ( Throwable t ) |
| 917 |
{ |
| 918 |
assert( t.msg == MSG ); |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
// Test exception chaining when switching contexts in finally blocks. |
| 923 |
unittest |
| 924 |
{ |
| 925 |
static void throwAndYield(string msg) { |
| 926 |
try { |
| 927 |
throw new Exception(msg); |
| 928 |
} finally { |
| 929 |
Fiber.yield(); |
| 930 |
} |
| 931 |
} |
| 932 |
|
| 933 |
static void fiber(string name) { |
| 934 |
try { |
| 935 |
try { |
| 936 |
throwAndYield(name ~ ".1"); |
| 937 |
} finally { |
| 938 |
throwAndYield(name ~ ".2"); |
| 939 |
} |
| 940 |
} catch (Exception e) { |
| 941 |
assert(e.msg == name ~ ".1"); |
| 942 |
assert(e.next); |
| 943 |
assert(e.next.msg == name ~ ".2"); |
| 944 |
assert(!e.next.next); |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
auto first = new Fiber(() => fiber("first")); |
| 949 |
auto second = new Fiber(() => fiber("second")); |
| 950 |
first.call(); |
| 951 |
second.call(); |
| 952 |
first.call(); |
| 953 |
second.call(); |
| 954 |
first.call(); |
| 955 |
second.call(); |
| 956 |
assert(first.state == Fiber.State.TERM); |
| 957 |
assert(second.state == Fiber.State.TERM); |
| 958 |
} |
| 959 |
|
| 960 |
// Test Fiber resetting |
| 961 |
unittest |
| 962 |
{ |
| 963 |
static string method; |
| 964 |
|
| 965 |
static void foo() |
| 966 |
{ |
| 967 |
method = "foo"; |
| 968 |
} |
| 969 |
|
| 970 |
void bar() |
| 971 |
{ |
| 972 |
method = "bar"; |
| 973 |
} |
| 974 |
|
| 975 |
static void expect(Fiber fib, string s) |
| 976 |
{ |
| 977 |
assert(fib.state == Fiber.State.HOLD); |
| 978 |
fib.call(); |
| 979 |
assert(fib.state == Fiber.State.TERM); |
| 980 |
assert(method == s); method = null; |
| 981 |
} |
| 982 |
auto fib = new Fiber(&foo); |
| 983 |
expect(fib, "foo"); |
| 984 |
|
| 985 |
fib.reset(); |
| 986 |
expect(fib, "foo"); |
| 987 |
|
| 988 |
fib.reset(&foo); |
| 989 |
expect(fib, "foo"); |
| 990 |
|
| 991 |
fib.reset(&bar); |
| 992 |
expect(fib, "bar"); |
| 993 |
|
| 994 |
fib.reset(function void(){method = "function";}); |
| 995 |
expect(fib, "function"); |
| 996 |
|
| 997 |
fib.reset(delegate void(){method = "delegate";}); |
| 998 |
expect(fib, "delegate"); |
| 999 |
} |
| 1000 |
|
| 1001 |
// Test unsafe reset in hold state |
| 1002 |
unittest |
| 1003 |
{ |
| 1004 |
auto fib = new Fiber(function {ubyte[2048] buf = void; Fiber.yield();}, 4096); |
| 1005 |
foreach (_; 0 .. 10) |
| 1006 |
{ |
| 1007 |
fib.call(); |
| 1008 |
assert(fib.state == Fiber.State.HOLD); |
| 1009 |
fib.reset(); |
| 1010 |
} |
| 1011 |
} |
| 1012 |
|
| 1013 |
// stress testing GC stack scanning |
| 1014 |
unittest |
| 1015 |
{ |
| 1016 |
import core.memory; |
| 1017 |
import core.thread.osthread : Thread; |
| 1018 |
import core.time : dur; |
| 1019 |
|
| 1020 |
static void unreferencedThreadObject() |
| 1021 |
{ |
| 1022 |
static void sleep() { Thread.sleep(dur!"msecs"(100)); } |
| 1023 |
auto thread = new Thread(&sleep).start(); |
| 1024 |
} |
| 1025 |
unreferencedThreadObject(); |
| 1026 |
GC.collect(); |
| 1027 |
|
| 1028 |
static class Foo |
| 1029 |
{ |
| 1030 |
this(int value) |
| 1031 |
{ |
| 1032 |
_value = value; |
| 1033 |
} |
| 1034 |
|
| 1035 |
int bar() |
| 1036 |
{ |
| 1037 |
return _value; |
| 1038 |
} |
| 1039 |
|
| 1040 |
int _value; |
| 1041 |
} |
| 1042 |
|
| 1043 |
static void collect() |
| 1044 |
{ |
| 1045 |
auto foo = new Foo(2); |
| 1046 |
assert(foo.bar() == 2); |
| 1047 |
GC.collect(); |
| 1048 |
Fiber.yield(); |
| 1049 |
GC.collect(); |
| 1050 |
assert(foo.bar() == 2); |
| 1051 |
} |
| 1052 |
|
| 1053 |
auto fiber = new Fiber(&collect); |
| 1054 |
|
| 1055 |
fiber.call(); |
| 1056 |
GC.collect(); |
| 1057 |
fiber.call(); |
| 1058 |
|
| 1059 |
// thread reference |
| 1060 |
auto foo = new Foo(2); |
| 1061 |
|
| 1062 |
void collect2() |
| 1063 |
{ |
| 1064 |
assert(foo.bar() == 2); |
| 1065 |
GC.collect(); |
| 1066 |
Fiber.yield(); |
| 1067 |
GC.collect(); |
| 1068 |
assert(foo.bar() == 2); |
| 1069 |
} |
| 1070 |
|
| 1071 |
fiber = new Fiber(&collect2); |
| 1072 |
|
| 1073 |
fiber.call(); |
| 1074 |
GC.collect(); |
| 1075 |
fiber.call(); |
| 1076 |
|
| 1077 |
static void recurse(size_t cnt) |
| 1078 |
{ |
| 1079 |
--cnt; |
| 1080 |
Fiber.yield(); |
| 1081 |
if (cnt) |
| 1082 |
{ |
| 1083 |
auto fib = new Fiber(() { recurse(cnt); }); |
| 1084 |
fib.call(); |
| 1085 |
GC.collect(); |
| 1086 |
fib.call(); |
| 1087 |
} |
| 1088 |
} |
| 1089 |
fiber = new Fiber(() { recurse(20); }); |
| 1090 |
fiber.call(); |
| 1091 |
} |