| 1 |
/** |
| 2 |
* Contains the garbage collector implementation. |
| 3 |
* |
| 4 |
* Copyright: D Language Foundation 2001 - 2021. |
| 5 |
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0). |
| 6 |
* Authors: Walter Bright, David Friedman, Sean Kelly |
| 7 |
*/ |
| 8 |
module core.internal.gc.impl.conservative.gc; |
| 9 |
|
| 10 |
// D Programming Language Garbage Collector implementation |
| 11 |
|
| 12 |
/************** Debugging ***************************/ |
| 13 |
|
| 14 |
//debug = PRINTF; // turn on printf's |
| 15 |
//debug = PARALLEL_PRINTF; // turn on printf's |
| 16 |
//debug = COLLECT_PRINTF; // turn on printf's |
| 17 |
//debug = MARK_PRINTF; // turn on printf's |
| 18 |
//debug = PRINTF_TO_FILE; // redirect printf's output to file "gcx.log" |
| 19 |
//debug = LOGGING; // log allocations / frees |
| 20 |
//debug = MEMSTOMP; // stomp on memory |
| 21 |
//debug = SENTINEL; // add underrun/overrrun protection |
| 22 |
// NOTE: this needs to be enabled globally in the makefiles |
| 23 |
// (-debug=SENTINEL) to pass druntime's unittests. |
| 24 |
//debug = PTRCHECK; // more pointer checking |
| 25 |
//debug = PTRCHECK2; // thorough but slow pointer checking |
| 26 |
//debug = INVARIANT; // enable invariants |
| 27 |
//debug = PROFILE_API; // profile API calls for config.profile > 1 |
| 28 |
//debug = GC_RECURSIVE_LOCK; // check for recursive locking on the same thread |
| 29 |
//debug = VALGRIND; // Valgrind memcheck integration |
| 30 |
|
| 31 |
/***************************************************/ |
| 32 |
version = COLLECT_PARALLEL; // parallel scanning |
| 33 |
version (Posix) |
| 34 |
version = COLLECT_FORK; |
| 35 |
|
| 36 |
import core.internal.gc.bits; |
| 37 |
import core.internal.gc.os; |
| 38 |
import core.gc.config; |
| 39 |
import core.gc.gcinterface; |
| 40 |
|
| 41 |
import core.internal.container.treap; |
| 42 |
import core.internal.spinlock; |
| 43 |
import core.internal.gc.pooltable; |
| 44 |
import core.internal.gc.blkcache; |
| 45 |
|
| 46 |
import cstdlib = core.stdc.stdlib; |
| 47 |
import core.stdc.string : memcpy, memset, memmove; |
| 48 |
import core.bitop; |
| 49 |
import core.thread; |
| 50 |
static import core.memory; |
| 51 |
|
| 52 |
version (GNU) import gcc.builtins; |
| 53 |
|
| 54 |
debug (PRINTF_TO_FILE) import core.stdc.stdio : sprintf, fprintf, fopen, fflush, FILE; |
| 55 |
else import core.stdc.stdio : sprintf, printf; // needed to output profiling results |
| 56 |
|
| 57 |
debug (VALGRIND) import etc.valgrind.valgrind; |
| 58 |
|
| 59 |
import core.time; |
| 60 |
alias currTime = MonoTime.currTime; |
| 61 |
|
| 62 |
// Track total time spent preparing for GC, |
| 63 |
// marking, sweeping and recovering pages. |
| 64 |
__gshared Duration prepTime; |
| 65 |
__gshared Duration markTime; |
| 66 |
__gshared Duration sweepTime; |
| 67 |
__gshared Duration pauseTime; |
| 68 |
__gshared Duration maxPauseTime; |
| 69 |
__gshared Duration maxCollectionTime; |
| 70 |
__gshared size_t numCollections; |
| 71 |
__gshared size_t maxPoolMemory; |
| 72 |
|
| 73 |
__gshared long numMallocs; |
| 74 |
__gshared long numFrees; |
| 75 |
__gshared long numReallocs; |
| 76 |
__gshared long numExtends; |
| 77 |
__gshared long numOthers; |
| 78 |
__gshared long mallocTime; // using ticks instead of MonoTime for better performance |
| 79 |
__gshared long freeTime; |
| 80 |
__gshared long reallocTime; |
| 81 |
__gshared long extendTime; |
| 82 |
__gshared long otherTime; |
| 83 |
__gshared long lockTime; |
| 84 |
|
| 85 |
ulong bytesAllocated; // thread local counter |
| 86 |
|
| 87 |
private |
| 88 |
{ |
| 89 |
extern (C) |
| 90 |
{ |
| 91 |
// to allow compilation of this module without access to the rt package, |
| 92 |
// make these functions available from rt.lifetime |
| 93 |
void rt_finalizeFromGC(void* p, size_t size, uint attr, const(TypeInfo) typeInfo) nothrow; |
| 94 |
int rt_hasFinalizerInSegment(void* p, size_t size, const(TypeInfo) typeInfo, const scope void[] segment) nothrow; |
| 95 |
|
| 96 |
// Declared as an extern instead of importing core.exception |
| 97 |
// to avoid inlining - see https://issues.dlang.org/show_bug.cgi?id=13725. |
| 98 |
noreturn onInvalidMemoryOperationError(void* pretend_sideffect = null, string file = __FILE__, size_t line = __LINE__) @trusted pure nothrow @nogc; |
| 99 |
noreturn onOutOfMemoryError(void* pretend_sideffect = null, string file = __FILE__, size_t line = __LINE__) @trusted pure nothrow @nogc; |
| 100 |
|
| 101 |
version (COLLECT_FORK) |
| 102 |
version (OSX) |
| 103 |
pid_t __fork() nothrow; |
| 104 |
} |
| 105 |
|
| 106 |
enum |
| 107 |
{ |
| 108 |
OPFAIL = ~cast(size_t)0 |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
alias GC gc_t; |
| 113 |
|
| 114 |
/* ============================ GC =============================== */ |
| 115 |
|
| 116 |
// register GC in C constructor (_STI_) |
| 117 |
private pragma(crt_constructor) void gc_conservative_ctor() |
| 118 |
{ |
| 119 |
_d_register_conservative_gc(); |
| 120 |
} |
| 121 |
|
| 122 |
extern(C) void _d_register_conservative_gc() |
| 123 |
{ |
| 124 |
import core.gc.registry; |
| 125 |
registerGCFactory("conservative", &initialize); |
| 126 |
} |
| 127 |
|
| 128 |
private pragma(crt_constructor) void gc_precise_ctor() |
| 129 |
{ |
| 130 |
_d_register_precise_gc(); |
| 131 |
} |
| 132 |
|
| 133 |
extern(C) void _d_register_precise_gc() |
| 134 |
{ |
| 135 |
import core.gc.registry; |
| 136 |
registerGCFactory("precise", &initialize_precise); |
| 137 |
} |
| 138 |
|
| 139 |
private GC initialize() |
| 140 |
{ |
| 141 |
import core.lifetime : emplace; |
| 142 |
|
| 143 |
auto gc = cast(ConservativeGC) cstdlib.malloc(__traits(classInstanceSize, ConservativeGC)); |
| 144 |
if (!gc) |
| 145 |
onOutOfMemoryError(); |
| 146 |
|
| 147 |
return emplace(gc); |
| 148 |
} |
| 149 |
|
| 150 |
private GC initialize_precise() |
| 151 |
{ |
| 152 |
ConservativeGC.isPrecise = true; |
| 153 |
return initialize(); |
| 154 |
} |
| 155 |
|
| 156 |
class ConservativeGC : GC |
| 157 |
{ |
| 158 |
// For passing to debug code (not thread safe) |
| 159 |
__gshared size_t line; |
| 160 |
__gshared char* file; |
| 161 |
|
| 162 |
Gcx *gcx; // implementation |
| 163 |
|
| 164 |
static gcLock = shared(AlignedSpinLock)(SpinLock.Contention.brief); |
| 165 |
static bool _inFinalizer; |
| 166 |
__gshared bool isPrecise = false; |
| 167 |
|
| 168 |
/* |
| 169 |
* Lock the GC. |
| 170 |
* |
| 171 |
* Throws: InvalidMemoryOperationError on recursive locking during finalization. |
| 172 |
*/ |
| 173 |
static void lockNR() @safe @nogc nothrow |
| 174 |
{ |
| 175 |
if (_inFinalizer) |
| 176 |
onInvalidMemoryOperationError(); |
| 177 |
gcLock.lock(); |
| 178 |
} |
| 179 |
|
| 180 |
/* |
| 181 |
* Initialize the GC based on command line configuration. |
| 182 |
* |
| 183 |
* Throws: |
| 184 |
* OutOfMemoryError if failed to initialize GC due to not enough memory. |
| 185 |
*/ |
| 186 |
this() |
| 187 |
{ |
| 188 |
//config is assumed to have already been initialized |
| 189 |
|
| 190 |
gcx = cast(Gcx*)cstdlib.calloc(1, Gcx.sizeof); |
| 191 |
if (!gcx) |
| 192 |
onOutOfMemoryError(); |
| 193 |
gcx.initialize(); |
| 194 |
|
| 195 |
if (config.initReserve) |
| 196 |
gcx.reserve(config.initReserve); |
| 197 |
if (config.disable) |
| 198 |
gcx.disabled++; |
| 199 |
} |
| 200 |
|
| 201 |
|
| 202 |
~this() |
| 203 |
{ |
| 204 |
version (linux) |
| 205 |
{ |
| 206 |
//debug(PRINTF) printf("Thread %x ", pthread_self()); |
| 207 |
//debug(PRINTF) printf("GC.Dtor()\n"); |
| 208 |
} |
| 209 |
|
| 210 |
if (gcx) |
| 211 |
{ |
| 212 |
gcx.Dtor(); |
| 213 |
cstdlib.free(gcx); |
| 214 |
gcx = null; |
| 215 |
} |
| 216 |
// TODO: cannot free as memory is overwritten and |
| 217 |
// the monitor is still read in rt_finalize (called by destroy) |
| 218 |
// cstdlib.free(cast(void*) this); |
| 219 |
} |
| 220 |
|
| 221 |
|
| 222 |
/** |
| 223 |
* Enables the GC if disable() was previously called. Must be called |
| 224 |
* for each time disable was called in order to enable the GC again. |
| 225 |
*/ |
| 226 |
void enable() |
| 227 |
{ |
| 228 |
static void go(Gcx* gcx) nothrow |
| 229 |
{ |
| 230 |
assert(gcx.disabled > 0); |
| 231 |
gcx.disabled--; |
| 232 |
} |
| 233 |
runLocked!(go, otherTime, numOthers)(gcx); |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
/** |
| 238 |
* Disable the GC. The GC may still run if it deems necessary. |
| 239 |
*/ |
| 240 |
void disable() |
| 241 |
{ |
| 242 |
static void go(Gcx* gcx) nothrow |
| 243 |
{ |
| 244 |
gcx.disabled++; |
| 245 |
} |
| 246 |
runLocked!(go, otherTime, numOthers)(gcx); |
| 247 |
} |
| 248 |
|
| 249 |
debug (GC_RECURSIVE_LOCK) static bool lockedOnThisThread; |
| 250 |
|
| 251 |
/** |
| 252 |
* Run a function inside a lock/unlock set. |
| 253 |
* |
| 254 |
* Params: |
| 255 |
* func = The function to run. |
| 256 |
* args = The function arguments. |
| 257 |
*/ |
| 258 |
auto runLocked(alias func, Args...)(auto ref Args args) |
| 259 |
{ |
| 260 |
debug(PROFILE_API) immutable tm = (config.profile > 1 ? currTime.ticks : 0); |
| 261 |
debug(GC_RECURSIVE_LOCK) |
| 262 |
{ |
| 263 |
if (lockedOnThisThread) |
| 264 |
onInvalidMemoryOperationError(); |
| 265 |
lockedOnThisThread = true; |
| 266 |
} |
| 267 |
lockNR(); |
| 268 |
scope (failure) gcLock.unlock(); |
| 269 |
debug(PROFILE_API) immutable tm2 = (config.profile > 1 ? currTime.ticks : 0); |
| 270 |
|
| 271 |
static if (is(typeof(func(args)) == void)) |
| 272 |
func(args); |
| 273 |
else |
| 274 |
auto res = func(args); |
| 275 |
|
| 276 |
debug(PROFILE_API) if (config.profile > 1) |
| 277 |
lockTime += tm2 - tm; |
| 278 |
gcLock.unlock(); |
| 279 |
debug(GC_RECURSIVE_LOCK) |
| 280 |
{ |
| 281 |
if (!lockedOnThisThread) |
| 282 |
onInvalidMemoryOperationError(); |
| 283 |
lockedOnThisThread = false; |
| 284 |
} |
| 285 |
|
| 286 |
static if (!is(typeof(func(args)) == void)) |
| 287 |
return res; |
| 288 |
} |
| 289 |
|
| 290 |
/** |
| 291 |
* Run a function in an lock/unlock set that keeps track of |
| 292 |
* how much time was spend inside this function (in ticks) |
| 293 |
* and how many times this fuction was called. |
| 294 |
* |
| 295 |
* Params: |
| 296 |
* func = The function to run. |
| 297 |
* time = The variable keeping track of the time (in ticks). |
| 298 |
* count = The variable keeping track of how many times this fuction was called. |
| 299 |
* args = The function arguments. |
| 300 |
*/ |
| 301 |
auto runLocked(alias func, alias time, alias count, Args...)(auto ref Args args) |
| 302 |
{ |
| 303 |
debug(PROFILE_API) immutable tm = (config.profile > 1 ? currTime.ticks : 0); |
| 304 |
debug(GC_RECURSIVE_LOCK) |
| 305 |
{ |
| 306 |
if (lockedOnThisThread) |
| 307 |
onInvalidMemoryOperationError(); |
| 308 |
lockedOnThisThread = true; |
| 309 |
} |
| 310 |
lockNR(); |
| 311 |
scope (failure) gcLock.unlock(); |
| 312 |
debug(PROFILE_API) immutable tm2 = (config.profile > 1 ? currTime.ticks : 0); |
| 313 |
|
| 314 |
static if (is(typeof(func(args)) == void)) |
| 315 |
func(args); |
| 316 |
else |
| 317 |
auto res = func(args); |
| 318 |
|
| 319 |
debug(PROFILE_API) if (config.profile > 1) |
| 320 |
{ |
| 321 |
count++; |
| 322 |
immutable now = currTime.ticks; |
| 323 |
lockTime += tm2 - tm; |
| 324 |
time += now - tm2; |
| 325 |
} |
| 326 |
gcLock.unlock(); |
| 327 |
debug(GC_RECURSIVE_LOCK) |
| 328 |
{ |
| 329 |
if (!lockedOnThisThread) |
| 330 |
onInvalidMemoryOperationError(); |
| 331 |
lockedOnThisThread = false; |
| 332 |
} |
| 333 |
|
| 334 |
static if (!is(typeof(func(args)) == void)) |
| 335 |
return res; |
| 336 |
} |
| 337 |
|
| 338 |
|
| 339 |
/** |
| 340 |
* Returns a bit field representing all block attributes set for the memory |
| 341 |
* referenced by p. |
| 342 |
* |
| 343 |
* Params: |
| 344 |
* p = A pointer to the base of a valid memory block or to null. |
| 345 |
* |
| 346 |
* Returns: |
| 347 |
* A bit field containing any bits set for the memory block referenced by |
| 348 |
* p or zero on error. |
| 349 |
*/ |
| 350 |
uint getAttr(void* p) nothrow |
| 351 |
{ |
| 352 |
if (!p) |
| 353 |
{ |
| 354 |
return 0; |
| 355 |
} |
| 356 |
|
| 357 |
static uint go(Gcx* gcx, void* p) nothrow |
| 358 |
{ |
| 359 |
Pool* pool = gcx.findPool(p); |
| 360 |
uint oldb = 0; |
| 361 |
|
| 362 |
if (pool) |
| 363 |
{ |
| 364 |
p = sentinel_sub(p); |
| 365 |
if (p != pool.findBase(p)) |
| 366 |
return 0; |
| 367 |
auto biti = cast(size_t)(p - pool.baseAddr) >> pool.shiftBy; |
| 368 |
|
| 369 |
oldb = pool.getBits(biti); |
| 370 |
} |
| 371 |
return oldb; |
| 372 |
} |
| 373 |
|
| 374 |
return runLocked!(go, otherTime, numOthers)(gcx, p); |
| 375 |
} |
| 376 |
|
| 377 |
/** |
| 378 |
* Sets the specified bits for the memory references by p. |
| 379 |
* |
| 380 |
* If p was not allocated by the GC, points inside a block, or is null, no |
| 381 |
* action will be taken. |
| 382 |
* |
| 383 |
* Params: |
| 384 |
* p = A pointer to the base of a valid memory block or to null. |
| 385 |
* mask = A bit field containing any bits to set for this memory block. |
| 386 |
* |
| 387 |
* Returns: |
| 388 |
* The result of a call to getAttr after the specified bits have been |
| 389 |
* set. |
| 390 |
*/ |
| 391 |
uint setAttr(void* p, uint mask) nothrow |
| 392 |
{ |
| 393 |
if (!p) |
| 394 |
{ |
| 395 |
return 0; |
| 396 |
} |
| 397 |
|
| 398 |
static uint go(Gcx* gcx, void* p, uint mask) nothrow |
| 399 |
{ |
| 400 |
Pool* pool = gcx.findPool(p); |
| 401 |
uint oldb = 0; |
| 402 |
|
| 403 |
if (pool) |
| 404 |
{ |
| 405 |
p = sentinel_sub(p); |
| 406 |
if (p != pool.findBase(p)) |
| 407 |
return 0; |
| 408 |
const biti = cast(size_t)(p - pool.baseAddr) >> pool.shiftBy; |
| 409 |
|
| 410 |
oldb = pool.getBits(biti); |
| 411 |
pool.setBits(biti, mask); |
| 412 |
} |
| 413 |
return oldb; |
| 414 |
} |
| 415 |
|
| 416 |
return runLocked!(go, otherTime, numOthers)(gcx, p, mask); |
| 417 |
} |
| 418 |
|
| 419 |
|
| 420 |
/** |
| 421 |
* Clears the specified bits for the memory references by p. |
| 422 |
* |
| 423 |
* If p was not allocated by the GC, points inside a block, or is null, no |
| 424 |
* action will be taken. |
| 425 |
* |
| 426 |
* Params: |
| 427 |
* p = A pointer to the base of a valid memory block or to null. |
| 428 |
* mask = A bit field containing any bits to clear for this memory block. |
| 429 |
* |
| 430 |
* Returns: |
| 431 |
* The result of a call to getAttr after the specified bits have been |
| 432 |
* cleared |
| 433 |
*/ |
| 434 |
uint clrAttr(void* p, uint mask) nothrow |
| 435 |
{ |
| 436 |
if (!p) |
| 437 |
{ |
| 438 |
return 0; |
| 439 |
} |
| 440 |
|
| 441 |
static uint go(Gcx* gcx, void* p, uint mask) nothrow |
| 442 |
{ |
| 443 |
Pool* pool = gcx.findPool(p); |
| 444 |
uint oldb = 0; |
| 445 |
|
| 446 |
if (pool) |
| 447 |
{ |
| 448 |
p = sentinel_sub(p); |
| 449 |
if (p != pool.findBase(p)) |
| 450 |
return 0; |
| 451 |
const biti = cast(size_t)(p - pool.baseAddr) >> pool.shiftBy; |
| 452 |
|
| 453 |
oldb = pool.getBits(biti); |
| 454 |
pool.clrBits(biti, mask); |
| 455 |
} |
| 456 |
return oldb; |
| 457 |
} |
| 458 |
|
| 459 |
return runLocked!(go, otherTime, numOthers)(gcx, p, mask); |
| 460 |
} |
| 461 |
|
| 462 |
/** |
| 463 |
* Requests an aligned block of managed memory from the garbage collector. |
| 464 |
* |
| 465 |
* Params: |
| 466 |
* size = The desired allocation size in bytes. |
| 467 |
* bits = A bitmask of the attributes to set on this block. |
| 468 |
* ti = TypeInfo to describe the memory. |
| 469 |
* |
| 470 |
* Returns: |
| 471 |
* A reference to the allocated memory or null if no memory was requested. |
| 472 |
* |
| 473 |
* Throws: |
| 474 |
* OutOfMemoryError on allocation failure |
| 475 |
*/ |
| 476 |
void *malloc(size_t size, uint bits = 0, const TypeInfo ti = null) nothrow |
| 477 |
{ |
| 478 |
import core.internal.gc.blockmeta; |
| 479 |
|
| 480 |
if (size == 0) |
| 481 |
{ |
| 482 |
return null; |
| 483 |
} |
| 484 |
|
| 485 |
adjustAttrs(bits, ti); |
| 486 |
|
| 487 |
immutable padding = __allocPad(size, bits); |
| 488 |
|
| 489 |
bool overflow; |
| 490 |
import core.checkedint : addu; |
| 491 |
immutable needed = addu(size, padding, overflow); |
| 492 |
if (overflow) |
| 493 |
{ |
| 494 |
return null; |
| 495 |
} |
| 496 |
|
| 497 |
size_t localAllocSize = void; |
| 498 |
|
| 499 |
auto p = runLocked!(mallocNoSync, mallocTime, numMallocs)(needed, bits, localAllocSize, ti); |
| 500 |
|
| 501 |
invalidate(p[0 .. localAllocSize], 0xF0, true); |
| 502 |
|
| 503 |
auto ret = setupMetadata(p[0 .. localAllocSize], bits, padding, size, ti); |
| 504 |
|
| 505 |
if (!(bits & BlkAttr.NO_SCAN)) |
| 506 |
{ |
| 507 |
memset(ret.ptr + size, 0, ret.length - size); |
| 508 |
} |
| 509 |
|
| 510 |
return ret.ptr; |
| 511 |
} |
| 512 |
|
| 513 |
|
| 514 |
// |
| 515 |
// Implementation for malloc and calloc. |
| 516 |
// |
| 517 |
private void *mallocNoSync(size_t size, uint bits, ref size_t alloc_size, const TypeInfo ti = null) nothrow |
| 518 |
{ |
| 519 |
assert(size != 0); |
| 520 |
|
| 521 |
debug(PRINTF) |
| 522 |
printf("GC::malloc(gcx = %p, size = %zd bits = %x, ti = %s)\n", gcx, size, bits, debugTypeName(ti).ptr); |
| 523 |
|
| 524 |
assert(gcx); |
| 525 |
//debug(PRINTF) printf("gcx.self = %x, pthread_self() = %x\n", gcx.self, pthread_self()); |
| 526 |
|
| 527 |
auto p = gcx.alloc(size + SENTINEL_EXTRA, alloc_size, bits, ti); |
| 528 |
if (!p) |
| 529 |
onOutOfMemoryError(); |
| 530 |
|
| 531 |
debug (SENTINEL) |
| 532 |
{ |
| 533 |
p = sentinel_add(p); |
| 534 |
sentinel_init(p, size); |
| 535 |
alloc_size = size; |
| 536 |
} |
| 537 |
gcx.leakDetector.log_malloc(p, size); |
| 538 |
bytesAllocated += alloc_size; |
| 539 |
|
| 540 |
debug(PRINTF) printf(" => p = %p\n", p); |
| 541 |
return p; |
| 542 |
} |
| 543 |
|
| 544 |
BlkInfo qalloc( size_t size, uint bits, const scope TypeInfo ti) nothrow |
| 545 |
{ |
| 546 |
// qalloc should not be used for building metadata-containing blocks, |
| 547 |
// so avoid all the checking for bits and array padding. |
| 548 |
|
| 549 |
if (!size) |
| 550 |
{ |
| 551 |
return BlkInfo.init; |
| 552 |
} |
| 553 |
|
| 554 |
BlkInfo retval; |
| 555 |
|
| 556 |
retval.base = runLocked!(mallocNoSync, mallocTime, numMallocs)(size, bits, retval.size, ti); |
| 557 |
|
| 558 |
if (!(bits & BlkAttr.NO_SCAN)) |
| 559 |
{ |
| 560 |
memset(retval.base + size, 0, retval.size - size); |
| 561 |
} |
| 562 |
|
| 563 |
retval.attr = bits; |
| 564 |
return retval; |
| 565 |
} |
| 566 |
|
| 567 |
|
| 568 |
/** |
| 569 |
* Requests an aligned block of managed memory from the garbage collector, |
| 570 |
* which is initialized with all bits set to zero. |
| 571 |
* |
| 572 |
* Params: |
| 573 |
* size = The desired allocation size in bytes. |
| 574 |
* bits = A bitmask of the attributes to set on this block. |
| 575 |
* ti = TypeInfo to describe the memory. |
| 576 |
* |
| 577 |
* Returns: |
| 578 |
* A reference to the allocated memory or null if no memory was requested. |
| 579 |
* |
| 580 |
* Throws: |
| 581 |
* OutOfMemoryError on allocation failure. |
| 582 |
*/ |
| 583 |
void *calloc(size_t size, uint bits = 0, const TypeInfo ti = null) nothrow |
| 584 |
{ |
| 585 |
import core.internal.gc.blockmeta; |
| 586 |
|
| 587 |
if (!size) |
| 588 |
{ |
| 589 |
return null; |
| 590 |
} |
| 591 |
|
| 592 |
adjustAttrs(bits, ti); |
| 593 |
|
| 594 |
immutable padding = __allocPad(size, bits); |
| 595 |
bool overflow; |
| 596 |
import core.checkedint : addu; |
| 597 |
immutable needed = addu(size, padding, overflow); |
| 598 |
if (overflow) |
| 599 |
{ |
| 600 |
return null; |
| 601 |
} |
| 602 |
|
| 603 |
|
| 604 |
size_t localAllocSize = void; |
| 605 |
|
| 606 |
auto p = runLocked!(mallocNoSync, mallocTime, numMallocs)(needed, bits, localAllocSize, ti); |
| 607 |
|
| 608 |
debug (VALGRIND) makeMemUndefined(p[0..size]); |
| 609 |
|
| 610 |
auto ret = setupMetadata(p[0 .. localAllocSize], bits, padding, size, ti); |
| 611 |
|
| 612 |
invalidate((ret.ptr + size)[0 .. ret.length - size], 0xF0, true); |
| 613 |
|
| 614 |
if (bits & BlkAttr.NO_SCAN) |
| 615 |
{ |
| 616 |
memset(ret.ptr, 0, size); |
| 617 |
} |
| 618 |
else |
| 619 |
{ |
| 620 |
memset(ret.ptr, 0, ret.length); |
| 621 |
} |
| 622 |
|
| 623 |
return ret.ptr; |
| 624 |
} |
| 625 |
|
| 626 |
/** |
| 627 |
* Request that the GC reallocate a block of memory, attempting to adjust |
| 628 |
* the size in place if possible. If size is 0, the memory will be freed. |
| 629 |
* |
| 630 |
* If p was not allocated by the GC, points inside a block, or is null, no |
| 631 |
* action will be taken. |
| 632 |
* |
| 633 |
* Params: |
| 634 |
* p = A pointer to the root of a valid memory block or to null. |
| 635 |
* size = The desired allocation size in bytes. |
| 636 |
* bits = A bitmask of the attributes to set on this block. APPENDABLE and |
| 637 |
* FINALIZE are not allowed for realloc. |
| 638 |
* ti = TypeInfo to describe the memory. |
| 639 |
* |
| 640 |
* Returns: |
| 641 |
* A reference to the allocated memory on success or null if size is |
| 642 |
* zero. |
| 643 |
* |
| 644 |
* Throws: |
| 645 |
* OutOfMemoryError on allocation failure. |
| 646 |
*/ |
| 647 |
void *realloc(void *p, size_t size, uint bits = 0, const TypeInfo ti = null) nothrow |
| 648 |
{ |
| 649 |
if (bits & (BlkAttr.APPENDABLE | BlkAttr.FINALIZE)) |
| 650 |
// these bits are not allowed. We can't properly manage |
| 651 |
// reallocation of such blocks. |
| 652 |
onInvalidMemoryOperationError(); |
| 653 |
|
| 654 |
size_t localAllocSize = void; |
| 655 |
auto oldp = p; |
| 656 |
|
| 657 |
p = runLocked!(reallocNoSync, mallocTime, numMallocs)(p, size, bits, localAllocSize, ti); |
| 658 |
|
| 659 |
if (p) |
| 660 |
{ |
| 661 |
// invalidate any block info cache we have for the old allocation. |
| 662 |
import core.internal.gc.blkcache; |
| 663 |
if (auto bic = __getBlkInfo(oldp)) { |
| 664 |
*bic = BlkInfo.init; |
| 665 |
} |
| 666 |
|
| 667 |
if (!(bits & BlkAttr.NO_SCAN)) |
| 668 |
{ |
| 669 |
memset(p + size, 0, localAllocSize - size); |
| 670 |
} |
| 671 |
} |
| 672 |
|
| 673 |
return p; |
| 674 |
} |
| 675 |
|
| 676 |
|
| 677 |
// |
| 678 |
// The implementation of realloc. |
| 679 |
// |
| 680 |
// bits will be set to the resulting bits of the new block |
| 681 |
// |
| 682 |
private void *reallocNoSync(void *p, size_t size, ref uint bits, ref size_t alloc_size, const TypeInfo ti = null) nothrow |
| 683 |
{ |
| 684 |
if (!size) |
| 685 |
{ |
| 686 |
if (p) |
| 687 |
freeNoSync(p); |
| 688 |
alloc_size = 0; |
| 689 |
return null; |
| 690 |
} |
| 691 |
if (!p) |
| 692 |
return mallocNoSync(size, bits, alloc_size, ti); |
| 693 |
|
| 694 |
debug(PRINTF) printf("GC::realloc(p = %p, size = %llu)\n", p, cast(ulong)size); |
| 695 |
|
| 696 |
Pool *pool = gcx.findPool(p); |
| 697 |
if (!pool) |
| 698 |
return null; |
| 699 |
|
| 700 |
size_t psize; |
| 701 |
size_t biti; |
| 702 |
|
| 703 |
debug(SENTINEL) |
| 704 |
{ |
| 705 |
void* q = p; |
| 706 |
p = sentinel_sub(p); |
| 707 |
bool alwaysMalloc = true; |
| 708 |
} |
| 709 |
else |
| 710 |
{ |
| 711 |
alias q = p; |
| 712 |
enum alwaysMalloc = false; |
| 713 |
} |
| 714 |
|
| 715 |
void* doMalloc() |
| 716 |
{ |
| 717 |
if (!bits) |
| 718 |
bits = pool.getBits(biti) & |
| 719 |
~(BlkAttr.APPENDABLE | BlkAttr.FINALIZE | BlkAttr.STRUCTFINAL); |
| 720 |
|
| 721 |
void* p2 = mallocNoSync(size, bits, alloc_size, ti); |
| 722 |
debug (SENTINEL) |
| 723 |
psize = sentinel_size(q, psize); |
| 724 |
if (psize < size) |
| 725 |
size = psize; |
| 726 |
//debug(PRINTF) printf("\tcopying %d bytes\n",size); |
| 727 |
memcpy(p2, q, size); |
| 728 |
freeNoSync(q); |
| 729 |
return p2; |
| 730 |
} |
| 731 |
|
| 732 |
if (pool.isLargeObject) |
| 733 |
{ |
| 734 |
auto lpool = cast(LargeObjectPool*) pool; |
| 735 |
auto psz = lpool.getPages(p); // get allocated size |
| 736 |
if (psz == 0) |
| 737 |
return null; // interior pointer |
| 738 |
psize = psz * PAGESIZE; |
| 739 |
|
| 740 |
alias pagenum = biti; // happens to be the same, but rename for clarity |
| 741 |
pagenum = lpool.pagenumOf(p); |
| 742 |
|
| 743 |
if (size <= PAGESIZE / 2 || alwaysMalloc) |
| 744 |
return doMalloc(); // switching from large object pool to small object pool |
| 745 |
|
| 746 |
auto newsz = lpool.numPages(size); |
| 747 |
if (newsz == psz) |
| 748 |
{ |
| 749 |
// nothing to do |
| 750 |
} |
| 751 |
else if (newsz < psz) |
| 752 |
{ |
| 753 |
// Shrink in place |
| 754 |
invalidate((p + size)[0 .. psize - size], 0xF2, false); |
| 755 |
lpool.freePages(pagenum + newsz, psz - newsz); |
| 756 |
lpool.mergeFreePageOffsets!(false, true)(pagenum + newsz, psz - newsz); |
| 757 |
lpool.bPageOffsets[pagenum] = cast(uint) newsz; |
| 758 |
} |
| 759 |
else if (pagenum + newsz <= pool.npages) |
| 760 |
{ |
| 761 |
// Attempt to expand in place (TODO: merge with extend) |
| 762 |
if (lpool.pagetable[pagenum + psz] != Bins.B_FREE) |
| 763 |
return doMalloc(); |
| 764 |
|
| 765 |
auto newPages = newsz - psz; |
| 766 |
auto freesz = lpool.bPageOffsets[pagenum + psz]; |
| 767 |
if (freesz < newPages) |
| 768 |
return doMalloc(); // free range too small |
| 769 |
|
| 770 |
invalidate((p + psize)[0 .. size - psize], 0xF0, true); |
| 771 |
debug (PRINTF) printFreeInfo(pool); |
| 772 |
memset(&lpool.pagetable[pagenum + psz], Bins.B_PAGEPLUS, newPages); |
| 773 |
lpool.bPageOffsets[pagenum] = cast(uint) newsz; |
| 774 |
for (auto offset = psz; offset < newsz; offset++) |
| 775 |
lpool.bPageOffsets[pagenum + offset] = cast(uint) offset; |
| 776 |
if (freesz > newPages) |
| 777 |
lpool.setFreePageOffsets(pagenum + newsz, freesz - newPages); |
| 778 |
gcx.usedLargePages += newPages; |
| 779 |
lpool.freepages -= newPages; |
| 780 |
debug (PRINTF) printFreeInfo(pool); |
| 781 |
} |
| 782 |
else |
| 783 |
return doMalloc(); // does not fit into current pool |
| 784 |
|
| 785 |
alloc_size = newsz * PAGESIZE; |
| 786 |
} |
| 787 |
else |
| 788 |
{ |
| 789 |
psize = (cast(SmallObjectPool*) pool).getSize(p); // get allocated bin size |
| 790 |
if (psize == 0) |
| 791 |
return null; // interior pointer |
| 792 |
biti = cast(size_t)(p - pool.baseAddr) >> Pool.ShiftBy.Small; |
| 793 |
if (pool.freebits.test (biti)) |
| 794 |
return null; |
| 795 |
|
| 796 |
// allocate if new size is bigger or less than half |
| 797 |
if (psize < size || psize > size * 2 || alwaysMalloc) |
| 798 |
return doMalloc(); |
| 799 |
|
| 800 |
alloc_size = psize; |
| 801 |
if (isPrecise) |
| 802 |
pool.setPointerBitmapSmall(p, size, psize, bits, ti); |
| 803 |
} |
| 804 |
|
| 805 |
if (bits) |
| 806 |
{ |
| 807 |
pool.clrBits(biti, ~BlkAttr.NONE); |
| 808 |
pool.setBits(biti, bits); |
| 809 |
} |
| 810 |
return p; |
| 811 |
} |
| 812 |
|
| 813 |
|
| 814 |
size_t extend(void* p, size_t minsize, size_t maxsize, const TypeInfo ti) nothrow |
| 815 |
{ |
| 816 |
auto result = runLocked!(extendNoSync, extendTime, numExtends)(p, minsize, maxsize, ti); |
| 817 |
if (result != 0) { |
| 818 |
// invalidate any block info cache we have for the old allocation. |
| 819 |
import core.internal.gc.blkcache; |
| 820 |
if (auto bic = __getBlkInfo(p)) { |
| 821 |
*bic = BlkInfo.init; |
| 822 |
} |
| 823 |
} |
| 824 |
|
| 825 |
return result; |
| 826 |
} |
| 827 |
|
| 828 |
|
| 829 |
// |
| 830 |
// Implementation of extend. |
| 831 |
// |
| 832 |
private size_t extendNoSync(void* p, size_t minsize, size_t maxsize, const TypeInfo ti = null) nothrow |
| 833 |
in |
| 834 |
{ |
| 835 |
assert(minsize <= maxsize); |
| 836 |
} |
| 837 |
do |
| 838 |
{ |
| 839 |
debug(PRINTF) printf("GC::extend(p = %p, minsize = %zu, maxsize = %zu)\n", p, minsize, maxsize); |
| 840 |
debug (SENTINEL) |
| 841 |
{ |
| 842 |
return 0; |
| 843 |
} |
| 844 |
else |
| 845 |
{ |
| 846 |
auto pool = gcx.findPool(p); |
| 847 |
if (!pool || !pool.isLargeObject) |
| 848 |
return 0; |
| 849 |
|
| 850 |
auto lpool = cast(LargeObjectPool*) pool; |
| 851 |
const pagenum = lpool.pagenumOf(p); |
| 852 |
if (lpool.pagetable[pagenum] != Bins.B_PAGE) |
| 853 |
return 0; |
| 854 |
|
| 855 |
uint psz = lpool.bPageOffsets[pagenum]; |
| 856 |
assert(psz > 0); |
| 857 |
|
| 858 |
const minsz = lpool.numPages(minsize); |
| 859 |
const maxsz = lpool.numPages(maxsize); |
| 860 |
|
| 861 |
if (pagenum + psz >= lpool.npages) |
| 862 |
return 0; |
| 863 |
if (lpool.pagetable[pagenum + psz] != Bins.B_FREE) |
| 864 |
return 0; |
| 865 |
|
| 866 |
const freesz = lpool.bPageOffsets[pagenum + psz]; |
| 867 |
if (freesz < minsz) |
| 868 |
return 0; |
| 869 |
const sz = freesz > maxsz ? maxsz : freesz; |
| 870 |
invalidate((pool.baseAddr + (pagenum + psz) * PAGESIZE)[0 .. sz * PAGESIZE], 0xF0, true); |
| 871 |
memset(lpool.pagetable + pagenum + psz, Bins.B_PAGEPLUS, sz); |
| 872 |
lpool.bPageOffsets[pagenum] = cast(uint) (psz + sz); |
| 873 |
for (auto offset = psz; offset < psz + sz; offset++) |
| 874 |
lpool.bPageOffsets[pagenum + offset] = cast(uint) offset; |
| 875 |
if (freesz > sz) |
| 876 |
lpool.setFreePageOffsets(pagenum + psz + sz, freesz - sz); |
| 877 |
lpool.freepages -= sz; |
| 878 |
gcx.usedLargePages += sz; |
| 879 |
return (psz + sz) * PAGESIZE; |
| 880 |
} |
| 881 |
} |
| 882 |
|
| 883 |
|
| 884 |
/** |
| 885 |
* Requests that at least size bytes of memory be obtained from the operating |
| 886 |
* system and marked as free. |
| 887 |
* |
| 888 |
* Params: |
| 889 |
* size = The desired size in bytes. |
| 890 |
* |
| 891 |
* Returns: |
| 892 |
* The actual number of bytes reserved or zero on error. |
| 893 |
*/ |
| 894 |
size_t reserve(size_t size) nothrow |
| 895 |
{ |
| 896 |
if (!size) |
| 897 |
{ |
| 898 |
return 0; |
| 899 |
} |
| 900 |
|
| 901 |
return runLocked!(reserveNoSync, otherTime, numOthers)(size); |
| 902 |
} |
| 903 |
|
| 904 |
|
| 905 |
// |
| 906 |
// Implementation of reserve |
| 907 |
// |
| 908 |
private size_t reserveNoSync(size_t size) nothrow |
| 909 |
{ |
| 910 |
assert(size != 0); |
| 911 |
assert(gcx); |
| 912 |
|
| 913 |
return gcx.reserve(size); |
| 914 |
} |
| 915 |
|
| 916 |
|
| 917 |
/** |
| 918 |
* Deallocates the memory referenced by p. |
| 919 |
* |
| 920 |
* If p was not allocated by the GC, points inside a block, is null, or |
| 921 |
* if free is called from a finalizer, no action will be taken. |
| 922 |
* |
| 923 |
* Params: |
| 924 |
* p = A pointer to the root of a valid memory block or to null. |
| 925 |
*/ |
| 926 |
void free(void *p) nothrow |
| 927 |
{ |
| 928 |
if (!p || _inFinalizer) |
| 929 |
{ |
| 930 |
return; |
| 931 |
} |
| 932 |
|
| 933 |
auto didFree = runLocked!(freeNoSync, freeTime, numFrees)(p); |
| 934 |
|
| 935 |
if (didFree) { |
| 936 |
// invalidate any block info cache we have for the old allocation. |
| 937 |
import core.internal.gc.blkcache; |
| 938 |
if (auto bic = __getBlkInfo(p)) { |
| 939 |
*bic = BlkInfo.init; |
| 940 |
} |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
|
| 945 |
// |
| 946 |
// Implementation of free. |
| 947 |
// |
| 948 |
private bool freeNoSync(void *p) nothrow @nogc |
| 949 |
{ |
| 950 |
debug(PRINTF) printf("Freeing %#zx\n", cast(size_t) p); |
| 951 |
assert (p); |
| 952 |
|
| 953 |
Pool* pool; |
| 954 |
size_t pagenum; |
| 955 |
Bins bin; |
| 956 |
size_t biti; |
| 957 |
|
| 958 |
// Find which page it is in |
| 959 |
pool = gcx.findPool(p); |
| 960 |
if (!pool) // if not one of ours |
| 961 |
return false; // ignore |
| 962 |
|
| 963 |
pagenum = pool.pagenumOf(p); |
| 964 |
|
| 965 |
debug(PRINTF) printf("pool base = %p, PAGENUM = %zd of %zd, bin = %d\n", pool.baseAddr, pagenum, pool.npages, pool.pagetable[pagenum]); |
| 966 |
debug(PRINTF) if (pool.isLargeObject) printf("Block size = %d\n", pool.bPageOffsets[pagenum]); |
| 967 |
|
| 968 |
bin = pool.pagetable[pagenum]; |
| 969 |
|
| 970 |
// Verify that the pointer is at the beginning of a block, |
| 971 |
// no action should be taken if p is an interior pointer |
| 972 |
if (bin > Bins.B_PAGE) // B_PAGEPLUS or B_FREE |
| 973 |
return false; |
| 974 |
size_t off = (sentinel_sub(p) - pool.baseAddr); |
| 975 |
size_t base = baseOffset(off, bin); |
| 976 |
if (off != base) |
| 977 |
return false; |
| 978 |
|
| 979 |
sentinel_Invariant(p); |
| 980 |
auto q = p; |
| 981 |
p = sentinel_sub(p); |
| 982 |
size_t ssize; |
| 983 |
|
| 984 |
if (pool.isLargeObject) // if large alloc |
| 985 |
{ |
| 986 |
biti = cast(size_t)(p - pool.baseAddr) >> pool.ShiftBy.Large; |
| 987 |
assert(bin == Bins.B_PAGE); |
| 988 |
auto lpool = cast(LargeObjectPool*) pool; |
| 989 |
|
| 990 |
// Free pages |
| 991 |
size_t npages = lpool.bPageOffsets[pagenum]; |
| 992 |
auto size = npages * PAGESIZE; |
| 993 |
ssize = sentinel_size(q, size); |
| 994 |
invalidate(p[0 .. size], 0xF2, false); |
| 995 |
lpool.freePages(pagenum, npages); |
| 996 |
lpool.mergeFreePageOffsets!(true, true)(pagenum, npages); |
| 997 |
} |
| 998 |
else |
| 999 |
{ |
| 1000 |
biti = cast(size_t)(p - pool.baseAddr) >> pool.ShiftBy.Small; |
| 1001 |
if (pool.freebits.test (biti)) |
| 1002 |
return false; |
| 1003 |
// Add to free list |
| 1004 |
List *list = cast(List*)p; |
| 1005 |
|
| 1006 |
auto size = binsize[bin]; |
| 1007 |
ssize = sentinel_size(q, size); |
| 1008 |
invalidate(p[0 .. size], 0xF2, false); |
| 1009 |
|
| 1010 |
// in case the page hasn't been recovered yet, don't add the object to the free list |
| 1011 |
if (!gcx.recoverPool[bin] || pool.binPageChain[pagenum] == Pool.PageRecovered) |
| 1012 |
{ |
| 1013 |
undefinedWrite(list.next, gcx.bucket[bin]); |
| 1014 |
undefinedWrite(list.pool, pool); |
| 1015 |
gcx.bucket[bin] = list; |
| 1016 |
} |
| 1017 |
pool.freebits.set(biti); |
| 1018 |
} |
| 1019 |
pool.clrBits(biti, ~BlkAttr.NONE); |
| 1020 |
|
| 1021 |
gcx.leakDetector.log_free(sentinel_add(p), ssize); |
| 1022 |
|
| 1023 |
return true; |
| 1024 |
} |
| 1025 |
|
| 1026 |
|
| 1027 |
/** |
| 1028 |
* Determine the base address of the block containing p. If p is not a gc |
| 1029 |
* allocated pointer, return null. |
| 1030 |
* |
| 1031 |
* Params: |
| 1032 |
* p = A pointer to the root or the interior of a valid memory block or to |
| 1033 |
* null. |
| 1034 |
* |
| 1035 |
* Returns: |
| 1036 |
* The base address of the memory block referenced by p or null on error. |
| 1037 |
*/ |
| 1038 |
void* addrOf(void *p) nothrow |
| 1039 |
{ |
| 1040 |
if (!p) |
| 1041 |
{ |
| 1042 |
return null; |
| 1043 |
} |
| 1044 |
|
| 1045 |
return runLocked!(addrOfNoSync, otherTime, numOthers)(p); |
| 1046 |
} |
| 1047 |
|
| 1048 |
|
| 1049 |
// |
| 1050 |
// Implementation of addrOf. |
| 1051 |
// |
| 1052 |
void* addrOfNoSync(void *p) nothrow @nogc |
| 1053 |
{ |
| 1054 |
if (!p) |
| 1055 |
{ |
| 1056 |
return null; |
| 1057 |
} |
| 1058 |
|
| 1059 |
auto q = gcx.findBase(p); |
| 1060 |
if (q) |
| 1061 |
q = sentinel_add(q); |
| 1062 |
return q; |
| 1063 |
} |
| 1064 |
|
| 1065 |
|
| 1066 |
/** |
| 1067 |
* Determine the allocated size of pointer p. If p is an interior pointer |
| 1068 |
* or not a gc allocated pointer, return 0. |
| 1069 |
* |
| 1070 |
* Params: |
| 1071 |
* p = A pointer to the root of a valid memory block or to null. |
| 1072 |
* |
| 1073 |
* Returns: |
| 1074 |
* The size in bytes of the memory block referenced by p or zero on error. |
| 1075 |
*/ |
| 1076 |
size_t sizeOf(void *p) nothrow |
| 1077 |
{ |
| 1078 |
if (!p) |
| 1079 |
{ |
| 1080 |
return 0; |
| 1081 |
} |
| 1082 |
|
| 1083 |
return runLocked!(sizeOfNoSync, otherTime, numOthers)(p); |
| 1084 |
} |
| 1085 |
|
| 1086 |
|
| 1087 |
// |
| 1088 |
// Implementation of sizeOf. |
| 1089 |
// |
| 1090 |
private size_t sizeOfNoSync(void *p) nothrow @nogc |
| 1091 |
{ |
| 1092 |
assert (p); |
| 1093 |
|
| 1094 |
debug (SENTINEL) |
| 1095 |
{ |
| 1096 |
p = sentinel_sub(p); |
| 1097 |
size_t size = gcx.findSize(p); |
| 1098 |
return size ? size - SENTINEL_EXTRA : 0; |
| 1099 |
} |
| 1100 |
else |
| 1101 |
{ |
| 1102 |
size_t size = gcx.findSize(p); |
| 1103 |
return size; |
| 1104 |
} |
| 1105 |
} |
| 1106 |
|
| 1107 |
|
| 1108 |
/** |
| 1109 |
* Determine the base address of the block containing p. If p is not a gc |
| 1110 |
* allocated pointer, return null. |
| 1111 |
* |
| 1112 |
* Params: |
| 1113 |
* p = A pointer to the root or the interior of a valid memory block or to |
| 1114 |
* null. |
| 1115 |
* |
| 1116 |
* Returns: |
| 1117 |
* Information regarding the memory block referenced by p or BlkInfo.init |
| 1118 |
* on error. |
| 1119 |
*/ |
| 1120 |
BlkInfo query(void *p) nothrow |
| 1121 |
{ |
| 1122 |
if (!p) |
| 1123 |
{ |
| 1124 |
BlkInfo i; |
| 1125 |
return i; |
| 1126 |
} |
| 1127 |
|
| 1128 |
return runLocked!(queryNoSync, otherTime, numOthers)(p); |
| 1129 |
} |
| 1130 |
|
| 1131 |
// |
| 1132 |
// Implementation of query |
| 1133 |
// |
| 1134 |
BlkInfo queryNoSync(void *p) nothrow |
| 1135 |
{ |
| 1136 |
assert(p); |
| 1137 |
|
| 1138 |
BlkInfo info = gcx.getInfo(p); |
| 1139 |
debug(SENTINEL) |
| 1140 |
{ |
| 1141 |
if (info.base) |
| 1142 |
{ |
| 1143 |
info.base = sentinel_add(info.base); |
| 1144 |
info.size = *sentinel_psize(info.base); |
| 1145 |
} |
| 1146 |
} |
| 1147 |
return info; |
| 1148 |
} |
| 1149 |
|
| 1150 |
|
| 1151 |
/** |
| 1152 |
* Performs certain checks on a pointer. These checks will cause asserts to |
| 1153 |
* fail unless the following conditions are met: |
| 1154 |
* 1) The poiinter belongs to this memory pool. |
| 1155 |
* 2) The pointer points to the start of an allocated piece of memory. |
| 1156 |
* 3) The pointer is not on a free list. |
| 1157 |
* |
| 1158 |
* Params: |
| 1159 |
* p = The pointer to be checked. |
| 1160 |
*/ |
| 1161 |
void check(void *p) nothrow |
| 1162 |
{ |
| 1163 |
if (!p) |
| 1164 |
{ |
| 1165 |
return; |
| 1166 |
} |
| 1167 |
|
| 1168 |
return runLocked!(checkNoSync, otherTime, numOthers)(p); |
| 1169 |
} |
| 1170 |
|
| 1171 |
|
| 1172 |
// |
| 1173 |
// Implementation of check |
| 1174 |
// |
| 1175 |
private void checkNoSync(void *p) nothrow |
| 1176 |
{ |
| 1177 |
assert(p); |
| 1178 |
|
| 1179 |
sentinel_Invariant(p); |
| 1180 |
debug (PTRCHECK) |
| 1181 |
{ |
| 1182 |
Pool* pool; |
| 1183 |
size_t pagenum; |
| 1184 |
Bins bin; |
| 1185 |
|
| 1186 |
p = sentinel_sub(p); |
| 1187 |
pool = gcx.findPool(p); |
| 1188 |
assert(pool); |
| 1189 |
pagenum = pool.pagenumOf(p); |
| 1190 |
bin = pool.pagetable[pagenum]; |
| 1191 |
assert(bin <= Bins.B_PAGE); |
| 1192 |
assert(p == cast(void*)baseOffset(cast(size_t)p, bin)); |
| 1193 |
|
| 1194 |
debug (PTRCHECK2) |
| 1195 |
{ |
| 1196 |
if (bin < Bins.B_PAGE) |
| 1197 |
{ |
| 1198 |
// Check that p is not on a free list |
| 1199 |
List *list; |
| 1200 |
|
| 1201 |
for (list = gcx.bucket[bin]; list; list = list.next) |
| 1202 |
{ |
| 1203 |
assert(cast(void*)list != p); |
| 1204 |
} |
| 1205 |
} |
| 1206 |
} |
| 1207 |
} |
| 1208 |
} |
| 1209 |
|
| 1210 |
|
| 1211 |
/** |
| 1212 |
* Add p to list of roots. If p is null, no operation is performed. |
| 1213 |
* |
| 1214 |
* Params: |
| 1215 |
* p = A pointer into a GC-managed memory block or null. |
| 1216 |
*/ |
| 1217 |
void addRoot(void *p) nothrow @nogc |
| 1218 |
{ |
| 1219 |
if (!p) |
| 1220 |
{ |
| 1221 |
return; |
| 1222 |
} |
| 1223 |
|
| 1224 |
gcx.addRoot(p); |
| 1225 |
} |
| 1226 |
|
| 1227 |
|
| 1228 |
/** |
| 1229 |
* Remove p from list of roots. If p is null or is not a value |
| 1230 |
* previously passed to addRoot() then no operation is performed. |
| 1231 |
* |
| 1232 |
* Params: |
| 1233 |
* p = A pointer into a GC-managed memory block or null. |
| 1234 |
*/ |
| 1235 |
void removeRoot(void *p) nothrow @nogc |
| 1236 |
{ |
| 1237 |
if (!p) |
| 1238 |
{ |
| 1239 |
return; |
| 1240 |
} |
| 1241 |
|
| 1242 |
gcx.removeRoot(p); |
| 1243 |
} |
| 1244 |
|
| 1245 |
/** |
| 1246 |
* Returns an iterator allowing roots to be traversed via a foreach loop. |
| 1247 |
*/ |
| 1248 |
@property RootIterator rootIter() @nogc |
| 1249 |
{ |
| 1250 |
return &gcx.rootsApply; |
| 1251 |
} |
| 1252 |
|
| 1253 |
|
| 1254 |
/** |
| 1255 |
* Add range to scan for roots. If p is null or sz is 0, no operation is performed. |
| 1256 |
* |
| 1257 |
* Params: |
| 1258 |
* p = A pointer to a valid memory address or to null. |
| 1259 |
* sz = The size in bytes of the block to add. |
| 1260 |
* ti = TypeInfo to describe the memory. |
| 1261 |
*/ |
| 1262 |
void addRange(void *p, size_t sz, const TypeInfo ti = null) nothrow @nogc |
| 1263 |
{ |
| 1264 |
if (!p || !sz) |
| 1265 |
{ |
| 1266 |
return; |
| 1267 |
} |
| 1268 |
|
| 1269 |
gcx.addRange(p, p + sz, ti); |
| 1270 |
} |
| 1271 |
|
| 1272 |
|
| 1273 |
/** |
| 1274 |
* Remove range from list of ranges. If p is null or does not represent |
| 1275 |
* a value previously passed to addRange() then no operation is |
| 1276 |
* performed. |
| 1277 |
* |
| 1278 |
* Params: |
| 1279 |
* p = A pointer to a valid memory address or to null. |
| 1280 |
*/ |
| 1281 |
void removeRange(void *p) nothrow @nogc |
| 1282 |
{ |
| 1283 |
if (!p) |
| 1284 |
{ |
| 1285 |
return; |
| 1286 |
} |
| 1287 |
|
| 1288 |
gcx.removeRange(p); |
| 1289 |
} |
| 1290 |
|
| 1291 |
|
| 1292 |
/** |
| 1293 |
* Returns an iterator allowing ranges to be traversed via a foreach loop. |
| 1294 |
*/ |
| 1295 |
@property RangeIterator rangeIter() @nogc |
| 1296 |
{ |
| 1297 |
return &gcx.rangesApply; |
| 1298 |
} |
| 1299 |
|
| 1300 |
|
| 1301 |
/** |
| 1302 |
* Run all finalizers in the code segment. |
| 1303 |
* |
| 1304 |
* Params: |
| 1305 |
* segment = address range of a code segment |
| 1306 |
*/ |
| 1307 |
void runFinalizers(const scope void[] segment) nothrow |
| 1308 |
{ |
| 1309 |
static void go(Gcx* gcx, const scope void[] segment) nothrow |
| 1310 |
{ |
| 1311 |
gcx.runFinalizers(segment); |
| 1312 |
} |
| 1313 |
return runLocked!(go, otherTime, numOthers)(gcx, segment); |
| 1314 |
} |
| 1315 |
|
| 1316 |
|
| 1317 |
bool inFinalizer() nothrow @nogc |
| 1318 |
{ |
| 1319 |
return _inFinalizer; |
| 1320 |
} |
| 1321 |
|
| 1322 |
|
| 1323 |
void collect() nothrow |
| 1324 |
{ |
| 1325 |
fullCollect(); |
| 1326 |
} |
| 1327 |
|
| 1328 |
|
| 1329 |
/** |
| 1330 |
* Begins a full collection, scanning all stack segments for roots. |
| 1331 |
* |
| 1332 |
* Returns: |
| 1333 |
* The number of pages freed. |
| 1334 |
*/ |
| 1335 |
size_t fullCollect() nothrow |
| 1336 |
{ |
| 1337 |
debug(PRINTF) printf("GC.fullCollect()\n"); |
| 1338 |
|
| 1339 |
// Since a finalizer could launch a new thread, we always need to lock |
| 1340 |
// when collecting. |
| 1341 |
static size_t go(Gcx* gcx) nothrow |
| 1342 |
{ |
| 1343 |
return gcx.fullcollect(false, true); // standard stop the world |
| 1344 |
} |
| 1345 |
immutable result = runLocked!go(gcx); |
| 1346 |
|
| 1347 |
version (none) |
| 1348 |
{ |
| 1349 |
GCStats stats; |
| 1350 |
|
| 1351 |
getStats(stats); |
| 1352 |
debug(PRINTF) printf("heapSize = %zx, freeSize = %zx\n", |
| 1353 |
stats.heapSize, stats.freeSize); |
| 1354 |
} |
| 1355 |
|
| 1356 |
gcx.leakDetector.log_collect(); |
| 1357 |
return result; |
| 1358 |
} |
| 1359 |
|
| 1360 |
|
| 1361 |
/** |
| 1362 |
* Minimize free space usage. |
| 1363 |
*/ |
| 1364 |
void minimize() nothrow |
| 1365 |
{ |
| 1366 |
static void go(Gcx* gcx) nothrow |
| 1367 |
{ |
| 1368 |
gcx.minimize(); |
| 1369 |
} |
| 1370 |
runLocked!(go, otherTime, numOthers)(gcx); |
| 1371 |
} |
| 1372 |
|
| 1373 |
|
| 1374 |
core.memory.GC.Stats stats() @safe nothrow @nogc |
| 1375 |
{ |
| 1376 |
typeof(return) ret; |
| 1377 |
|
| 1378 |
runLocked!(getStatsNoSync, otherTime, numOthers)(ret); |
| 1379 |
|
| 1380 |
return ret; |
| 1381 |
} |
| 1382 |
|
| 1383 |
|
| 1384 |
core.memory.GC.ProfileStats profileStats() nothrow @trusted |
| 1385 |
{ |
| 1386 |
typeof(return) ret; |
| 1387 |
|
| 1388 |
ret.numCollections = numCollections; |
| 1389 |
ret.totalCollectionTime = prepTime + markTime + sweepTime; |
| 1390 |
ret.totalPauseTime = pauseTime; |
| 1391 |
ret.maxCollectionTime = maxCollectionTime; |
| 1392 |
ret.maxPauseTime = maxPauseTime; |
| 1393 |
|
| 1394 |
return ret; |
| 1395 |
} |
| 1396 |
|
| 1397 |
|
| 1398 |
ulong allocatedInCurrentThread() nothrow |
| 1399 |
{ |
| 1400 |
return bytesAllocated; |
| 1401 |
} |
| 1402 |
|
| 1403 |
|
| 1404 |
// |
| 1405 |
// Implementation of getStats |
| 1406 |
// |
| 1407 |
private void getStatsNoSync(out core.memory.GC.Stats stats) @trusted nothrow @nogc |
| 1408 |
{ |
| 1409 |
// This function is trusted for two reasons: `pool.pagetable` is a pointer, |
| 1410 |
// which is being sliced in the below foreach, and so is `binPageChain`, |
| 1411 |
// also sliced a bit later in this function. |
| 1412 |
// However, both usages are safe as long as the assumption that `npools` |
| 1413 |
// defines the limit for `pagetable`'s length holds true (see allocation). |
| 1414 |
// The slicing happens at __LINE__ + 4 and __LINE__ + 24. |
| 1415 |
// `@trusted` delegates are not used to prevent any performance issue. |
| 1416 |
foreach (pool; gcx.pooltable[]) |
| 1417 |
{ |
| 1418 |
foreach (bin; pool.pagetable[0 .. pool.npages]) |
| 1419 |
{ |
| 1420 |
if (bin == Bins.B_FREE) |
| 1421 |
stats.freeSize += PAGESIZE; |
| 1422 |
else |
| 1423 |
stats.usedSize += PAGESIZE; |
| 1424 |
} |
| 1425 |
} |
| 1426 |
|
| 1427 |
size_t freeListSize; |
| 1428 |
foreach (n; 0 .. Bins.B_PAGE) |
| 1429 |
{ |
| 1430 |
immutable sz = binsize[n]; |
| 1431 |
for (List *list = gcx.bucket[n]; list; list = list.next) |
| 1432 |
freeListSize += sz; |
| 1433 |
|
| 1434 |
foreach (pool; gcx.pooltable[]) |
| 1435 |
{ |
| 1436 |
if (pool.isLargeObject) |
| 1437 |
continue; |
| 1438 |
for (uint pn = pool.recoverPageFirst[n]; pn < pool.npages; pn = pool.binPageChain[pn]) |
| 1439 |
{ |
| 1440 |
const bitbase = pn * PAGESIZE / 16; |
| 1441 |
const top = PAGESIZE - sz + 1; // ensure <size> bytes available even if unaligned |
| 1442 |
for (size_t u = 0; u < top; u += sz) |
| 1443 |
if (pool.freebits.test(bitbase + u / 16)) |
| 1444 |
freeListSize += sz; |
| 1445 |
} |
| 1446 |
} |
| 1447 |
} |
| 1448 |
|
| 1449 |
stats.usedSize -= freeListSize; |
| 1450 |
stats.freeSize += freeListSize; |
| 1451 |
stats.allocatedInCurrentThread = bytesAllocated; |
| 1452 |
} |
| 1453 |
|
| 1454 |
// ARRAY FUNCTIONS |
| 1455 |
void[] getArrayUsed(void *ptr, bool atomic = false) nothrow |
| 1456 |
{ |
| 1457 |
import core.internal.gc.blockmeta; |
| 1458 |
import core.internal.gc.blkcache; |
| 1459 |
import core.internal.array.utils; |
| 1460 |
|
| 1461 |
// lookup the block info, using the cache if possible. |
| 1462 |
auto bic = atomic ? null : __getBlkInfo(ptr); |
| 1463 |
auto info = bic ? *bic : query(ptr); |
| 1464 |
|
| 1465 |
if (!(info.attr & BlkAttr.APPENDABLE)) |
| 1466 |
// not appendable |
| 1467 |
return null; |
| 1468 |
|
| 1469 |
assert(info.base); // sanity check. |
| 1470 |
if (!bic && !atomic) |
| 1471 |
// cache the lookup for next time |
| 1472 |
__insertBlkInfoCache(info, null); |
| 1473 |
|
| 1474 |
auto usedSize = atomic ? __arrayAllocLengthAtomic(info) : __arrayAllocLength(info); |
| 1475 |
return __arrayStart(info)[0 .. usedSize]; |
| 1476 |
} |
| 1477 |
|
| 1478 |
/* NOTE about @trusted in these functions: |
| 1479 |
* These functions do a lot of pointer manipulation, and has writeable |
| 1480 |
* access to BlkInfo which is used to interface with other parts of the GC, |
| 1481 |
* including the block metadata and block cache. Marking these functions as |
| 1482 |
* @safe would mean that any modification of BlkInfo fields should be |
| 1483 |
* considered @safe, which is not the case. For example, it would be |
| 1484 |
* perfectly legal to change the BlkInfo size to some huge number, and then |
| 1485 |
* store it in the block cache to blow up later. The utility functions |
| 1486 |
* count on the BlkInfo representing the correct information inside the GC. |
| 1487 |
* |
| 1488 |
* In order to mark these @safe, we would need a BlkInfo that has |
| 1489 |
* restrictive access (i.e. @system only) to the information inside the |
| 1490 |
* BlkInfo. Until then any use of these structures needs to be @trusted, |
| 1491 |
* and therefore the entire functions are @trusted. The API is still @safe |
| 1492 |
* because the information is stored and looked up by the GC, not the |
| 1493 |
* caller. |
| 1494 |
*/ |
| 1495 |
bool expandArrayUsed(void[] slice, size_t newUsed, bool atomic = false) nothrow @trusted |
| 1496 |
{ |
| 1497 |
import core.internal.gc.blockmeta; |
| 1498 |
import core.internal.gc.blkcache; |
| 1499 |
import core.internal.array.utils; |
| 1500 |
|
| 1501 |
if (newUsed < slice.length) |
| 1502 |
// cannot "expand" by shrinking. |
| 1503 |
return false; |
| 1504 |
|
| 1505 |
// lookup the block info, using the cache if possible |
| 1506 |
auto bic = atomic ? null : __getBlkInfo(slice.ptr); |
| 1507 |
auto info = bic ? *bic : query(slice.ptr); |
| 1508 |
|
| 1509 |
if (!(info.attr & BlkAttr.APPENDABLE)) |
| 1510 |
// not appendable |
| 1511 |
return false; |
| 1512 |
|
| 1513 |
assert(info.base); // sanity check. |
| 1514 |
|
| 1515 |
immutable offset = slice.ptr - __arrayStart(info); |
| 1516 |
newUsed += offset; |
| 1517 |
auto existingUsed = slice.length + offset; |
| 1518 |
|
| 1519 |
size_t typeInfoSize = (info.attr & BlkAttr.STRUCTFINAL) ? size_t.sizeof : 0; |
| 1520 |
if (__setArrayAllocLengthImpl(info, offset + newUsed, atomic, existingUsed, typeInfoSize)) |
| 1521 |
{ |
| 1522 |
// could expand without extending |
| 1523 |
if (!bic && !atomic) |
| 1524 |
// cache the lookup for next time |
| 1525 |
__insertBlkInfoCache(info, null); |
| 1526 |
return true; |
| 1527 |
} |
| 1528 |
|
| 1529 |
// if we got here, just setting the used size did not work. |
| 1530 |
if (info.size < PAGESIZE) |
| 1531 |
// nothing else we can do |
| 1532 |
return false; |
| 1533 |
|
| 1534 |
// try extending the block into subsequent pages. |
| 1535 |
immutable requiredExtension = newUsed - info.size - LARGEPAD; |
| 1536 |
auto extendedSize = extend(info.base, requiredExtension, requiredExtension, null); |
| 1537 |
if (extendedSize == 0) |
| 1538 |
// could not extend, can't satisfy the request |
| 1539 |
return false; |
| 1540 |
|
| 1541 |
info.size = extendedSize; |
| 1542 |
if (bic) |
| 1543 |
*bic = info; |
| 1544 |
else if (!atomic) |
| 1545 |
__insertBlkInfoCache(info, null); |
| 1546 |
|
| 1547 |
// this should always work. |
| 1548 |
return __setArrayAllocLengthImpl(info, newUsed, atomic, existingUsed, typeInfoSize); |
| 1549 |
} |
| 1550 |
|
| 1551 |
bool shrinkArrayUsed(void[] slice, size_t existingUsed, bool atomic = false) nothrow |
| 1552 |
{ |
| 1553 |
import core.internal.gc.blockmeta; |
| 1554 |
import core.internal.gc.blkcache; |
| 1555 |
import core.internal.array.utils; |
| 1556 |
|
| 1557 |
if (existingUsed < slice.length) |
| 1558 |
// cannot "shrink" by growing. |
| 1559 |
return false; |
| 1560 |
|
| 1561 |
// lookup the block info, using the cache if possible. |
| 1562 |
auto bic = atomic ? null : __getBlkInfo(slice.ptr); |
| 1563 |
auto info = bic ? *bic : query(slice.ptr); |
| 1564 |
|
| 1565 |
if (!(info.attr & BlkAttr.APPENDABLE)) |
| 1566 |
// not appendable |
| 1567 |
return false; |
| 1568 |
|
| 1569 |
assert(info.base); // sanity check |
| 1570 |
|
| 1571 |
immutable offset = slice.ptr - __arrayStart(info); |
| 1572 |
existingUsed += offset; |
| 1573 |
auto newUsed = slice.length + offset; |
| 1574 |
|
| 1575 |
size_t typeInfoSize = (info.attr & BlkAttr.STRUCTFINAL) ? size_t.sizeof : 0; |
| 1576 |
|
| 1577 |
if (__setArrayAllocLengthImpl(info, newUsed, atomic, existingUsed, typeInfoSize)) |
| 1578 |
{ |
| 1579 |
if (!bic && !atomic) |
| 1580 |
__insertBlkInfoCache(info, null); |
| 1581 |
return true; |
| 1582 |
} |
| 1583 |
|
| 1584 |
return false; |
| 1585 |
} |
| 1586 |
|
| 1587 |
size_t reserveArrayCapacity(void[] slice, size_t request, bool atomic = false) nothrow @trusted |
| 1588 |
{ |
| 1589 |
import core.internal.gc.blockmeta; |
| 1590 |
import core.internal.gc.blkcache; |
| 1591 |
import core.internal.array.utils; |
| 1592 |
|
| 1593 |
// lookup the block info, using the cache if possible. |
| 1594 |
auto bic = atomic ? null : __getBlkInfo(slice.ptr); |
| 1595 |
auto info = bic ? *bic : query(slice.ptr); |
| 1596 |
|
| 1597 |
if (!(info.attr & BlkAttr.APPENDABLE)) |
| 1598 |
// not appendable |
| 1599 |
return 0; |
| 1600 |
|
| 1601 |
assert(info.base); // sanity check |
| 1602 |
|
| 1603 |
immutable offset = slice.ptr - __arrayStart(info); |
| 1604 |
request += offset; |
| 1605 |
auto existingUsed = slice.length + offset; |
| 1606 |
|
| 1607 |
// make sure this slice ends at the used space |
| 1608 |
auto blockUsed = atomic ? __arrayAllocLengthAtomic(info) : __arrayAllocLength(info); |
| 1609 |
if (existingUsed != blockUsed) |
| 1610 |
// not an expandable slice. |
| 1611 |
return 0; |
| 1612 |
|
| 1613 |
// see if the capacity can contain the existing data |
| 1614 |
auto existingCapacity = __arrayAllocCapacity(info); |
| 1615 |
if (existingCapacity < request) |
| 1616 |
{ |
| 1617 |
if (info.size < PAGESIZE) |
| 1618 |
// no possibility to extend |
| 1619 |
return 0; |
| 1620 |
|
| 1621 |
immutable requiredExtension = request - existingCapacity; |
| 1622 |
auto extendedSize = extend(info.base, requiredExtension, requiredExtension, null); |
| 1623 |
if (extendedSize == 0) |
| 1624 |
// could not extend, can't satisfy the request |
| 1625 |
return 0; |
| 1626 |
|
| 1627 |
info.size = extendedSize; |
| 1628 |
|
| 1629 |
// update the block info cache if it was used |
| 1630 |
if (bic) |
| 1631 |
*bic = info; |
| 1632 |
else if (!atomic) |
| 1633 |
__insertBlkInfoCache(info, null); |
| 1634 |
|
| 1635 |
existingCapacity = __arrayAllocCapacity(info); |
| 1636 |
} |
| 1637 |
|
| 1638 |
return existingCapacity - offset; |
| 1639 |
} |
| 1640 |
} |
| 1641 |
|
| 1642 |
|
| 1643 |
/* ============================ Gcx =============================== */ |
| 1644 |
|
| 1645 |
enum |
| 1646 |
{ PAGESIZE = 4096, |
| 1647 |
} |
| 1648 |
|
| 1649 |
|
| 1650 |
enum Bins : ubyte |
| 1651 |
{ |
| 1652 |
B_16, |
| 1653 |
B_32, |
| 1654 |
B_48, |
| 1655 |
B_64, |
| 1656 |
B_96, |
| 1657 |
B_128, |
| 1658 |
B_176, |
| 1659 |
B_256, |
| 1660 |
B_368, |
| 1661 |
B_512, |
| 1662 |
B_816, |
| 1663 |
B_1024, |
| 1664 |
B_1360, |
| 1665 |
B_2048, |
| 1666 |
B_NUMSMALL, |
| 1667 |
|
| 1668 |
B_PAGE = B_NUMSMALL,// start of large alloc |
| 1669 |
B_PAGEPLUS, // continuation of large alloc |
| 1670 |
B_FREE, // free page |
| 1671 |
B_MAX, |
| 1672 |
} |
| 1673 |
|
| 1674 |
struct List |
| 1675 |
{ |
| 1676 |
List *next; |
| 1677 |
Pool *pool; |
| 1678 |
} |
| 1679 |
|
| 1680 |
// non power of two sizes optimized for small remainder within page (<= 64 bytes) |
| 1681 |
immutable short[Bins.B_NUMSMALL + 1] binsize = [ 16, 32, 48, 64, 96, 128, 176, 256, 368, 512, 816, 1024, 1360, 2048, 4096 ]; |
| 1682 |
immutable short[PAGESIZE / 16][Bins.B_NUMSMALL + 1] binbase = calcBinBase(); |
| 1683 |
|
| 1684 |
short[PAGESIZE / 16][Bins.B_NUMSMALL + 1] calcBinBase() |
| 1685 |
{ |
| 1686 |
short[PAGESIZE / 16][Bins.B_NUMSMALL + 1] bin; |
| 1687 |
|
| 1688 |
foreach (i, size; binsize) |
| 1689 |
{ |
| 1690 |
short end = cast(short) ((PAGESIZE / size) * size); |
| 1691 |
short bsz = size / 16; |
| 1692 |
foreach (off; 0..PAGESIZE/16) |
| 1693 |
{ |
| 1694 |
// add the remainder to the last bin, so no check during scanning |
| 1695 |
// is needed if a false pointer targets that area |
| 1696 |
const base = (off - off % bsz) * 16; |
| 1697 |
bin[i][off] = cast(short)(base < end ? base : end - size); |
| 1698 |
} |
| 1699 |
} |
| 1700 |
return bin; |
| 1701 |
} |
| 1702 |
|
| 1703 |
size_t baseOffset(size_t offset, Bins bin) @nogc nothrow |
| 1704 |
{ |
| 1705 |
assert(bin <= Bins.B_PAGE); |
| 1706 |
return (offset & ~(PAGESIZE - 1)) + binbase[bin][(offset & (PAGESIZE - 1)) >> 4]; |
| 1707 |
} |
| 1708 |
|
| 1709 |
alias PageBits = GCBits.wordtype[PAGESIZE / 16 / GCBits.BITS_PER_WORD]; |
| 1710 |
static assert(PAGESIZE % (GCBits.BITS_PER_WORD * 16) == 0); |
| 1711 |
|
| 1712 |
// bitmask with bits set at base offsets of objects |
| 1713 |
immutable PageBits[Bins.B_NUMSMALL] baseOffsetBits = (){ |
| 1714 |
PageBits[Bins.B_NUMSMALL] bits; |
| 1715 |
foreach (bin; 0 .. Bins.B_NUMSMALL) |
| 1716 |
{ |
| 1717 |
size_t size = binsize[bin]; |
| 1718 |
const top = PAGESIZE - size + 1; // ensure <size> bytes available even if unaligned |
| 1719 |
for (size_t u = 0; u < top; u += size) |
| 1720 |
{ |
| 1721 |
size_t biti = u / 16; |
| 1722 |
size_t off = biti / GCBits.BITS_PER_WORD; |
| 1723 |
size_t mod = biti % GCBits.BITS_PER_WORD; |
| 1724 |
bits[bin][off] |= GCBits.BITS_1 << mod; |
| 1725 |
} |
| 1726 |
} |
| 1727 |
return bits; |
| 1728 |
}(); |
| 1729 |
|
| 1730 |
private void set(ref PageBits bits, size_t i) @nogc pure nothrow |
| 1731 |
{ |
| 1732 |
assert(i < PageBits.sizeof * 8); |
| 1733 |
bts(bits.ptr, i); |
| 1734 |
} |
| 1735 |
|
| 1736 |
/* ============================ Gcx =============================== */ |
| 1737 |
|
| 1738 |
struct Gcx |
| 1739 |
{ |
| 1740 |
auto rootsLock = shared(AlignedSpinLock)(SpinLock.Contention.brief); |
| 1741 |
auto rangesLock = shared(AlignedSpinLock)(SpinLock.Contention.brief); |
| 1742 |
Treap!Root roots; |
| 1743 |
Treap!Range ranges; |
| 1744 |
bool minimizeAfterNextCollection = false; |
| 1745 |
version (COLLECT_FORK) |
| 1746 |
{ |
| 1747 |
private pid_t markProcPid = 0; |
| 1748 |
bool shouldFork; |
| 1749 |
} |
| 1750 |
|
| 1751 |
debug(INVARIANT) bool initialized; |
| 1752 |
debug(INVARIANT) bool inCollection; |
| 1753 |
uint disabled; // turn off collections if >0 |
| 1754 |
|
| 1755 |
PoolTable!Pool pooltable; |
| 1756 |
|
| 1757 |
List*[Bins.B_NUMSMALL] bucket; // free list for each small size |
| 1758 |
|
| 1759 |
// run a collection when reaching those thresholds (number of used pages) |
| 1760 |
float smallCollectThreshold = 0.0f, largeCollectThreshold = 0.0f; |
| 1761 |
uint usedSmallPages, usedLargePages; |
| 1762 |
// total number of mapped pages |
| 1763 |
uint mappedPages; |
| 1764 |
|
| 1765 |
debug (LOGGING) |
| 1766 |
LeakDetector leakDetector; |
| 1767 |
else |
| 1768 |
alias leakDetector = LeakDetector; |
| 1769 |
|
| 1770 |
SmallObjectPool*[Bins.B_NUMSMALL] recoverPool; |
| 1771 |
version (Posix) __gshared Gcx* instance; |
| 1772 |
|
| 1773 |
void initialize() |
| 1774 |
{ |
| 1775 |
(cast(byte*)&this)[0 .. Gcx.sizeof] = 0; |
| 1776 |
leakDetector.initialize(&this); |
| 1777 |
roots.initialize(0x243F6A8885A308D3UL); |
| 1778 |
ranges.initialize(0x13198A2E03707344UL); |
| 1779 |
smallCollectThreshold = largeCollectThreshold = 0.0f; |
| 1780 |
usedSmallPages = usedLargePages = 0; |
| 1781 |
mappedPages = 0; |
| 1782 |
//printf("gcx = %p, self = %x\n", &this, self); |
| 1783 |
version (Posix) |
| 1784 |
{ |
| 1785 |
import core.sys.posix.pthread : pthread_atfork; |
| 1786 |
instance = &this; |
| 1787 |
__gshared atforkHandlersInstalled = false; |
| 1788 |
if (!atforkHandlersInstalled) |
| 1789 |
{ |
| 1790 |
pthread_atfork( |
| 1791 |
&_d_gcx_atfork_prepare, |
| 1792 |
&_d_gcx_atfork_parent, |
| 1793 |
&_d_gcx_atfork_child); |
| 1794 |
atforkHandlersInstalled = true; |
| 1795 |
} |
| 1796 |
} |
| 1797 |
debug(INVARIANT) initialized = true; |
| 1798 |
version (COLLECT_FORK) |
| 1799 |
shouldFork = config.fork; |
| 1800 |
|
| 1801 |
} |
| 1802 |
|
| 1803 |
void Dtor() |
| 1804 |
{ |
| 1805 |
if (config.profile) |
| 1806 |
{ |
| 1807 |
printf("\tNumber of collections: %llu\n", cast(ulong)numCollections); |
| 1808 |
printf("\tTotal GC prep time: %lld milliseconds\n", |
| 1809 |
prepTime.total!("msecs")); |
| 1810 |
printf("\tTotal mark time: %lld milliseconds\n", |
| 1811 |
markTime.total!("msecs")); |
| 1812 |
printf("\tTotal sweep time: %lld milliseconds\n", |
| 1813 |
sweepTime.total!("msecs")); |
| 1814 |
long maxPause = maxPauseTime.total!("msecs"); |
| 1815 |
printf("\tMax Pause Time: %lld milliseconds\n", maxPause); |
| 1816 |
long gcTime = (sweepTime + markTime + prepTime).total!("msecs"); |
| 1817 |
printf("\tGrand total GC time: %lld milliseconds\n", gcTime); |
| 1818 |
long pauseTime = (markTime + prepTime).total!("msecs"); |
| 1819 |
|
| 1820 |
char[30] apitxt = void; |
| 1821 |
apitxt[0] = 0; |
| 1822 |
debug(PROFILE_API) if (config.profile > 1) |
| 1823 |
{ |
| 1824 |
static Duration toDuration(long dur) |
| 1825 |
{ |
| 1826 |
return MonoTime(dur) - MonoTime(0); |
| 1827 |
} |
| 1828 |
|
| 1829 |
printf("\n"); |
| 1830 |
printf("\tmalloc: %llu calls, %lld ms\n", cast(ulong)numMallocs, toDuration(mallocTime).total!"msecs"); |
| 1831 |
printf("\trealloc: %llu calls, %lld ms\n", cast(ulong)numReallocs, toDuration(reallocTime).total!"msecs"); |
| 1832 |
printf("\tfree: %llu calls, %lld ms\n", cast(ulong)numFrees, toDuration(freeTime).total!"msecs"); |
| 1833 |
printf("\textend: %llu calls, %lld ms\n", cast(ulong)numExtends, toDuration(extendTime).total!"msecs"); |
| 1834 |
printf("\tother: %llu calls, %lld ms\n", cast(ulong)numOthers, toDuration(otherTime).total!"msecs"); |
| 1835 |
printf("\tlock time: %lld ms\n", toDuration(lockTime).total!"msecs"); |
| 1836 |
|
| 1837 |
long apiTime = mallocTime + reallocTime + freeTime + extendTime + otherTime + lockTime; |
| 1838 |
printf("\tGC API: %lld ms\n", toDuration(apiTime).total!"msecs"); |
| 1839 |
sprintf(apitxt.ptr, " API%5lld ms", toDuration(apiTime).total!"msecs"); |
| 1840 |
} |
| 1841 |
|
| 1842 |
printf("GC summary:%5lld MB,%5lld GC%5lld ms, Pauses%5lld ms <%5lld ms%s\n", |
| 1843 |
cast(long) maxPoolMemory >> 20, cast(ulong)numCollections, gcTime, |
| 1844 |
pauseTime, maxPause, apitxt.ptr); |
| 1845 |
} |
| 1846 |
|
| 1847 |
version (Posix) |
| 1848 |
instance = null; |
| 1849 |
version (COLLECT_PARALLEL) |
| 1850 |
stopScanThreads(); |
| 1851 |
|
| 1852 |
debug(INVARIANT) initialized = false; |
| 1853 |
|
| 1854 |
foreach (Pool* pool; this.pooltable[]) |
| 1855 |
{ |
| 1856 |
mappedPages -= pool.npages; |
| 1857 |
pool.Dtor(); |
| 1858 |
cstdlib.free(pool); |
| 1859 |
} |
| 1860 |
assert(!mappedPages); |
| 1861 |
pooltable.Dtor(); |
| 1862 |
|
| 1863 |
roots.removeAll(); |
| 1864 |
ranges.removeAll(); |
| 1865 |
toscanConservative.reset(); |
| 1866 |
toscanPrecise.reset(); |
| 1867 |
} |
| 1868 |
|
| 1869 |
|
| 1870 |
void Invariant() const { } |
| 1871 |
|
| 1872 |
debug(INVARIANT) |
| 1873 |
invariant |
| 1874 |
{ |
| 1875 |
if (initialized) |
| 1876 |
{ |
| 1877 |
//printf("Gcx.invariant(): this = %p\n", &this); |
| 1878 |
pooltable.Invariant(); |
| 1879 |
for (size_t p = 0; p < pooltable.length; p++) |
| 1880 |
if (pooltable.pools[p].isLargeObject) |
| 1881 |
(cast(LargeObjectPool*)(pooltable.pools[p])).Invariant(); |
| 1882 |
else |
| 1883 |
(cast(SmallObjectPool*)(pooltable.pools[p])).Invariant(); |
| 1884 |
|
| 1885 |
if (!inCollection) |
| 1886 |
(cast()rangesLock).lock(); |
| 1887 |
foreach (range; ranges) |
| 1888 |
{ |
| 1889 |
assert(range.pbot); |
| 1890 |
assert(range.ptop); |
| 1891 |
assert(range.pbot <= range.ptop); |
| 1892 |
} |
| 1893 |
if (!inCollection) |
| 1894 |
(cast()rangesLock).unlock(); |
| 1895 |
|
| 1896 |
for (size_t i = 0; i < Bins.B_NUMSMALL; i++) |
| 1897 |
{ |
| 1898 |
size_t j = 0; |
| 1899 |
List* prev, pprev, ppprev; // keep a short history to inspect in the debugger |
| 1900 |
for (auto list = cast(List*)bucket[i]; list; list = list.next) |
| 1901 |
{ |
| 1902 |
auto pool = list.pool; |
| 1903 |
auto biti = cast(size_t)(cast(void*)list - pool.baseAddr) >> Pool.ShiftBy.Small; |
| 1904 |
assert(pool.freebits.test(biti)); |
| 1905 |
ppprev = pprev; |
| 1906 |
pprev = prev; |
| 1907 |
prev = list; |
| 1908 |
} |
| 1909 |
} |
| 1910 |
} |
| 1911 |
} |
| 1912 |
|
| 1913 |
@property bool collectInProgress() const nothrow |
| 1914 |
{ |
| 1915 |
version (COLLECT_FORK) |
| 1916 |
return markProcPid != 0; |
| 1917 |
else |
| 1918 |
return false; |
| 1919 |
} |
| 1920 |
|
| 1921 |
|
| 1922 |
/** |
| 1923 |
* |
| 1924 |
*/ |
| 1925 |
void addRoot(void *p) nothrow @nogc |
| 1926 |
{ |
| 1927 |
rootsLock.lock(); |
| 1928 |
scope (failure) rootsLock.unlock(); |
| 1929 |
roots.insert(Root(p)); |
| 1930 |
rootsLock.unlock(); |
| 1931 |
} |
| 1932 |
|
| 1933 |
|
| 1934 |
/** |
| 1935 |
* |
| 1936 |
*/ |
| 1937 |
void removeRoot(void *p) nothrow @nogc |
| 1938 |
{ |
| 1939 |
rootsLock.lock(); |
| 1940 |
scope (failure) rootsLock.unlock(); |
| 1941 |
roots.remove(Root(p)); |
| 1942 |
rootsLock.unlock(); |
| 1943 |
} |
| 1944 |
|
| 1945 |
|
| 1946 |
/** |
| 1947 |
* |
| 1948 |
*/ |
| 1949 |
int rootsApply(scope int delegate(ref Root) nothrow dg) nothrow |
| 1950 |
{ |
| 1951 |
rootsLock.lock(); |
| 1952 |
scope (failure) rootsLock.unlock(); |
| 1953 |
auto ret = roots.opApply(dg); |
| 1954 |
rootsLock.unlock(); |
| 1955 |
return ret; |
| 1956 |
} |
| 1957 |
|
| 1958 |
|
| 1959 |
/** |
| 1960 |
* |
| 1961 |
*/ |
| 1962 |
void addRange(void *pbot, void *ptop, const TypeInfo ti) nothrow @nogc |
| 1963 |
{ |
| 1964 |
//debug(PRINTF) printf("Thread %x ", pthread_self()); |
| 1965 |
debug(PRINTF) printf("%p.Gcx::addRange(%p, %p)\n", &this, pbot, ptop); |
| 1966 |
rangesLock.lock(); |
| 1967 |
scope (failure) rangesLock.unlock(); |
| 1968 |
ranges.insert(Range(pbot, ptop)); |
| 1969 |
rangesLock.unlock(); |
| 1970 |
} |
| 1971 |
|
| 1972 |
|
| 1973 |
/** |
| 1974 |
* |
| 1975 |
*/ |
| 1976 |
void removeRange(void *pbot) nothrow @nogc |
| 1977 |
{ |
| 1978 |
//debug(PRINTF) printf("Thread %x ", pthread_self()); |
| 1979 |
debug(PRINTF) printf("Gcx.removeRange(%p)\n", pbot); |
| 1980 |
rangesLock.lock(); |
| 1981 |
scope (failure) rangesLock.unlock(); |
| 1982 |
ranges.remove(Range(pbot, pbot)); // only pbot is used, see Range.opCmp |
| 1983 |
rangesLock.unlock(); |
| 1984 |
|
| 1985 |
// debug(PRINTF) printf("Wrong thread\n"); |
| 1986 |
// This is a fatal error, but ignore it. |
| 1987 |
// The problem is that we can get a Close() call on a thread |
| 1988 |
// other than the one the range was allocated on. |
| 1989 |
//assert(zero); |
| 1990 |
} |
| 1991 |
|
| 1992 |
/** |
| 1993 |
* |
| 1994 |
*/ |
| 1995 |
int rangesApply(scope int delegate(ref Range) nothrow dg) nothrow |
| 1996 |
{ |
| 1997 |
rangesLock.lock(); |
| 1998 |
scope (failure) rangesLock.unlock(); |
| 1999 |
auto ret = ranges.opApply(dg); |
| 2000 |
rangesLock.unlock(); |
| 2001 |
return ret; |
| 2002 |
} |
| 2003 |
|
| 2004 |
|
| 2005 |
/** |
| 2006 |
* |
| 2007 |
*/ |
| 2008 |
void runFinalizers(const scope void[] segment) nothrow |
| 2009 |
{ |
| 2010 |
ConservativeGC._inFinalizer = true; |
| 2011 |
scope (failure) ConservativeGC._inFinalizer = false; |
| 2012 |
|
| 2013 |
foreach (pool; this.pooltable[]) |
| 2014 |
{ |
| 2015 |
if (!pool.finals.nbits) continue; |
| 2016 |
|
| 2017 |
if (pool.isLargeObject) |
| 2018 |
{ |
| 2019 |
auto lpool = cast(LargeObjectPool*) pool; |
| 2020 |
lpool.runFinalizers(segment); |
| 2021 |
} |
| 2022 |
else |
| 2023 |
{ |
| 2024 |
auto spool = cast(SmallObjectPool*) pool; |
| 2025 |
spool.runFinalizers(segment); |
| 2026 |
} |
| 2027 |
} |
| 2028 |
ConservativeGC._inFinalizer = false; |
| 2029 |
} |
| 2030 |
|
| 2031 |
Pool* findPool(void* p) pure nothrow @nogc |
| 2032 |
{ |
| 2033 |
return pooltable.findPool(p); |
| 2034 |
} |
| 2035 |
|
| 2036 |
/** |
| 2037 |
* Find base address of block containing pointer p. |
| 2038 |
* Returns null if not a gc'd pointer |
| 2039 |
*/ |
| 2040 |
void* findBase(void *p) nothrow @nogc |
| 2041 |
{ |
| 2042 |
Pool *pool; |
| 2043 |
|
| 2044 |
pool = findPool(p); |
| 2045 |
if (pool) |
| 2046 |
return pool.findBase(p); |
| 2047 |
return null; |
| 2048 |
} |
| 2049 |
|
| 2050 |
|
| 2051 |
/** |
| 2052 |
* Find size of pointer p. |
| 2053 |
* Returns 0 if not a gc'd pointer |
| 2054 |
*/ |
| 2055 |
size_t findSize(void *p) nothrow @nogc |
| 2056 |
{ |
| 2057 |
Pool* pool = findPool(p); |
| 2058 |
if (pool) |
| 2059 |
return pool.slGetSize(p); |
| 2060 |
return 0; |
| 2061 |
} |
| 2062 |
|
| 2063 |
/** |
| 2064 |
* |
| 2065 |
*/ |
| 2066 |
BlkInfo getInfo(void* p) nothrow |
| 2067 |
{ |
| 2068 |
Pool* pool = findPool(p); |
| 2069 |
if (pool) |
| 2070 |
return pool.slGetInfo(p); |
| 2071 |
return BlkInfo(); |
| 2072 |
} |
| 2073 |
|
| 2074 |
/** |
| 2075 |
* Computes the bin table using CTFE. |
| 2076 |
*/ |
| 2077 |
static Bins[2049] ctfeBins() nothrow |
| 2078 |
{ |
| 2079 |
Bins[2049] ret; |
| 2080 |
size_t p = 0; |
| 2081 |
for (Bins b = Bins.B_16; b <= Bins.B_2048; b++) |
| 2082 |
for ( ; p <= binsize[b]; p++) |
| 2083 |
ret[p] = b; |
| 2084 |
|
| 2085 |
return ret; |
| 2086 |
} |
| 2087 |
|
| 2088 |
static immutable Bins[2049] binTable = ctfeBins(); |
| 2089 |
|
| 2090 |
/** |
| 2091 |
* Allocate a new pool of at least size bytes. |
| 2092 |
* Sort it into pooltable[]. |
| 2093 |
* Mark all memory in the pool as B_FREE. |
| 2094 |
* Return the actual number of bytes reserved or 0 on error. |
| 2095 |
*/ |
| 2096 |
size_t reserve(size_t size) nothrow |
| 2097 |
{ |
| 2098 |
size_t npages = (size + PAGESIZE - 1) / PAGESIZE; |
| 2099 |
|
| 2100 |
// Assume reserve() is for small objects. |
| 2101 |
Pool* pool = newPool(npages, false); |
| 2102 |
|
| 2103 |
if (!pool) |
| 2104 |
return 0; |
| 2105 |
return pool.npages * PAGESIZE; |
| 2106 |
} |
| 2107 |
|
| 2108 |
/** |
| 2109 |
* Update the thresholds for when to collect the next time |
| 2110 |
*/ |
| 2111 |
void updateCollectThresholds() nothrow |
| 2112 |
{ |
| 2113 |
static float max(float a, float b) nothrow |
| 2114 |
{ |
| 2115 |
return a >= b ? a : b; |
| 2116 |
} |
| 2117 |
|
| 2118 |
// instantly increases, slowly decreases |
| 2119 |
static float smoothDecay(float oldVal, float newVal) nothrow |
| 2120 |
{ |
| 2121 |
// decay to 63.2% of newVal over 5 collections |
| 2122 |
// http://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter |
| 2123 |
enum alpha = 1.0 / (5 + 1); |
| 2124 |
immutable decay = (newVal - oldVal) * alpha + oldVal; |
| 2125 |
return max(newVal, decay); |
| 2126 |
} |
| 2127 |
|
| 2128 |
immutable smTarget = usedSmallPages * config.heapSizeFactor; |
| 2129 |
smallCollectThreshold = smoothDecay(smallCollectThreshold, smTarget); |
| 2130 |
immutable lgTarget = usedLargePages * config.heapSizeFactor; |
| 2131 |
largeCollectThreshold = smoothDecay(largeCollectThreshold, lgTarget); |
| 2132 |
} |
| 2133 |
|
| 2134 |
/** |
| 2135 |
* Minimizes physical memory usage by returning free pools to the OS. |
| 2136 |
*/ |
| 2137 |
void minimize() nothrow |
| 2138 |
{ |
| 2139 |
debug(PRINTF) printf("Minimizing.\n"); |
| 2140 |
|
| 2141 |
foreach (pool; pooltable.minimize()) |
| 2142 |
{ |
| 2143 |
debug(PRINTF) printFreeInfo(pool); |
| 2144 |
mappedPages -= pool.npages; |
| 2145 |
pool.Dtor(); |
| 2146 |
cstdlib.free(pool); |
| 2147 |
} |
| 2148 |
|
| 2149 |
debug(PRINTF) printf("Done minimizing.\n"); |
| 2150 |
} |
| 2151 |
|
| 2152 |
private @property bool lowMem() const nothrow |
| 2153 |
{ |
| 2154 |
return isLowOnMem(cast(size_t)mappedPages * PAGESIZE); |
| 2155 |
} |
| 2156 |
|
| 2157 |
void* alloc(size_t size, ref size_t alloc_size, uint bits, const TypeInfo ti) nothrow |
| 2158 |
{ |
| 2159 |
return size <= PAGESIZE/2 ? smallAlloc(size, alloc_size, bits, ti) |
| 2160 |
: bigAlloc(size, alloc_size, bits, ti); |
| 2161 |
} |
| 2162 |
|
| 2163 |
void* smallAlloc(size_t size, ref size_t alloc_size, uint bits, const TypeInfo ti) nothrow |
| 2164 |
{ |
| 2165 |
immutable bin = binTable[size]; |
| 2166 |
alloc_size = binsize[bin]; |
| 2167 |
|
| 2168 |
void* p = bucket[bin]; |
| 2169 |
if (p) |
| 2170 |
goto L_hasBin; |
| 2171 |
|
| 2172 |
if (recoverPool[bin]) |
| 2173 |
recoverNextPage(bin); |
| 2174 |
|
| 2175 |
bool tryAlloc() nothrow |
| 2176 |
{ |
| 2177 |
if (!bucket[bin]) |
| 2178 |
{ |
| 2179 |
bucket[bin] = allocPage(bin); |
| 2180 |
if (!bucket[bin]) |
| 2181 |
return false; |
| 2182 |
} |
| 2183 |
p = bucket[bin]; |
| 2184 |
return true; |
| 2185 |
} |
| 2186 |
|
| 2187 |
if (!tryAlloc()) |
| 2188 |
{ |
| 2189 |
if (!lowMem && (disabled || usedSmallPages < smallCollectThreshold)) |
| 2190 |
{ |
| 2191 |
// disabled or threshold not reached => allocate a new pool instead of collecting |
| 2192 |
if (!newPool(1, false)) |
| 2193 |
{ |
| 2194 |
// out of memory => try to free some memory |
| 2195 |
fullcollect(false, true); // stop the world |
| 2196 |
if (lowMem) |
| 2197 |
minimize(); |
| 2198 |
recoverNextPage(bin); |
| 2199 |
} |
| 2200 |
} |
| 2201 |
else if (usedSmallPages > 0) |
| 2202 |
{ |
| 2203 |
fullcollect(); |
| 2204 |
if (lowMem) |
| 2205 |
minimize(); |
| 2206 |
recoverNextPage(bin); |
| 2207 |
} |
| 2208 |
// tryAlloc will succeed if a new pool was allocated above, if it fails allocate a new pool now |
| 2209 |
if (!tryAlloc() && (!newPool(1, false) || !tryAlloc())) |
| 2210 |
// out of luck or memory |
| 2211 |
onOutOfMemoryError(); |
| 2212 |
} |
| 2213 |
assert(p !is null); |
| 2214 |
L_hasBin: |
| 2215 |
// Return next item from free list |
| 2216 |
bucket[bin] = undefinedRead((cast(List*)p).next); |
| 2217 |
auto pool = undefinedRead((cast(List*)p).pool); |
| 2218 |
|
| 2219 |
auto biti = (p - pool.baseAddr) >> pool.shiftBy; |
| 2220 |
assert(pool.freebits.test(biti)); |
| 2221 |
if (collectInProgress) |
| 2222 |
pool.mark.setLocked(biti); // be sure that the child is aware of the page being used |
| 2223 |
pool.freebits.clear(biti); |
| 2224 |
if (bits) |
| 2225 |
pool.setBits(biti, bits); |
| 2226 |
//debug(PRINTF) printf("\tmalloc => %p\n", p); |
| 2227 |
invalidate(p[0 .. alloc_size], 0xF0, true); |
| 2228 |
|
| 2229 |
if (ConservativeGC.isPrecise) |
| 2230 |
{ |
| 2231 |
debug(SENTINEL) |
| 2232 |
pool.setPointerBitmapSmall(sentinel_add(p), size - SENTINEL_EXTRA, size - SENTINEL_EXTRA, bits, ti); |
| 2233 |
else |
| 2234 |
pool.setPointerBitmapSmall(p, size, alloc_size, bits, ti); |
| 2235 |
} |
| 2236 |
return p; |
| 2237 |
} |
| 2238 |
|
| 2239 |
/** |
| 2240 |
* Allocate a chunk of memory that is larger than a page. |
| 2241 |
* Return null if out of memory. |
| 2242 |
*/ |
| 2243 |
void* bigAlloc(size_t size, ref size_t alloc_size, uint bits, const TypeInfo ti = null) nothrow |
| 2244 |
{ |
| 2245 |
debug(PRINTF) printf("In bigAlloc. Size: %zd\n", size); |
| 2246 |
|
| 2247 |
LargeObjectPool* pool; |
| 2248 |
size_t pn; |
| 2249 |
immutable npages = LargeObjectPool.numPages(size); |
| 2250 |
if (npages == size_t.max) |
| 2251 |
onOutOfMemoryError(); // size just below size_t.max requested |
| 2252 |
|
| 2253 |
bool tryAlloc() nothrow |
| 2254 |
{ |
| 2255 |
foreach (p; this.pooltable[]) |
| 2256 |
{ |
| 2257 |
if (!p.isLargeObject || p.freepages < npages) |
| 2258 |
continue; |
| 2259 |
auto lpool = cast(LargeObjectPool*) p; |
| 2260 |
if ((pn = lpool.allocPages(npages)) == OPFAIL) |
| 2261 |
continue; |
| 2262 |
pool = lpool; |
| 2263 |
return true; |
| 2264 |
} |
| 2265 |
return false; |
| 2266 |
} |
| 2267 |
|
| 2268 |
bool tryAllocNewPool() nothrow |
| 2269 |
{ |
| 2270 |
pool = cast(LargeObjectPool*) newPool(npages, true); |
| 2271 |
if (!pool) return false; |
| 2272 |
pn = pool.allocPages(npages); |
| 2273 |
assert(pn != OPFAIL); |
| 2274 |
return true; |
| 2275 |
} |
| 2276 |
|
| 2277 |
if (!tryAlloc()) |
| 2278 |
{ |
| 2279 |
if (!lowMem && (disabled || usedLargePages < largeCollectThreshold)) |
| 2280 |
{ |
| 2281 |
// disabled or threshold not reached => allocate a new pool instead of collecting |
| 2282 |
if (!tryAllocNewPool()) |
| 2283 |
{ |
| 2284 |
// disabled but out of memory => try to free some memory |
| 2285 |
minimizeAfterNextCollection = true; |
| 2286 |
fullcollect(false, true); |
| 2287 |
} |
| 2288 |
} |
| 2289 |
else if (usedLargePages > 0) |
| 2290 |
{ |
| 2291 |
minimizeAfterNextCollection = true; |
| 2292 |
fullcollect(); |
| 2293 |
} |
| 2294 |
// If alloc didn't yet succeed retry now that we collected/minimized |
| 2295 |
if (!pool && !tryAlloc() && !tryAllocNewPool()) |
| 2296 |
// out of luck or memory |
| 2297 |
return null; |
| 2298 |
} |
| 2299 |
assert(pool); |
| 2300 |
|
| 2301 |
debug(PRINTF) printFreeInfo(&pool.base); |
| 2302 |
if (collectInProgress) |
| 2303 |
pool.mark.setLocked(pn); |
| 2304 |
usedLargePages += npages; |
| 2305 |
|
| 2306 |
debug(PRINTF) printFreeInfo(&pool.base); |
| 2307 |
|
| 2308 |
auto p = pool.baseAddr + pn * PAGESIZE; |
| 2309 |
debug(PRINTF) printf("Got large alloc: %p, pt = %d, np = %zd\n", p, pool.pagetable[pn], npages); |
| 2310 |
invalidate(p[0 .. size], 0xF1, true); |
| 2311 |
alloc_size = npages * PAGESIZE; |
| 2312 |
//debug(PRINTF) printf("\tp = %p\n", p); |
| 2313 |
|
| 2314 |
if (bits) |
| 2315 |
pool.setBits(pn, bits); |
| 2316 |
|
| 2317 |
if (ConservativeGC.isPrecise) |
| 2318 |
{ |
| 2319 |
// an array of classes is in fact an array of pointers |
| 2320 |
immutable(void)* rtinfo; |
| 2321 |
if (!ti) |
| 2322 |
rtinfo = rtinfoHasPointers; |
| 2323 |
else if ((bits & BlkAttr.APPENDABLE) && (typeid(ti) is typeid(TypeInfo_Class))) |
| 2324 |
rtinfo = rtinfoHasPointers; |
| 2325 |
else |
| 2326 |
rtinfo = ti.rtInfo(); |
| 2327 |
pool.rtinfo[pn] = cast(immutable(size_t)*)rtinfo; |
| 2328 |
} |
| 2329 |
|
| 2330 |
return p; |
| 2331 |
} |
| 2332 |
|
| 2333 |
|
| 2334 |
/** |
| 2335 |
* Allocate a new pool with at least npages in it. |
| 2336 |
* Sort it into pooltable[]. |
| 2337 |
* Return null if failed. |
| 2338 |
*/ |
| 2339 |
Pool *newPool(size_t npages, bool isLargeObject) nothrow |
| 2340 |
{ |
| 2341 |
//debug(PRINTF) printf("************Gcx::newPool(npages = %d)****************\n", npages); |
| 2342 |
|
| 2343 |
// Minimum of POOLSIZE |
| 2344 |
size_t minPages = config.minPoolSize / PAGESIZE; |
| 2345 |
if (npages < minPages) |
| 2346 |
npages = minPages; |
| 2347 |
else if (npages > minPages) |
| 2348 |
{ // Give us 150% of requested size, so there's room to extend |
| 2349 |
auto n = npages + (npages >> 1); |
| 2350 |
if (n < size_t.max/PAGESIZE) |
| 2351 |
npages = n; |
| 2352 |
} |
| 2353 |
|
| 2354 |
// Allocate successively larger pools up to 8 megs |
| 2355 |
if (this.pooltable.length) |
| 2356 |
{ |
| 2357 |
size_t n; |
| 2358 |
|
| 2359 |
n = config.minPoolSize + config.incPoolSize * this.pooltable.length; |
| 2360 |
if (n > config.maxPoolSize) |
| 2361 |
n = config.maxPoolSize; // cap pool size |
| 2362 |
n /= PAGESIZE; // convert bytes to pages |
| 2363 |
if (npages < n) |
| 2364 |
npages = n; |
| 2365 |
} |
| 2366 |
|
| 2367 |
//printf("npages = %d\n", npages); |
| 2368 |
|
| 2369 |
auto pool = cast(Pool *)cstdlib.calloc(1, isLargeObject ? LargeObjectPool.sizeof : SmallObjectPool.sizeof); |
| 2370 |
if (pool) |
| 2371 |
{ |
| 2372 |
pool.initialize(npages, isLargeObject); |
| 2373 |
if (collectInProgress) |
| 2374 |
pool.mark.setAll(); |
| 2375 |
if (!pool.baseAddr || !pooltable.insert(pool)) |
| 2376 |
{ |
| 2377 |
pool.Dtor(); |
| 2378 |
cstdlib.free(pool); |
| 2379 |
return null; |
| 2380 |
} |
| 2381 |
} |
| 2382 |
|
| 2383 |
mappedPages += npages; |
| 2384 |
|
| 2385 |
if (config.profile) |
| 2386 |
{ |
| 2387 |
if (cast(size_t)mappedPages * PAGESIZE > maxPoolMemory) |
| 2388 |
maxPoolMemory = cast(size_t)mappedPages * PAGESIZE; |
| 2389 |
} |
| 2390 |
return pool; |
| 2391 |
} |
| 2392 |
|
| 2393 |
/** |
| 2394 |
* Allocate a page of bin's. |
| 2395 |
* Returns: |
| 2396 |
* head of a single linked list of new entries |
| 2397 |
*/ |
| 2398 |
List* allocPage(Bins bin) nothrow |
| 2399 |
{ |
| 2400 |
//debug(PRINTF) printf("Gcx::allocPage(bin = %d)\n", bin); |
| 2401 |
foreach (Pool* pool; this.pooltable[]) |
| 2402 |
{ |
| 2403 |
if (pool.isLargeObject) |
| 2404 |
continue; |
| 2405 |
if (List* p = (cast(SmallObjectPool*)pool).allocPage(bin)) |
| 2406 |
{ |
| 2407 |
++usedSmallPages; |
| 2408 |
return p; |
| 2409 |
} |
| 2410 |
} |
| 2411 |
return null; |
| 2412 |
} |
| 2413 |
|
| 2414 |
static struct ScanRange(bool precise) |
| 2415 |
{ |
| 2416 |
void* pbot; |
| 2417 |
void* ptop; |
| 2418 |
static if (precise) |
| 2419 |
{ |
| 2420 |
void** pbase; // start of memory described by ptrbitmap |
| 2421 |
size_t* ptrbmp; // bits from is_pointer or rtinfo |
| 2422 |
size_t bmplength; // number of valid bits |
| 2423 |
} |
| 2424 |
} |
| 2425 |
|
| 2426 |
static struct ToScanStack(RANGE) |
| 2427 |
{ |
| 2428 |
nothrow: |
| 2429 |
@disable this(this); |
| 2430 |
auto stackLock = shared(AlignedSpinLock)(SpinLock.Contention.brief); |
| 2431 |
|
| 2432 |
void reset() |
| 2433 |
{ |
| 2434 |
_length = 0; |
| 2435 |
if (_p) |
| 2436 |
{ |
| 2437 |
os_mem_unmap(_p, _cap * RANGE.sizeof); |
| 2438 |
_p = null; |
| 2439 |
} |
| 2440 |
_cap = 0; |
| 2441 |
} |
| 2442 |
void clear() |
| 2443 |
{ |
| 2444 |
_length = 0; |
| 2445 |
} |
| 2446 |
|
| 2447 |
void push(RANGE rng) |
| 2448 |
{ |
| 2449 |
if (_length == _cap) grow(); |
| 2450 |
_p[_length++] = rng; |
| 2451 |
} |
| 2452 |
|
| 2453 |
RANGE pop() |
| 2454 |
in { assert(!empty); } |
| 2455 |
do |
| 2456 |
{ |
| 2457 |
return _p[--_length]; |
| 2458 |
} |
| 2459 |
|
| 2460 |
bool popLocked(ref RANGE rng) |
| 2461 |
{ |
| 2462 |
if (_length == 0) |
| 2463 |
return false; |
| 2464 |
|
| 2465 |
stackLock.lock(); |
| 2466 |
scope(exit) stackLock.unlock(); |
| 2467 |
if (_length == 0) |
| 2468 |
return false; |
| 2469 |
rng = _p[--_length]; |
| 2470 |
return true; |
| 2471 |
} |
| 2472 |
|
| 2473 |
ref inout(RANGE) opIndex(size_t idx) inout |
| 2474 |
in { assert(idx < _length); } |
| 2475 |
do |
| 2476 |
{ |
| 2477 |
return _p[idx]; |
| 2478 |
} |
| 2479 |
|
| 2480 |
@property size_t length() const { return _length; } |
| 2481 |
@property bool empty() const { return !length; } |
| 2482 |
|
| 2483 |
private: |
| 2484 |
void grow() |
| 2485 |
{ |
| 2486 |
pragma(inline, false); |
| 2487 |
|
| 2488 |
enum initSize = 64 * 1024; // Windows VirtualAlloc granularity |
| 2489 |
immutable ncap = _cap ? 2 * _cap : initSize / RANGE.sizeof; |
| 2490 |
auto p = cast(RANGE*)os_mem_map(ncap * RANGE.sizeof); |
| 2491 |
if (p is null) onOutOfMemoryError(); |
| 2492 |
debug (VALGRIND) makeMemUndefined(p[0..ncap]); |
| 2493 |
if (_p !is null) |
| 2494 |
{ |
| 2495 |
p[0 .. _length] = _p[0 .. _length]; |
| 2496 |
os_mem_unmap(_p, _cap * RANGE.sizeof); |
| 2497 |
} |
| 2498 |
_p = p; |
| 2499 |
_cap = ncap; |
| 2500 |
} |
| 2501 |
|
| 2502 |
size_t _length; |
| 2503 |
RANGE* _p; |
| 2504 |
size_t _cap; |
| 2505 |
} |
| 2506 |
|
| 2507 |
ToScanStack!(ScanRange!false) toscanConservative; |
| 2508 |
ToScanStack!(ScanRange!true) toscanPrecise; |
| 2509 |
|
| 2510 |
template scanStack(bool precise) |
| 2511 |
{ |
| 2512 |
static if (precise) |
| 2513 |
alias scanStack = toscanPrecise; |
| 2514 |
else |
| 2515 |
alias scanStack = toscanConservative; |
| 2516 |
} |
| 2517 |
|
| 2518 |
/** |
| 2519 |
* Search a range of memory values and mark any pointers into the GC pool. |
| 2520 |
*/ |
| 2521 |
private void mark(bool precise, bool parallel, bool shared_mem)(ScanRange!precise rng) scope nothrow |
| 2522 |
{ |
| 2523 |
alias toscan = scanStack!precise; |
| 2524 |
|
| 2525 |
debug(MARK_PRINTF) |
| 2526 |
printf("marking range: [%p..%p] (%#llx)\n", rng.pbot, rng.ptop, cast(long)(rng.ptop - rng.pbot)); |
| 2527 |
|
| 2528 |
// limit the amount of ranges added to the toscan stack |
| 2529 |
enum FANOUT_LIMIT = 32; |
| 2530 |
size_t stackPos; |
| 2531 |
ScanRange!precise[FANOUT_LIMIT] stack = void; |
| 2532 |
|
| 2533 |
size_t pcache = 0; |
| 2534 |
|
| 2535 |
// let dmd allocate a register for this.pools |
| 2536 |
auto pools = pooltable.pools; |
| 2537 |
const highpool = pooltable.length - 1; |
| 2538 |
const minAddr = pooltable.minAddr; |
| 2539 |
size_t memSize = pooltable.maxAddr - minAddr; |
| 2540 |
Pool* pool = null; |
| 2541 |
|
| 2542 |
// properties of allocation pointed to |
| 2543 |
ScanRange!precise tgt = void; |
| 2544 |
|
| 2545 |
for (;;) |
| 2546 |
{ |
| 2547 |
auto p = undefinedRead(*cast(void**)(rng.pbot)); |
| 2548 |
debug (VALGRIND) makeMemDefined((&p)[0 .. 1]); |
| 2549 |
|
| 2550 |
debug(MARK_PRINTF) printf("\tmark %p: %p\n", rng.pbot, p); |
| 2551 |
|
| 2552 |
if (cast(size_t)(p - minAddr) < memSize && |
| 2553 |
(cast(size_t)p & ~cast(size_t)(PAGESIZE-1)) != pcache) |
| 2554 |
{ |
| 2555 |
static if (precise) if (rng.pbase) |
| 2556 |
{ |
| 2557 |
size_t bitpos = cast(void**)rng.pbot - rng.pbase; |
| 2558 |
while (bitpos >= rng.bmplength) |
| 2559 |
{ |
| 2560 |
bitpos -= rng.bmplength; |
| 2561 |
rng.pbase += rng.bmplength; |
| 2562 |
} |
| 2563 |
if (!core.bitop.bt(rng.ptrbmp, bitpos)) |
| 2564 |
{ |
| 2565 |
debug(MARK_PRINTF) printf("\t\tskipping non-pointer\n"); |
| 2566 |
goto LnextPtr; |
| 2567 |
} |
| 2568 |
} |
| 2569 |
|
| 2570 |
if (!pool || p < pool.baseAddr || p >= pool.topAddr) |
| 2571 |
{ |
| 2572 |
size_t low = 0; |
| 2573 |
size_t high = highpool; |
| 2574 |
while (true) |
| 2575 |
{ |
| 2576 |
size_t mid = (low + high) >> 1; |
| 2577 |
pool = pools[mid]; |
| 2578 |
if (p < pool.baseAddr) |
| 2579 |
high = mid - 1; |
| 2580 |
else if (p >= pool.topAddr) |
| 2581 |
low = mid + 1; |
| 2582 |
else break; |
| 2583 |
|
| 2584 |
if (low > high) |
| 2585 |
goto LnextPtr; |
| 2586 |
} |
| 2587 |
} |
| 2588 |
size_t offset = cast(size_t)(p - pool.baseAddr); |
| 2589 |
size_t biti = void; |
| 2590 |
size_t pn = offset / PAGESIZE; |
| 2591 |
size_t bin = pool.pagetable[pn]; // not Bins to avoid multiple size extension instructions |
| 2592 |
|
| 2593 |
debug(MARK_PRINTF) |
| 2594 |
printf("\t\tfound pool %p, base=%p, pn = %llu, bin = %llu\n", pool, pool.baseAddr, cast(ulong)pn, cast(ulong)bin); |
| 2595 |
|
| 2596 |
// Adjust bit to be at start of allocated memory block |
| 2597 |
if (bin < Bins.B_PAGE) |
| 2598 |
{ |
| 2599 |
// We don't care abou setting pointsToBase correctly |
| 2600 |
// because it's ignored for small object pools anyhow. |
| 2601 |
auto offsetBase = baseOffset(offset, cast(Bins)bin); |
| 2602 |
biti = offsetBase >> Pool.ShiftBy.Small; |
| 2603 |
//debug(PRINTF) printf("\t\tbiti = x%x\n", biti); |
| 2604 |
|
| 2605 |
if (!pool.mark.testAndSet!shared_mem(biti) && !pool.noscan.test(biti)) |
| 2606 |
{ |
| 2607 |
tgt.pbot = pool.baseAddr + offsetBase; |
| 2608 |
tgt.ptop = tgt.pbot + binsize[bin]; |
| 2609 |
static if (precise) |
| 2610 |
{ |
| 2611 |
tgt.pbase = cast(void**)pool.baseAddr; |
| 2612 |
tgt.ptrbmp = pool.is_pointer.data; |
| 2613 |
tgt.bmplength = size_t.max; // no repetition |
| 2614 |
} |
| 2615 |
goto LaddRange; |
| 2616 |
} |
| 2617 |
} |
| 2618 |
else if (bin == Bins.B_PAGE) |
| 2619 |
{ |
| 2620 |
biti = offset >> Pool.ShiftBy.Large; |
| 2621 |
//debug(PRINTF) printf("\t\tbiti = x%x\n", biti); |
| 2622 |
|
| 2623 |
pcache = cast(size_t)p & ~cast(size_t)(PAGESIZE-1); |
| 2624 |
tgt.pbot = cast(void*)pcache; |
| 2625 |
|
| 2626 |
// For the NO_INTERIOR attribute. This tracks whether |
| 2627 |
// the pointer is an interior pointer or points to the |
| 2628 |
// base address of a block. |
| 2629 |
if (tgt.pbot != sentinel_sub(p) && pool.nointerior.nbits && pool.nointerior.test(biti)) |
| 2630 |
goto LnextPtr; |
| 2631 |
|
| 2632 |
if (!pool.mark.testAndSet!shared_mem(biti) && !pool.noscan.test(biti)) |
| 2633 |
{ |
| 2634 |
tgt.ptop = tgt.pbot + (cast(LargeObjectPool*)pool).getSize(pn); |
| 2635 |
goto LaddLargeRange; |
| 2636 |
} |
| 2637 |
} |
| 2638 |
else if (bin == Bins.B_PAGEPLUS) |
| 2639 |
{ |
| 2640 |
pn -= pool.bPageOffsets[pn]; |
| 2641 |
biti = pn * (PAGESIZE >> Pool.ShiftBy.Large); |
| 2642 |
|
| 2643 |
pcache = cast(size_t)p & ~cast(size_t)(PAGESIZE-1); |
| 2644 |
if (pool.nointerior.nbits && pool.nointerior.test(biti)) |
| 2645 |
goto LnextPtr; |
| 2646 |
|
| 2647 |
if (!pool.mark.testAndSet!shared_mem(biti) && !pool.noscan.test(biti)) |
| 2648 |
{ |
| 2649 |
tgt.pbot = pool.baseAddr + (pn * PAGESIZE); |
| 2650 |
tgt.ptop = tgt.pbot + (cast(LargeObjectPool*)pool).getSize(pn); |
| 2651 |
LaddLargeRange: |
| 2652 |
static if (precise) |
| 2653 |
{ |
| 2654 |
auto rtinfo = pool.rtinfo[biti]; |
| 2655 |
if (rtinfo is rtinfoNoPointers) |
| 2656 |
goto LnextPtr; // only if inconsistent with noscan |
| 2657 |
if (rtinfo is rtinfoHasPointers) |
| 2658 |
{ |
| 2659 |
tgt.pbase = null; // conservative |
| 2660 |
} |
| 2661 |
else |
| 2662 |
{ |
| 2663 |
tgt.ptrbmp = cast(size_t*)rtinfo; |
| 2664 |
size_t element_size = *tgt.ptrbmp++; |
| 2665 |
tgt.bmplength = (element_size + (void*).sizeof - 1) / (void*).sizeof; |
| 2666 |
assert(tgt.bmplength); |
| 2667 |
|
| 2668 |
debug(SENTINEL) |
| 2669 |
tgt.pbot = sentinel_add(tgt.pbot); |
| 2670 |
if (pool.appendable.test(biti)) |
| 2671 |
{ |
| 2672 |
// take advantage of knowing array layout in rt.lifetime |
| 2673 |
void* arrtop = tgt.pbot + 16 + *cast(size_t*)tgt.pbot; |
| 2674 |
assert (arrtop > tgt.pbot && arrtop <= tgt.ptop); |
| 2675 |
tgt.pbot += 16; |
| 2676 |
tgt.ptop = arrtop; |
| 2677 |
} |
| 2678 |
else |
| 2679 |
{ |
| 2680 |
tgt.ptop = tgt.pbot + element_size; |
| 2681 |
} |
| 2682 |
tgt.pbase = cast(void**)tgt.pbot; |
| 2683 |
} |
| 2684 |
} |
| 2685 |
goto LaddRange; |
| 2686 |
} |
| 2687 |
} |
| 2688 |
else |
| 2689 |
{ |
| 2690 |
// Don't mark bits in B_FREE pages |
| 2691 |
assert(bin == Bins.B_FREE); |
| 2692 |
} |
| 2693 |
} |
| 2694 |
LnextPtr: |
| 2695 |
rng.pbot += (void*).sizeof; |
| 2696 |
if (rng.pbot < rng.ptop) |
| 2697 |
continue; |
| 2698 |
|
| 2699 |
LnextRange: |
| 2700 |
if (stackPos) |
| 2701 |
{ |
| 2702 |
// pop range from local stack and recurse |
| 2703 |
rng = stack[--stackPos]; |
| 2704 |
} |
| 2705 |
else |
| 2706 |
{ |
| 2707 |
static if (parallel) |
| 2708 |
{ |
| 2709 |
if (!toscan.popLocked(rng)) |
| 2710 |
break; // nothing more to do |
| 2711 |
} |
| 2712 |
else |
| 2713 |
{ |
| 2714 |
if (toscan.empty) |
| 2715 |
break; // nothing more to do |
| 2716 |
|
| 2717 |
// pop range from global stack and recurse |
| 2718 |
rng = toscan.pop(); |
| 2719 |
} |
| 2720 |
} |
| 2721 |
// printf(" pop [%p..%p] (%#zx)\n", p1, p2, cast(size_t)p2 - cast(size_t)p1); |
| 2722 |
goto LcontRange; |
| 2723 |
|
| 2724 |
LaddRange: |
| 2725 |
rng.pbot += (void*).sizeof; |
| 2726 |
if (rng.pbot < rng.ptop) |
| 2727 |
{ |
| 2728 |
if (stackPos < stack.length) |
| 2729 |
{ |
| 2730 |
stack[stackPos] = tgt; |
| 2731 |
stackPos++; |
| 2732 |
continue; |
| 2733 |
} |
| 2734 |
static if (parallel) |
| 2735 |
{ |
| 2736 |
toscan.stackLock.lock(); |
| 2737 |
scope(exit) toscan.stackLock.unlock(); |
| 2738 |
} |
| 2739 |
toscan.push(rng); |
| 2740 |
// reverse order for depth-first-order traversal |
| 2741 |
foreach_reverse (ref range; stack) |
| 2742 |
toscan.push(range); |
| 2743 |
stackPos = 0; |
| 2744 |
} |
| 2745 |
LendOfRange: |
| 2746 |
// continue with last found range |
| 2747 |
rng = tgt; |
| 2748 |
|
| 2749 |
LcontRange: |
| 2750 |
pcache = 0; |
| 2751 |
} |
| 2752 |
} |
| 2753 |
|
| 2754 |
void markConservative(bool shared_mem)(void *pbot, void *ptop) scope nothrow |
| 2755 |
{ |
| 2756 |
if (pbot < ptop) |
| 2757 |
mark!(false, false, shared_mem)(ScanRange!false(pbot, ptop)); |
| 2758 |
} |
| 2759 |
|
| 2760 |
void markPrecise(bool shared_mem)(void *pbot, void *ptop) scope nothrow |
| 2761 |
{ |
| 2762 |
if (pbot < ptop) |
| 2763 |
mark!(true, false, shared_mem)(ScanRange!true(pbot, ptop, null)); |
| 2764 |
} |
| 2765 |
|
| 2766 |
version (COLLECT_PARALLEL) |
| 2767 |
ToScanStack!(void*) toscanRoots; |
| 2768 |
|
| 2769 |
version (COLLECT_PARALLEL) |
| 2770 |
void collectRoots(void *pbot, void *ptop) scope nothrow |
| 2771 |
{ |
| 2772 |
const minAddr = pooltable.minAddr; |
| 2773 |
size_t memSize = pooltable.maxAddr - minAddr; |
| 2774 |
|
| 2775 |
for (auto p = cast(void**)pbot; cast(void*)p < ptop; p++) |
| 2776 |
{ |
| 2777 |
auto ptr = *p; |
| 2778 |
debug (VALGRIND) makeMemDefined((&ptr)[0 .. 1]); |
| 2779 |
if (cast(size_t)(ptr - minAddr) < memSize) |
| 2780 |
toscanRoots.push(ptr); |
| 2781 |
} |
| 2782 |
} |
| 2783 |
|
| 2784 |
// collection step 1: prepare freebits and mark bits |
| 2785 |
void prepare() nothrow |
| 2786 |
{ |
| 2787 |
debug(COLLECT_PRINTF) printf("preparing mark.\n"); |
| 2788 |
|
| 2789 |
foreach (Pool* pool; this.pooltable[]) |
| 2790 |
{ |
| 2791 |
if (pool.isLargeObject) |
| 2792 |
pool.mark.zero(); |
| 2793 |
else |
| 2794 |
pool.mark.copy(&pool.freebits); |
| 2795 |
} |
| 2796 |
} |
| 2797 |
|
| 2798 |
// collection step 2: mark roots and heap |
| 2799 |
void markAll(alias markFn)() nothrow |
| 2800 |
{ |
| 2801 |
debug(COLLECT_PRINTF) printf("\tscan stacks.\n"); |
| 2802 |
// Scan stacks registers, and TLS for each paused thread |
| 2803 |
thread_scanAll(&markFn); |
| 2804 |
|
| 2805 |
// Scan roots[] |
| 2806 |
debug(COLLECT_PRINTF) printf("\tscan roots[]\n"); |
| 2807 |
foreach (root; roots) |
| 2808 |
{ |
| 2809 |
markFn(cast(void*)&root.proot, cast(void*)(&root.proot + 1)); |
| 2810 |
} |
| 2811 |
|
| 2812 |
// Scan ranges[] |
| 2813 |
debug(COLLECT_PRINTF) printf("\tscan ranges[]\n"); |
| 2814 |
//log++; |
| 2815 |
foreach (range; ranges) |
| 2816 |
{ |
| 2817 |
debug(COLLECT_PRINTF) printf("\t\t%p .. %p\n", range.pbot, range.ptop); |
| 2818 |
markFn(range.pbot, range.ptop); |
| 2819 |
} |
| 2820 |
//log--; |
| 2821 |
} |
| 2822 |
|
| 2823 |
version (COLLECT_PARALLEL) |
| 2824 |
void collectAllRoots() nothrow |
| 2825 |
{ |
| 2826 |
debug(COLLECT_PRINTF) printf("\tcollect stacks.\n"); |
| 2827 |
// Scan stacks registers and TLS for each paused thread |
| 2828 |
thread_scanAll(&collectRoots); |
| 2829 |
|
| 2830 |
// Scan roots[] |
| 2831 |
debug(COLLECT_PRINTF) printf("\tcollect roots[]\n"); |
| 2832 |
foreach (root; roots) |
| 2833 |
{ |
| 2834 |
toscanRoots.push(root); |
| 2835 |
} |
| 2836 |
|
| 2837 |
// Scan ranges[] |
| 2838 |
debug(COLLECT_PRINTF) printf("\tcollect ranges[]\n"); |
| 2839 |
foreach (range; ranges) |
| 2840 |
{ |
| 2841 |
debug(COLLECT_PRINTF) printf("\t\t%p .. %p\n", range.pbot, range.ptop); |
| 2842 |
collectRoots(range.pbot, range.ptop); |
| 2843 |
} |
| 2844 |
} |
| 2845 |
|
| 2846 |
// collection step 3: finalize unreferenced objects, recover full pages with no live objects |
| 2847 |
size_t sweep() nothrow |
| 2848 |
{ |
| 2849 |
// Free up everything not marked |
| 2850 |
debug(COLLECT_PRINTF) printf("\tfree'ing\n"); |
| 2851 |
size_t freedLargePages; |
| 2852 |
size_t freedSmallPages; |
| 2853 |
size_t freed; |
| 2854 |
foreach (Pool* pool; this.pooltable[]) |
| 2855 |
{ |
| 2856 |
size_t pn; |
| 2857 |
|
| 2858 |
if (pool.isLargeObject) |
| 2859 |
{ |
| 2860 |
auto lpool = cast(LargeObjectPool*)pool; |
| 2861 |
size_t numFree = 0; |
| 2862 |
size_t npages; |
| 2863 |
for (pn = 0; pn < pool.npages; pn += npages) |
| 2864 |
{ |
| 2865 |
npages = pool.bPageOffsets[pn]; |
| 2866 |
Bins bin = cast(Bins)pool.pagetable[pn]; |
| 2867 |
if (bin == Bins.B_FREE) |
| 2868 |
{ |
| 2869 |
numFree += npages; |
| 2870 |
continue; |
| 2871 |
} |
| 2872 |
assert(bin == Bins.B_PAGE); |
| 2873 |
size_t biti = pn; |
| 2874 |
|
| 2875 |
if (!pool.mark.test(biti)) |
| 2876 |
{ |
| 2877 |
void *p = pool.baseAddr + pn * PAGESIZE; |
| 2878 |
void* q = sentinel_add(p); |
| 2879 |
sentinel_Invariant(q); |
| 2880 |
|
| 2881 |
if (pool.finals.nbits && pool.finals.clear(biti)) |
| 2882 |
{ |
| 2883 |
import core.internal.gc.blockmeta; |
| 2884 |
size_t size = npages * PAGESIZE - SENTINEL_EXTRA; |
| 2885 |
size = sentinel_size(q, size); |
| 2886 |
uint attr = pool.getBits(biti); |
| 2887 |
auto ti = __getBlockFinalizerInfo(q, size, attr); |
| 2888 |
__trimExtents(q, size, attr); |
| 2889 |
rt_finalizeFromGC(q, size, attr, ti); |
| 2890 |
} |
| 2891 |
|
| 2892 |
pool.clrBits(biti, ~BlkAttr.NONE ^ BlkAttr.FINALIZE); |
| 2893 |
|
| 2894 |
debug(COLLECT_PRINTF) printf("\tcollecting big %p\n", p); |
| 2895 |
leakDetector.log_free(q, sentinel_size(q, npages * PAGESIZE - SENTINEL_EXTRA)); |
| 2896 |
pool.pagetable[pn..pn+npages] = Bins.B_FREE; |
| 2897 |
if (pn < pool.searchStart) pool.searchStart = pn; |
| 2898 |
freedLargePages += npages; |
| 2899 |
pool.freepages += npages; |
| 2900 |
numFree += npages; |
| 2901 |
|
| 2902 |
invalidate(p[0 .. npages * PAGESIZE], 0xF3, false); |
| 2903 |
// Don't need to update searchStart here because |
| 2904 |
// pn is guaranteed to be greater than last time |
| 2905 |
// we updated it. |
| 2906 |
|
| 2907 |
pool.largestFree = pool.freepages; // invalidate |
| 2908 |
} |
| 2909 |
else |
| 2910 |
{ |
| 2911 |
if (numFree > 0) |
| 2912 |
{ |
| 2913 |
lpool.setFreePageOffsets(pn - numFree, numFree); |
| 2914 |
numFree = 0; |
| 2915 |
} |
| 2916 |
} |
| 2917 |
} |
| 2918 |
if (numFree > 0) |
| 2919 |
lpool.setFreePageOffsets(pn - numFree, numFree); |
| 2920 |
} |
| 2921 |
else |
| 2922 |
{ |
| 2923 |
// reinit chain of pages to rebuild free list |
| 2924 |
pool.recoverPageFirst[] = cast(uint)pool.npages; |
| 2925 |
|
| 2926 |
for (pn = 0; pn < pool.npages; pn++) |
| 2927 |
{ |
| 2928 |
Bins bin = cast(Bins)pool.pagetable[pn]; |
| 2929 |
|
| 2930 |
if (bin < Bins.B_PAGE) |
| 2931 |
{ |
| 2932 |
auto freebitsdata = pool.freebits.data + pn * PageBits.length; |
| 2933 |
auto markdata = pool.mark.data + pn * PageBits.length; |
| 2934 |
|
| 2935 |
// the entries to free are allocated objects (freebits == false) |
| 2936 |
// that are not marked (mark == false) |
| 2937 |
PageBits toFree; |
| 2938 |
static foreach (w; 0 .. PageBits.length) |
| 2939 |
toFree[w] = (~freebitsdata[w] & ~markdata[w]); |
| 2940 |
|
| 2941 |
// the page is unchanged if there is nothing to free |
| 2942 |
bool unchanged = true; |
| 2943 |
static foreach (w; 0 .. PageBits.length) |
| 2944 |
unchanged = unchanged && (toFree[w] == 0); |
| 2945 |
if (unchanged) |
| 2946 |
{ |
| 2947 |
bool hasDead = false; |
| 2948 |
static foreach (w; 0 .. PageBits.length) |
| 2949 |
hasDead = hasDead || (~freebitsdata[w] != baseOffsetBits[bin][w]); |
| 2950 |
if (hasDead) |
| 2951 |
{ |
| 2952 |
// add to recover chain |
| 2953 |
pool.binPageChain[pn] = pool.recoverPageFirst[bin]; |
| 2954 |
pool.recoverPageFirst[bin] = cast(uint)pn; |
| 2955 |
} |
| 2956 |
else |
| 2957 |
{ |
| 2958 |
pool.binPageChain[pn] = Pool.PageRecovered; |
| 2959 |
} |
| 2960 |
continue; |
| 2961 |
} |
| 2962 |
|
| 2963 |
// the page can be recovered if all of the allocated objects (freebits == false) |
| 2964 |
// are freed |
| 2965 |
bool recoverPage = true; |
| 2966 |
static foreach (w; 0 .. PageBits.length) |
| 2967 |
recoverPage = recoverPage && (~freebitsdata[w] == toFree[w]); |
| 2968 |
|
| 2969 |
// We need to loop through each object if any have a finalizer, |
| 2970 |
// or, if any of the debug hooks are enabled. |
| 2971 |
bool doLoop = false; |
| 2972 |
debug (SENTINEL) |
| 2973 |
doLoop = true; |
| 2974 |
else version (assert) |
| 2975 |
doLoop = true; |
| 2976 |
else debug (COLLECT_PRINTF) // need output for each object |
| 2977 |
doLoop = true; |
| 2978 |
else debug (LOGGING) |
| 2979 |
doLoop = true; |
| 2980 |
else debug (MEMSTOMP) |
| 2981 |
doLoop = true; |
| 2982 |
else if (pool.finals.data) |
| 2983 |
{ |
| 2984 |
// finalizers must be called on objects that are about to be freed |
| 2985 |
auto finalsdata = pool.finals.data + pn * PageBits.length; |
| 2986 |
static foreach (w; 0 .. PageBits.length) |
| 2987 |
doLoop = doLoop || (toFree[w] & finalsdata[w]) != 0; |
| 2988 |
} |
| 2989 |
|
| 2990 |
if (doLoop) |
| 2991 |
{ |
| 2992 |
immutable size = binsize[bin]; |
| 2993 |
void *p = pool.baseAddr + pn * PAGESIZE; |
| 2994 |
immutable base = pn * (PAGESIZE/16); |
| 2995 |
immutable bitstride = size / 16; |
| 2996 |
|
| 2997 |
// ensure that there are at least <size> bytes for every address |
| 2998 |
// below ptop even if unaligned |
| 2999 |
void *ptop = p + PAGESIZE - size + 1; |
| 3000 |
for (size_t i; p < ptop; p += size, i += bitstride) |
| 3001 |
{ |
| 3002 |
immutable biti = base + i; |
| 3003 |
|
| 3004 |
if (pool.mark.test(biti)) |
| 3005 |
continue; |
| 3006 |
|
| 3007 |
void* q = sentinel_add(p); |
| 3008 |
sentinel_Invariant(q); |
| 3009 |
|
| 3010 |
if (pool.finals.nbits && pool.finals.test(biti)) |
| 3011 |
{ |
| 3012 |
import core.internal.gc.blockmeta; |
| 3013 |
size_t ssize = sentinel_size(q, size); |
| 3014 |
uint attr = pool.getBits(biti); |
| 3015 |
auto ti = __getBlockFinalizerInfo(q, ssize, attr); |
| 3016 |
__trimExtents(q, ssize, attr); |
| 3017 |
rt_finalizeFromGC(q, ssize, attr, ti); |
| 3018 |
} |
| 3019 |
|
| 3020 |
assert(core.bitop.bt(toFree.ptr, i)); |
| 3021 |
|
| 3022 |
debug(COLLECT_PRINTF) printf("\tcollecting %p\n", p); |
| 3023 |
leakDetector.log_free(q, sentinel_size(q, size)); |
| 3024 |
|
| 3025 |
invalidate(p[0 .. size], 0xF3, false); |
| 3026 |
} |
| 3027 |
} |
| 3028 |
|
| 3029 |
if (recoverPage) |
| 3030 |
{ |
| 3031 |
pool.freeAllPageBits(pn); |
| 3032 |
|
| 3033 |
pool.pagetable[pn] = Bins.B_FREE; |
| 3034 |
// add to free chain |
| 3035 |
pool.binPageChain[pn] = cast(uint) pool.searchStart; |
| 3036 |
pool.searchStart = pn; |
| 3037 |
pool.freepages++; |
| 3038 |
freedSmallPages++; |
| 3039 |
} |
| 3040 |
else |
| 3041 |
{ |
| 3042 |
pool.freePageBits(pn, toFree); |
| 3043 |
|
| 3044 |
// add to recover chain |
| 3045 |
pool.binPageChain[pn] = pool.recoverPageFirst[bin]; |
| 3046 |
pool.recoverPageFirst[bin] = cast(uint)pn; |
| 3047 |
} |
| 3048 |
} |
| 3049 |
} |
| 3050 |
} |
| 3051 |
} |
| 3052 |
|
| 3053 |
assert(freedLargePages <= usedLargePages); |
| 3054 |
usedLargePages -= freedLargePages; |
| 3055 |
debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", |
| 3056 |
freed, freedLargePages, this.pooltable.length); |
| 3057 |
|
| 3058 |
assert(freedSmallPages <= usedSmallPages); |
| 3059 |
usedSmallPages -= freedSmallPages; |
| 3060 |
debug(COLLECT_PRINTF) printf("\trecovered small pages = %d\n", freedSmallPages); |
| 3061 |
|
| 3062 |
return freedLargePages + freedSmallPages; |
| 3063 |
} |
| 3064 |
|
| 3065 |
bool recoverPage(SmallObjectPool* pool, size_t pn, Bins bin) nothrow |
| 3066 |
{ |
| 3067 |
size_t size = binsize[bin]; |
| 3068 |
size_t bitbase = pn * (PAGESIZE / 16); |
| 3069 |
|
| 3070 |
auto freebitsdata = pool.freebits.data + pn * PageBits.length; |
| 3071 |
|
| 3072 |
// the page had dead objects when collecting, these cannot have been resurrected |
| 3073 |
bool hasDead = false; |
| 3074 |
static foreach (w; 0 .. PageBits.length) |
| 3075 |
hasDead = hasDead || (freebitsdata[w] != 0); |
| 3076 |
assert(hasDead); |
| 3077 |
|
| 3078 |
// prepend to buckets, but with forward addresses inside the page |
| 3079 |
assert(bucket[bin] is null); |
| 3080 |
List** bucketTail = &bucket[bin]; |
| 3081 |
|
| 3082 |
void* p = pool.baseAddr + pn * PAGESIZE; |
| 3083 |
const top = PAGESIZE - size + 1; // ensure <size> bytes available even if unaligned |
| 3084 |
for (size_t u = 0; u < top; u += size) |
| 3085 |
{ |
| 3086 |
if (!core.bitop.bt(freebitsdata, u / 16)) |
| 3087 |
continue; |
| 3088 |
auto elem = cast(List *)(p + u); |
| 3089 |
undefinedWrite(elem.pool, &pool.base); |
| 3090 |
undefinedWrite(*bucketTail, elem); |
| 3091 |
bucketTail = &elem.next; |
| 3092 |
} |
| 3093 |
undefinedWrite(*bucketTail, null); |
| 3094 |
assert(bucket[bin] !is null); |
| 3095 |
return true; |
| 3096 |
} |
| 3097 |
|
| 3098 |
bool recoverNextPage(Bins bin) nothrow |
| 3099 |
{ |
| 3100 |
SmallObjectPool* pool = recoverPool[bin]; |
| 3101 |
while (pool) |
| 3102 |
{ |
| 3103 |
auto pn = pool.recoverPageFirst[bin]; |
| 3104 |
while (pn < pool.npages) |
| 3105 |
{ |
| 3106 |
auto next = pool.binPageChain[pn]; |
| 3107 |
pool.binPageChain[pn] = Pool.PageRecovered; |
| 3108 |
pool.recoverPageFirst[bin] = next; |
| 3109 |
if (recoverPage(pool, pn, bin)) |
| 3110 |
return true; |
| 3111 |
pn = next; |
| 3112 |
} |
| 3113 |
pool = setNextRecoverPool(bin, pool.ptIndex + 1); |
| 3114 |
} |
| 3115 |
return false; |
| 3116 |
} |
| 3117 |
|
| 3118 |
private SmallObjectPool* setNextRecoverPool(Bins bin, size_t poolIndex) nothrow |
| 3119 |
{ |
| 3120 |
Pool* pool; |
| 3121 |
while (poolIndex < this.pooltable.length && |
| 3122 |
((pool = this.pooltable[poolIndex]).isLargeObject || |
| 3123 |
pool.recoverPageFirst[bin] >= pool.npages)) |
| 3124 |
poolIndex++; |
| 3125 |
|
| 3126 |
return recoverPool[bin] = poolIndex < this.pooltable.length ? cast(SmallObjectPool*)pool : null; |
| 3127 |
} |
| 3128 |
|
| 3129 |
version (COLLECT_FORK) |
| 3130 |
void disableFork() nothrow |
| 3131 |
{ |
| 3132 |
markProcPid = 0; |
| 3133 |
shouldFork = false; |
| 3134 |
} |
| 3135 |
|
| 3136 |
version (COLLECT_FORK) |
| 3137 |
ChildStatus collectFork(bool block) nothrow |
| 3138 |
{ |
| 3139 |
typeof(return) rc = wait_pid(markProcPid, block); |
| 3140 |
final switch (rc) |
| 3141 |
{ |
| 3142 |
case ChildStatus.done: |
| 3143 |
debug(COLLECT_PRINTF) printf("\t\tmark proc DONE (block=%d)\n", |
| 3144 |
cast(int) block); |
| 3145 |
markProcPid = 0; |
| 3146 |
// process GC marks then sweep |
| 3147 |
thread_suspendAll(); |
| 3148 |
thread_processTLSGCData(&clearBlkCacheData); |
| 3149 |
thread_resumeAll(); |
| 3150 |
break; |
| 3151 |
case ChildStatus.running: |
| 3152 |
debug(COLLECT_PRINTF) printf("\t\tmark proc RUNNING\n"); |
| 3153 |
if (!block) |
| 3154 |
break; |
| 3155 |
// Something went wrong, if block is true, wait() should never |
| 3156 |
// return RUNNING. |
| 3157 |
goto case ChildStatus.error; |
| 3158 |
case ChildStatus.error: |
| 3159 |
debug(COLLECT_PRINTF) printf("\t\tmark proc ERROR\n"); |
| 3160 |
// Try to keep going without forking |
| 3161 |
// and do the marking in this thread |
| 3162 |
break; |
| 3163 |
} |
| 3164 |
return rc; |
| 3165 |
} |
| 3166 |
|
| 3167 |
version (COLLECT_FORK) |
| 3168 |
ChildStatus markFork(bool block, bool doParallel) nothrow |
| 3169 |
{ |
| 3170 |
// Forking is enabled, so we fork() and start a new concurrent mark phase |
| 3171 |
// in the child. If the collection should not block, the parent process |
| 3172 |
// tells the caller no memory could be recycled immediately (if this collection |
| 3173 |
// was triggered by an allocation, the caller should allocate more memory |
| 3174 |
// to fulfill the request). |
| 3175 |
// If the collection should block, the parent will wait for the mark phase |
| 3176 |
// to finish before returning control to the mutator, |
| 3177 |
// but other threads are restarted and may run in parallel with the mark phase |
| 3178 |
// (unless they allocate or use the GC themselves, in which case |
| 3179 |
// the global GC lock will stop them). |
| 3180 |
// fork now and sweep later |
| 3181 |
int child_mark() scope |
| 3182 |
{ |
| 3183 |
if (doParallel) |
| 3184 |
markParallel(); |
| 3185 |
else if (ConservativeGC.isPrecise) |
| 3186 |
markAll!(markPrecise!true)(); |
| 3187 |
else |
| 3188 |
markAll!(markConservative!true)(); |
| 3189 |
return 0; |
| 3190 |
} |
| 3191 |
|
| 3192 |
import core.stdc.stdlib : _Exit; |
| 3193 |
debug (PRINTF_TO_FILE) |
| 3194 |
{ |
| 3195 |
fflush(null); // avoid duplicated FILE* output |
| 3196 |
} |
| 3197 |
version (OSX) |
| 3198 |
{ |
| 3199 |
auto pid = __fork(); // avoids calling handlers (from libc source code) |
| 3200 |
} |
| 3201 |
else version (linux) |
| 3202 |
{ |
| 3203 |
// clone() fits better as we don't want to do anything but scanning in the child process. |
| 3204 |
// no fork-handlers are called, so we can avoid deadlocks due to malloc locks. Probably related: |
| 3205 |
// https://sourceware.org/bugzilla/show_bug.cgi?id=4737 |
| 3206 |
import core.sys.linux.sched : clone; |
| 3207 |
import core.sys.posix.signal : SIGCHLD; |
| 3208 |
const flags = SIGCHLD; // exit signal |
| 3209 |
scope int delegate() scope dg = &child_mark; |
| 3210 |
extern(C) static int wrap_delegate(void* arg) |
| 3211 |
{ |
| 3212 |
auto dg = cast(int delegate() scope*)arg; |
| 3213 |
return (*dg)(); |
| 3214 |
} |
| 3215 |
ubyte[256] stackbuf; // enough stack space for clone() to place some info for the child without stomping the parent stack |
| 3216 |
auto stack = stackbuf.ptr + (isStackGrowingDown ? stackbuf.length : 0); |
| 3217 |
auto pid = clone(&wrap_delegate, stack, flags, &dg); |
| 3218 |
} |
| 3219 |
else |
| 3220 |
{ |
| 3221 |
fork_needs_lock = false; |
| 3222 |
auto pid = fork(); |
| 3223 |
fork_needs_lock = true; |
| 3224 |
} |
| 3225 |
switch (pid) |
| 3226 |
{ |
| 3227 |
case -1: // fork() failed, retry without forking |
| 3228 |
return ChildStatus.error; |
| 3229 |
case 0: // child process (not run with clone) |
| 3230 |
child_mark(); |
| 3231 |
_Exit(0); |
| 3232 |
default: // the parent |
| 3233 |
thread_resumeAll(); |
| 3234 |
if (!block) |
| 3235 |
{ |
| 3236 |
markProcPid = pid; |
| 3237 |
return ChildStatus.running; |
| 3238 |
} |
| 3239 |
ChildStatus r = wait_pid(pid); // block until marking is done |
| 3240 |
if (r == ChildStatus.error) |
| 3241 |
{ |
| 3242 |
thread_suspendAll(); |
| 3243 |
// there was an error |
| 3244 |
// do the marking in this thread |
| 3245 |
disableFork(); |
| 3246 |
if (doParallel) |
| 3247 |
markParallel(); |
| 3248 |
else if (ConservativeGC.isPrecise) |
| 3249 |
markAll!(markPrecise!false)(); |
| 3250 |
else |
| 3251 |
markAll!(markConservative!false)(); |
| 3252 |
} else { |
| 3253 |
assert(r == ChildStatus.done); |
| 3254 |
assert(r != ChildStatus.running); |
| 3255 |
} |
| 3256 |
} |
| 3257 |
return ChildStatus.done; // waited for the child |
| 3258 |
} |
| 3259 |
|
| 3260 |
/** |
| 3261 |
* Return number of full pages free'd. |
| 3262 |
* The collection is done concurrently only if block and isFinal are false. |
| 3263 |
*/ |
| 3264 |
size_t fullcollect(bool block = false, bool isFinal = false) nothrow |
| 3265 |
{ |
| 3266 |
// It is possible that `fullcollect` will be called from a thread which |
| 3267 |
// is not yet registered in runtime (because allocating `new Thread` is |
| 3268 |
// part of `thread_attachThis` implementation). In that case it is |
| 3269 |
// better not to try actually collecting anything |
| 3270 |
|
| 3271 |
if (Thread.getThis() is null) |
| 3272 |
return 0; |
| 3273 |
|
| 3274 |
MonoTime start, stop, begin; |
| 3275 |
begin = start = currTime; |
| 3276 |
|
| 3277 |
debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n"); |
| 3278 |
version (COLLECT_PARALLEL) |
| 3279 |
{ |
| 3280 |
bool doParallel = config.parallel > 0 && !config.fork; |
| 3281 |
if (doParallel && !scanThreadData) |
| 3282 |
{ |
| 3283 |
if (isFinal) // avoid starting threads for parallel marking |
| 3284 |
doParallel = false; |
| 3285 |
else |
| 3286 |
startScanThreads(); |
| 3287 |
} |
| 3288 |
} |
| 3289 |
else |
| 3290 |
enum doParallel = false; |
| 3291 |
|
| 3292 |
//printf("\tpool address range = %p .. %p\n", minAddr, maxAddr); |
| 3293 |
|
| 3294 |
version (COLLECT_FORK) |
| 3295 |
alias doFork = shouldFork; |
| 3296 |
else |
| 3297 |
enum doFork = false; |
| 3298 |
|
| 3299 |
if (doFork && collectInProgress) |
| 3300 |
{ |
| 3301 |
version (COLLECT_FORK) |
| 3302 |
{ |
| 3303 |
// If there is a mark process running, check if it already finished. |
| 3304 |
// If that is the case, we move to the sweep phase. |
| 3305 |
// If it's still running, either we block until the mark phase is |
| 3306 |
// done (and then sweep to finish the collection), or in case of error |
| 3307 |
// we redo the mark phase without forking. |
| 3308 |
ChildStatus rc = collectFork(block); |
| 3309 |
final switch (rc) |
| 3310 |
{ |
| 3311 |
case ChildStatus.done: |
| 3312 |
break; |
| 3313 |
case ChildStatus.running: |
| 3314 |
return 0; |
| 3315 |
case ChildStatus.error: |
| 3316 |
disableFork(); |
| 3317 |
goto Lmark; |
| 3318 |
} |
| 3319 |
} |
| 3320 |
} |
| 3321 |
else |
| 3322 |
{ |
| 3323 |
Lmark: |
| 3324 |
// lock roots and ranges around suspending threads b/c they're not reentrant safe |
| 3325 |
rangesLock.lock(); |
| 3326 |
rootsLock.lock(); |
| 3327 |
debug(INVARIANT) inCollection = true; |
| 3328 |
scope (exit) |
| 3329 |
{ |
| 3330 |
debug(INVARIANT) inCollection = false; |
| 3331 |
rangesLock.unlock(); |
| 3332 |
rootsLock.unlock(); |
| 3333 |
} |
| 3334 |
thread_suspendAll(); |
| 3335 |
|
| 3336 |
prepare(); |
| 3337 |
|
| 3338 |
stop = currTime; |
| 3339 |
prepTime += (stop - start); |
| 3340 |
start = stop; |
| 3341 |
|
| 3342 |
if (doFork && !isFinal && !block) // don't start a new fork during termination |
| 3343 |
{ |
| 3344 |
version (COLLECT_FORK) |
| 3345 |
{ |
| 3346 |
auto forkResult = markFork(block, doParallel); |
| 3347 |
final switch (forkResult) |
| 3348 |
{ |
| 3349 |
case ChildStatus.error: |
| 3350 |
// fork() failed, retry without forking |
| 3351 |
disableFork(); |
| 3352 |
goto Lmark; |
| 3353 |
case ChildStatus.running: |
| 3354 |
// update profiling informations |
| 3355 |
stop = currTime; |
| 3356 |
markTime += (stop - start); |
| 3357 |
Duration pause = stop - begin; |
| 3358 |
if (pause > maxPauseTime) |
| 3359 |
maxPauseTime = pause; |
| 3360 |
pauseTime += pause; |
| 3361 |
return 0; |
| 3362 |
case ChildStatus.done: |
| 3363 |
break; |
| 3364 |
} |
| 3365 |
// if we get here, forking failed and a standard STW collection got issued |
| 3366 |
// threads were suspended again, restart them |
| 3367 |
thread_suspendAll(); |
| 3368 |
} |
| 3369 |
} |
| 3370 |
else if (doParallel) |
| 3371 |
{ |
| 3372 |
version (COLLECT_PARALLEL) |
| 3373 |
markParallel(); |
| 3374 |
} |
| 3375 |
else |
| 3376 |
{ |
| 3377 |
if (ConservativeGC.isPrecise) |
| 3378 |
markAll!(markPrecise!false)(); |
| 3379 |
else |
| 3380 |
markAll!(markConservative!false)(); |
| 3381 |
} |
| 3382 |
|
| 3383 |
thread_processTLSGCData(&clearBlkCacheData); |
| 3384 |
thread_resumeAll(); |
| 3385 |
isFinal = false; |
| 3386 |
} |
| 3387 |
|
| 3388 |
// If we get here with the forking GC, the child process has finished the marking phase |
| 3389 |
// or block == true and we are using standard stop the world collection. |
| 3390 |
// It is time to sweep |
| 3391 |
|
| 3392 |
stop = currTime; |
| 3393 |
markTime += (stop - start); |
| 3394 |
Duration pause = stop - begin; |
| 3395 |
if (pause > maxPauseTime) |
| 3396 |
maxPauseTime = pause; |
| 3397 |
pauseTime += pause; |
| 3398 |
start = stop; |
| 3399 |
|
| 3400 |
ConservativeGC._inFinalizer = true; |
| 3401 |
size_t freedPages = void; |
| 3402 |
{ |
| 3403 |
scope (failure) ConservativeGC._inFinalizer = false; |
| 3404 |
freedPages = sweep(); |
| 3405 |
ConservativeGC._inFinalizer = false; |
| 3406 |
} |
| 3407 |
|
| 3408 |
// minimize() should be called only after a call to fullcollect |
| 3409 |
// terminates with a sweep |
| 3410 |
if (minimizeAfterNextCollection || lowMem) |
| 3411 |
{ |
| 3412 |
minimizeAfterNextCollection = false; |
| 3413 |
minimize(); |
| 3414 |
} |
| 3415 |
|
| 3416 |
// init bucket lists |
| 3417 |
bucket[] = null; |
| 3418 |
foreach (Bins bin; Bins.B_16 .. Bins.B_NUMSMALL) |
| 3419 |
setNextRecoverPool(bin, 0); |
| 3420 |
|
| 3421 |
stop = currTime; |
| 3422 |
sweepTime += (stop - start); |
| 3423 |
|
| 3424 |
Duration collectionTime = stop - begin; |
| 3425 |
if (collectionTime > maxCollectionTime) |
| 3426 |
maxCollectionTime = collectionTime; |
| 3427 |
|
| 3428 |
++numCollections; |
| 3429 |
|
| 3430 |
updateCollectThresholds(); |
| 3431 |
if (doFork && isFinal) |
| 3432 |
return fullcollect(true, false); |
| 3433 |
return freedPages; |
| 3434 |
} |
| 3435 |
|
| 3436 |
/** |
| 3437 |
* Clear the block cache data if it exists, given the data which is the |
| 3438 |
* block info cache. |
| 3439 |
* |
| 3440 |
* Warning! This should only be called while the world is stopped inside |
| 3441 |
* the fullcollect function after all live objects have been marked, but |
| 3442 |
* before sweeping. |
| 3443 |
*/ |
| 3444 |
void *clearBlkCacheData(void* data) scope nothrow |
| 3445 |
{ |
| 3446 |
processGCMarks(data, &isMarked); |
| 3447 |
return data; |
| 3448 |
} |
| 3449 |
|
| 3450 |
/** |
| 3451 |
* Returns true if the addr lies within a marked block. |
| 3452 |
* |
| 3453 |
* Warning! This should only be called while the world is stopped inside |
| 3454 |
* the fullcollect function after all live objects have been marked, but before sweeping. |
| 3455 |
*/ |
| 3456 |
IsMarked isMarked(void *addr) scope nothrow |
| 3457 |
{ |
| 3458 |
// first, we find the Pool this block is in, then check to see if the |
| 3459 |
// mark bit is clear. |
| 3460 |
if (auto pool = findPool(addr)) |
| 3461 |
{ |
| 3462 |
auto offset = cast(size_t)(addr - pool.baseAddr); |
| 3463 |
auto pn = offset / PAGESIZE; |
| 3464 |
auto bins = cast(Bins)pool.pagetable[pn]; |
| 3465 |
size_t biti = void; |
| 3466 |
if (bins < Bins.B_PAGE) |
| 3467 |
{ |
| 3468 |
biti = baseOffset(offset, bins) >> pool.ShiftBy.Small; |
| 3469 |
// doesn't need to check freebits because no pointer must exist |
| 3470 |
// to a block that was free before starting the collection |
| 3471 |
} |
| 3472 |
else if (bins == Bins.B_PAGE) |
| 3473 |
{ |
| 3474 |
biti = pn * (PAGESIZE >> pool.ShiftBy.Large); |
| 3475 |
} |
| 3476 |
else if (bins == Bins.B_PAGEPLUS) |
| 3477 |
{ |
| 3478 |
pn -= pool.bPageOffsets[pn]; |
| 3479 |
biti = pn * (PAGESIZE >> pool.ShiftBy.Large); |
| 3480 |
} |
| 3481 |
else // bins == Bins.B_FREE |
| 3482 |
{ |
| 3483 |
assert(bins == Bins.B_FREE); |
| 3484 |
return IsMarked.no; |
| 3485 |
} |
| 3486 |
return pool.mark.test(biti) ? IsMarked.yes : IsMarked.no; |
| 3487 |
} |
| 3488 |
return IsMarked.unknown; |
| 3489 |
} |
| 3490 |
|
| 3491 |
version (Posix) |
| 3492 |
{ |
| 3493 |
// A fork might happen while GC code is running in a different thread. |
| 3494 |
// Because that would leave the GC in an inconsistent state, |
| 3495 |
// make sure no GC code is running by acquiring the lock here, |
| 3496 |
// before a fork. |
| 3497 |
// This must not happen if fork is called from the GC with the lock already held |
| 3498 |
|
| 3499 |
__gshared bool fork_needs_lock = true; // racing condition with cocurrent calls of fork? |
| 3500 |
|
| 3501 |
|
| 3502 |
extern(C) static void _d_gcx_atfork_prepare() |
| 3503 |
{ |
| 3504 |
if (instance && fork_needs_lock) |
| 3505 |
ConservativeGC.lockNR(); |
| 3506 |
} |
| 3507 |
|
| 3508 |
extern(C) static void _d_gcx_atfork_parent() |
| 3509 |
{ |
| 3510 |
if (instance && fork_needs_lock) |
| 3511 |
ConservativeGC.gcLock.unlock(); |
| 3512 |
} |
| 3513 |
|
| 3514 |
extern(C) static void _d_gcx_atfork_child() |
| 3515 |
{ |
| 3516 |
if (instance && fork_needs_lock) |
| 3517 |
{ |
| 3518 |
ConservativeGC.gcLock.unlock(); |
| 3519 |
|
| 3520 |
// make sure the threads and event handles are reinitialized in a fork |
| 3521 |
version (COLLECT_PARALLEL) |
| 3522 |
{ |
| 3523 |
if (Gcx.instance.scanThreadData) |
| 3524 |
{ |
| 3525 |
cstdlib.free(Gcx.instance.scanThreadData); |
| 3526 |
Gcx.instance.numScanThreads = 0; |
| 3527 |
Gcx.instance.scanThreadData = null; |
| 3528 |
Gcx.instance.busyThreads = 0; |
| 3529 |
|
| 3530 |
memset(&Gcx.instance.evStart, 0, Gcx.instance.evStart.sizeof); |
| 3531 |
memset(&Gcx.instance.evDone, 0, Gcx.instance.evDone.sizeof); |
| 3532 |
} |
| 3533 |
} |
| 3534 |
} |
| 3535 |
} |
| 3536 |
} |
| 3537 |
|
| 3538 |
/* ============================ Parallel scanning =============================== */ |
| 3539 |
version (COLLECT_PARALLEL): |
| 3540 |
|
| 3541 |
import core.atomic; |
| 3542 |
import core.cpuid; |
| 3543 |
import core.sync.event; |
| 3544 |
|
| 3545 |
private: // disable invariants for background threads |
| 3546 |
|
| 3547 |
static struct ScanThreadData |
| 3548 |
{ |
| 3549 |
ThreadID tid; |
| 3550 |
} |
| 3551 |
uint numScanThreads; |
| 3552 |
ScanThreadData* scanThreadData; |
| 3553 |
|
| 3554 |
Event evStart; |
| 3555 |
Event evDone; |
| 3556 |
|
| 3557 |
shared uint busyThreads; |
| 3558 |
shared uint stoppedThreads; |
| 3559 |
bool stopGC; |
| 3560 |
|
| 3561 |
void markParallel() nothrow |
| 3562 |
{ |
| 3563 |
toscanRoots.clear(); |
| 3564 |
collectAllRoots(); |
| 3565 |
if (toscanRoots.empty) |
| 3566 |
return; |
| 3567 |
|
| 3568 |
void** pbot = toscanRoots._p; |
| 3569 |
void** ptop = toscanRoots._p + toscanRoots._length; |
| 3570 |
|
| 3571 |
debug(PARALLEL_PRINTF) printf("markParallel\n"); |
| 3572 |
|
| 3573 |
size_t pointersPerThread = toscanRoots._length / (numScanThreads + 1); |
| 3574 |
if (pointersPerThread > 0) |
| 3575 |
{ |
| 3576 |
void pushRanges(bool precise)() |
| 3577 |
{ |
| 3578 |
alias toscan = scanStack!precise; |
| 3579 |
toscan.stackLock.lock(); |
| 3580 |
|
| 3581 |
for (int idx = 0; idx < numScanThreads; idx++) |
| 3582 |
{ |
| 3583 |
toscan.push(ScanRange!precise(pbot, pbot + pointersPerThread)); |
| 3584 |
pbot += pointersPerThread; |
| 3585 |
} |
| 3586 |
toscan.stackLock.unlock(); |
| 3587 |
} |
| 3588 |
if (ConservativeGC.isPrecise) |
| 3589 |
pushRanges!true(); |
| 3590 |
else |
| 3591 |
pushRanges!false(); |
| 3592 |
} |
| 3593 |
assert(pbot < ptop); |
| 3594 |
|
| 3595 |
busyThreads.atomicOp!"+="(1); // main thread is busy |
| 3596 |
|
| 3597 |
evStart.setIfInitialized(); |
| 3598 |
|
| 3599 |
debug(PARALLEL_PRINTF) printf("mark %lld roots\n", cast(ulong)(ptop - pbot)); |
| 3600 |
|
| 3601 |
if (ConservativeGC.isPrecise) |
| 3602 |
mark!(true, true, true)(ScanRange!true(pbot, ptop, null)); |
| 3603 |
else |
| 3604 |
mark!(false, true, true)(ScanRange!false(pbot, ptop)); |
| 3605 |
|
| 3606 |
busyThreads.atomicOp!"-="(1); |
| 3607 |
|
| 3608 |
debug(PARALLEL_PRINTF) printf("waitForScanDone\n"); |
| 3609 |
pullFromScanStack(); |
| 3610 |
debug(PARALLEL_PRINTF) printf("waitForScanDone done\n"); |
| 3611 |
} |
| 3612 |
|
| 3613 |
int maxParallelThreads() nothrow |
| 3614 |
{ |
| 3615 |
auto threads = threadsPerCPU(); |
| 3616 |
|
| 3617 |
if (threads == 0) |
| 3618 |
{ |
| 3619 |
// If the GC is called by module ctors no explicit |
| 3620 |
// import dependency on the GC is generated. So the |
| 3621 |
// GC module is not correctly inserted into the module |
| 3622 |
// initialization chain. As it relies on core.cpuid being |
| 3623 |
// initialized, force this here. |
| 3624 |
try |
| 3625 |
{ |
| 3626 |
foreach (m; ModuleInfo) |
| 3627 |
if (m.name == "core.cpuid") |
| 3628 |
if (auto ctor = m.ctor()) |
| 3629 |
{ |
| 3630 |
ctor(); |
| 3631 |
threads = threadsPerCPU(); |
| 3632 |
break; |
| 3633 |
} |
| 3634 |
} |
| 3635 |
catch (Exception) |
| 3636 |
{ |
| 3637 |
assert(false, "unexpected exception iterating ModuleInfo"); |
| 3638 |
} |
| 3639 |
} |
| 3640 |
return threads; |
| 3641 |
} |
| 3642 |
|
| 3643 |
|
| 3644 |
void startScanThreads() nothrow |
| 3645 |
{ |
| 3646 |
auto threads = maxParallelThreads(); |
| 3647 |
debug(PARALLEL_PRINTF) printf("startScanThreads: %d threads per CPU\n", threads); |
| 3648 |
if (threads <= 1) |
| 3649 |
return; // either core.cpuid not initialized or single core |
| 3650 |
|
| 3651 |
numScanThreads = threads >= config.parallel ? config.parallel : threads - 1; |
| 3652 |
|
| 3653 |
scanThreadData = cast(ScanThreadData*) cstdlib.calloc(numScanThreads, ScanThreadData.sizeof); |
| 3654 |
if (!scanThreadData) |
| 3655 |
onOutOfMemoryError(); |
| 3656 |
|
| 3657 |
evStart.initialize(false, false); |
| 3658 |
evDone.initialize(false, false); |
| 3659 |
|
| 3660 |
version (Posix) |
| 3661 |
{ |
| 3662 |
import core.sys.posix.signal : pthread_sigmask, SIG_BLOCK, SIG_SETMASK, sigfillset, sigset_t; |
| 3663 |
// block all signals, scanBackground inherits this mask. |
| 3664 |
// see https://issues.dlang.org/show_bug.cgi?id=20256 |
| 3665 |
sigset_t new_mask, old_mask; |
| 3666 |
sigfillset(&new_mask); |
| 3667 |
auto sigmask_rc = pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); |
| 3668 |
assert(sigmask_rc == 0, "failed to set up GC scan thread sigmask"); |
| 3669 |
} |
| 3670 |
|
| 3671 |
for (int idx = 0; idx < numScanThreads; idx++) |
| 3672 |
scanThreadData[idx].tid = createLowLevelThread(&scanBackground, 0x4000, &stopScanThreads); |
| 3673 |
|
| 3674 |
version (Posix) |
| 3675 |
{ |
| 3676 |
sigmask_rc = pthread_sigmask(SIG_SETMASK, &old_mask, null); |
| 3677 |
assert(sigmask_rc == 0, "failed to set up GC scan thread sigmask"); |
| 3678 |
} |
| 3679 |
} |
| 3680 |
|
| 3681 |
void stopScanThreads() nothrow |
| 3682 |
{ |
| 3683 |
if (!numScanThreads) |
| 3684 |
return; |
| 3685 |
|
| 3686 |
debug(PARALLEL_PRINTF) printf("stopScanThreads\n"); |
| 3687 |
int startedThreads = 0; |
| 3688 |
for (int idx = 0; idx < numScanThreads; idx++) |
| 3689 |
if (scanThreadData[idx].tid != scanThreadData[idx].tid.init) |
| 3690 |
startedThreads++; |
| 3691 |
|
| 3692 |
version (Windows) |
| 3693 |
alias allThreadsDead = thread_DLLProcessDetaching; |
| 3694 |
else |
| 3695 |
enum allThreadsDead = false; |
| 3696 |
stopGC = true; |
| 3697 |
while (atomicLoad(stoppedThreads) < startedThreads && !allThreadsDead) |
| 3698 |
{ |
| 3699 |
evStart.setIfInitialized(); |
| 3700 |
evDone.wait(dur!"msecs"(1)); |
| 3701 |
} |
| 3702 |
|
| 3703 |
for (int idx = 0; idx < numScanThreads; idx++) |
| 3704 |
{ |
| 3705 |
if (scanThreadData[idx].tid != scanThreadData[idx].tid.init) |
| 3706 |
{ |
| 3707 |
joinLowLevelThread(scanThreadData[idx].tid); |
| 3708 |
scanThreadData[idx].tid = scanThreadData[idx].tid.init; |
| 3709 |
} |
| 3710 |
} |
| 3711 |
|
| 3712 |
evDone.terminate(); |
| 3713 |
evStart.terminate(); |
| 3714 |
|
| 3715 |
cstdlib.free(scanThreadData); |
| 3716 |
// scanThreadData = null; // keep non-null to not start again after shutdown |
| 3717 |
numScanThreads = 0; |
| 3718 |
|
| 3719 |
debug(PARALLEL_PRINTF) printf("stopScanThreads done\n"); |
| 3720 |
} |
| 3721 |
|
| 3722 |
void scanBackground() nothrow |
| 3723 |
{ |
| 3724 |
while (!stopGC) |
| 3725 |
{ |
| 3726 |
evStart.wait(); |
| 3727 |
pullFromScanStack(); |
| 3728 |
evDone.setIfInitialized(); |
| 3729 |
} |
| 3730 |
stoppedThreads.atomicOp!"+="(1); |
| 3731 |
} |
| 3732 |
|
| 3733 |
void pullFromScanStack() nothrow |
| 3734 |
{ |
| 3735 |
if (ConservativeGC.isPrecise) |
| 3736 |
pullFromScanStackImpl!true(); |
| 3737 |
else |
| 3738 |
pullFromScanStackImpl!false(); |
| 3739 |
} |
| 3740 |
|
| 3741 |
void pullFromScanStackImpl(bool precise)() nothrow |
| 3742 |
{ |
| 3743 |
if (atomicLoad(busyThreads) == 0) |
| 3744 |
return; |
| 3745 |
|
| 3746 |
version (Posix) debug (PARALLEL_PRINTF) |
| 3747 |
{ |
| 3748 |
import core.sys.posix.pthread : pthread_self, pthread_t; |
| 3749 |
pthread_t threadId = pthread_self(); |
| 3750 |
printf("scanBackground thread %d start\n", threadId); |
| 3751 |
} |
| 3752 |
|
| 3753 |
ScanRange!precise rng; |
| 3754 |
alias toscan = scanStack!precise; |
| 3755 |
|
| 3756 |
while (atomicLoad(busyThreads) > 0) |
| 3757 |
{ |
| 3758 |
if (toscan.empty) |
| 3759 |
{ |
| 3760 |
evDone.wait(dur!"msecs"(1)); |
| 3761 |
continue; |
| 3762 |
} |
| 3763 |
|
| 3764 |
busyThreads.atomicOp!"+="(1); |
| 3765 |
if (toscan.popLocked(rng)) |
| 3766 |
{ |
| 3767 |
version (Posix) debug (PARALLEL_PRINTF) |
| 3768 |
{ |
| 3769 |
printf("scanBackground thread %d scanning range [%p,%lld] from stack\n", |
| 3770 |
threadId, rng.pbot, cast(long) (rng.ptop - rng.pbot)); |
| 3771 |
} |
| 3772 |
mark!(precise, true, true)(rng); |
| 3773 |
} |
| 3774 |
busyThreads.atomicOp!"-="(1); |
| 3775 |
} |
| 3776 |
version (Posix) debug (PARALLEL_PRINTF) printf("scanBackground thread %d done\n", threadId); |
| 3777 |
} |
| 3778 |
} |
| 3779 |
|
| 3780 |
/* ============================ Pool =============================== */ |
| 3781 |
|
| 3782 |
struct Pool |
| 3783 |
{ |
| 3784 |
void* baseAddr; |
| 3785 |
void* topAddr; |
| 3786 |
size_t ptIndex; // index in pool table |
| 3787 |
GCBits mark; // entries already scanned, or should not be scanned |
| 3788 |
GCBits freebits; // entries that are on the free list (all bits set but for allocated objects at their base offset) |
| 3789 |
GCBits finals; // entries that need finalizer run on them |
| 3790 |
GCBits structFinals;// struct entries that need a finalzier run on them |
| 3791 |
GCBits noscan; // entries that should not be scanned |
| 3792 |
GCBits appendable; // entries that are appendable |
| 3793 |
GCBits nointerior; // interior pointers should be ignored. |
| 3794 |
// Only implemented for large object pools. |
| 3795 |
GCBits is_pointer; // precise GC only: per-word, not per-block like the rest of them (SmallObjectPool only) |
| 3796 |
size_t npages; |
| 3797 |
size_t freepages; // The number of pages not in use. |
| 3798 |
Bins* pagetable; |
| 3799 |
|
| 3800 |
bool isLargeObject; |
| 3801 |
|
| 3802 |
enum ShiftBy |
| 3803 |
{ |
| 3804 |
Small = 4, |
| 3805 |
Large = 12 |
| 3806 |
} |
| 3807 |
ShiftBy shiftBy = void; // shift count for the divisor used for determining bit indices. |
| 3808 |
|
| 3809 |
// This tracks how far back we have to go to find the nearest B_PAGE at |
| 3810 |
// a smaller address than a B_PAGEPLUS. To save space, we use a uint. |
| 3811 |
// This limits individual allocations to 16 terabytes, assuming a 4k |
| 3812 |
// pagesize. (LargeObjectPool only) |
| 3813 |
// For B_PAGE and B_FREE, this specifies the number of pages in this block. |
| 3814 |
// As an optimization, a contiguous range of free pages tracks this information |
| 3815 |
// only for the first and the last page. |
| 3816 |
uint* bPageOffsets; |
| 3817 |
|
| 3818 |
// The small object pool uses the same array to keep a chain of |
| 3819 |
// - pages with the same bin size that are still to be recovered |
| 3820 |
// - free pages (searchStart is first free page) |
| 3821 |
// other pages are marked by value PageRecovered |
| 3822 |
alias binPageChain = bPageOffsets; |
| 3823 |
|
| 3824 |
enum PageRecovered = uint.max; |
| 3825 |
|
| 3826 |
// first of chain of pages to recover (SmallObjectPool only) |
| 3827 |
uint[Bins.B_NUMSMALL] recoverPageFirst; |
| 3828 |
|
| 3829 |
// precise GC: TypeInfo.rtInfo for allocation (LargeObjectPool only) |
| 3830 |
immutable(size_t)** rtinfo; |
| 3831 |
|
| 3832 |
// This variable tracks a conservative estimate of where the first free |
| 3833 |
// page in this pool is, so that if a lot of pages towards the beginning |
| 3834 |
// are occupied, we can bypass them in O(1). |
| 3835 |
size_t searchStart; |
| 3836 |
size_t largestFree; // upper limit for largest free chunk in large object pool |
| 3837 |
|
| 3838 |
void initialize(size_t npages, bool isLargeObject) nothrow |
| 3839 |
{ |
| 3840 |
assert(npages >= 256); |
| 3841 |
|
| 3842 |
this.isLargeObject = isLargeObject; |
| 3843 |
size_t poolsize; |
| 3844 |
|
| 3845 |
shiftBy = isLargeObject ? ShiftBy.Large : ShiftBy.Small; |
| 3846 |
|
| 3847 |
//debug(PRINTF) printf("Pool::Pool(%u)\n", npages); |
| 3848 |
poolsize = npages * PAGESIZE; |
| 3849 |
baseAddr = cast(byte *)os_mem_map(poolsize); |
| 3850 |
version (VALGRIND) makeMemNoAccess(baseAddr[0..poolsize]); |
| 3851 |
|
| 3852 |
// Some of the code depends on page alignment of memory pools |
| 3853 |
assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0); |
| 3854 |
|
| 3855 |
if (!baseAddr) |
| 3856 |
{ |
| 3857 |
//debug(PRINTF) printf("GC fail: poolsize = x%zx, errno = %d\n", poolsize, errno); |
| 3858 |
//debug(PRINTF) printf("message = '%s'\n", sys_errlist[errno]); |
| 3859 |
|
| 3860 |
npages = 0; |
| 3861 |
poolsize = 0; |
| 3862 |
} |
| 3863 |
//assert(baseAddr); |
| 3864 |
topAddr = baseAddr + poolsize; |
| 3865 |
auto nbits = cast(size_t)poolsize >> shiftBy; |
| 3866 |
|
| 3867 |
version (COLLECT_FORK) |
| 3868 |
mark.alloc(nbits, config.fork); |
| 3869 |
else |
| 3870 |
mark.alloc(nbits); |
| 3871 |
if (ConservativeGC.isPrecise) |
| 3872 |
{ |
| 3873 |
if (isLargeObject) |
| 3874 |
{ |
| 3875 |
rtinfo = cast(immutable(size_t)**)cstdlib.malloc(npages * (size_t*).sizeof); |
| 3876 |
if (!rtinfo) |
| 3877 |
onOutOfMemoryError(); |
| 3878 |
memset(rtinfo, 0, npages * (size_t*).sizeof); |
| 3879 |
} |
| 3880 |
else |
| 3881 |
{ |
| 3882 |
is_pointer.alloc(cast(size_t)poolsize/(void*).sizeof); |
| 3883 |
is_pointer.clrRange(0, is_pointer.nbits); |
| 3884 |
} |
| 3885 |
} |
| 3886 |
|
| 3887 |
// pagetable already keeps track of what's free for the large object |
| 3888 |
// pool. |
| 3889 |
if (!isLargeObject) |
| 3890 |
{ |
| 3891 |
freebits.alloc(nbits); |
| 3892 |
freebits.setRange(0, nbits); |
| 3893 |
} |
| 3894 |
|
| 3895 |
noscan.alloc(nbits); |
| 3896 |
appendable.alloc(nbits); |
| 3897 |
|
| 3898 |
pagetable = cast(Bins*)cstdlib.malloc(npages * Bins.sizeof); |
| 3899 |
if (!pagetable) |
| 3900 |
onOutOfMemoryError(); |
| 3901 |
|
| 3902 |
if (npages > 0) |
| 3903 |
{ |
| 3904 |
bPageOffsets = cast(uint*)cstdlib.malloc(npages * uint.sizeof); |
| 3905 |
if (!bPageOffsets) |
| 3906 |
onOutOfMemoryError(); |
| 3907 |
|
| 3908 |
if (isLargeObject) |
| 3909 |
{ |
| 3910 |
bPageOffsets[0] = cast(uint)npages; |
| 3911 |
bPageOffsets[npages-1] = cast(uint)npages; |
| 3912 |
} |
| 3913 |
else |
| 3914 |
{ |
| 3915 |
// all pages free |
| 3916 |
foreach (n; 0..npages) |
| 3917 |
binPageChain[n] = cast(uint)(n + 1); |
| 3918 |
recoverPageFirst[] = cast(uint)npages; |
| 3919 |
} |
| 3920 |
} |
| 3921 |
|
| 3922 |
memset(pagetable, Bins.B_FREE, npages); |
| 3923 |
|
| 3924 |
this.npages = npages; |
| 3925 |
this.freepages = npages; |
| 3926 |
this.searchStart = 0; |
| 3927 |
this.largestFree = npages; |
| 3928 |
} |
| 3929 |
|
| 3930 |
|
| 3931 |
void Dtor() nothrow |
| 3932 |
{ |
| 3933 |
if (baseAddr) |
| 3934 |
{ |
| 3935 |
int result; |
| 3936 |
|
| 3937 |
if (npages) |
| 3938 |
{ |
| 3939 |
result = os_mem_unmap(baseAddr, npages * PAGESIZE); |
| 3940 |
assert(result == 0); |
| 3941 |
npages = 0; |
| 3942 |
} |
| 3943 |
|
| 3944 |
baseAddr = null; |
| 3945 |
topAddr = null; |
| 3946 |
} |
| 3947 |
if (pagetable) |
| 3948 |
{ |
| 3949 |
cstdlib.free(pagetable); |
| 3950 |
pagetable = null; |
| 3951 |
} |
| 3952 |
|
| 3953 |
if (bPageOffsets) |
| 3954 |
{ |
| 3955 |
cstdlib.free(bPageOffsets); |
| 3956 |
bPageOffsets = null; |
| 3957 |
} |
| 3958 |
|
| 3959 |
mark.Dtor(config.fork); |
| 3960 |
if (ConservativeGC.isPrecise) |
| 3961 |
{ |
| 3962 |
if (isLargeObject) |
| 3963 |
cstdlib.free(rtinfo); |
| 3964 |
else |
| 3965 |
is_pointer.Dtor(); |
| 3966 |
} |
| 3967 |
if (isLargeObject) |
| 3968 |
{ |
| 3969 |
nointerior.Dtor(); |
| 3970 |
} |
| 3971 |
else |
| 3972 |
{ |
| 3973 |
freebits.Dtor(); |
| 3974 |
} |
| 3975 |
finals.Dtor(); |
| 3976 |
structFinals.Dtor(); |
| 3977 |
noscan.Dtor(); |
| 3978 |
appendable.Dtor(); |
| 3979 |
} |
| 3980 |
|
| 3981 |
/** |
| 3982 |
* |
| 3983 |
*/ |
| 3984 |
uint getBits(size_t biti) nothrow |
| 3985 |
{ |
| 3986 |
uint bits; |
| 3987 |
|
| 3988 |
if (finals.nbits && finals.test(biti)) |
| 3989 |
bits |= BlkAttr.FINALIZE; |
| 3990 |
if (structFinals.nbits && structFinals.test(biti)) |
| 3991 |
bits |= BlkAttr.STRUCTFINAL; |
| 3992 |
if (noscan.test(biti)) |
| 3993 |
bits |= BlkAttr.NO_SCAN; |
| 3994 |
if (nointerior.nbits && nointerior.test(biti)) |
| 3995 |
bits |= BlkAttr.NO_INTERIOR; |
| 3996 |
if (appendable.test(biti)) |
| 3997 |
bits |= BlkAttr.APPENDABLE; |
| 3998 |
return bits; |
| 3999 |
} |
| 4000 |
|
| 4001 |
/** |
| 4002 |
* |
| 4003 |
*/ |
| 4004 |
void clrBits(size_t biti, uint mask) nothrow @nogc |
| 4005 |
{ |
| 4006 |
immutable dataIndex = biti >> GCBits.BITS_SHIFT; |
| 4007 |
immutable bitOffset = biti & GCBits.BITS_MASK; |
| 4008 |
immutable keep = ~(GCBits.BITS_1 << bitOffset); |
| 4009 |
|
| 4010 |
if (mask & BlkAttr.FINALIZE && finals.nbits) |
| 4011 |
finals.data[dataIndex] &= keep; |
| 4012 |
|
| 4013 |
if (structFinals.nbits && (mask & BlkAttr.STRUCTFINAL)) |
| 4014 |
structFinals.data[dataIndex] &= keep; |
| 4015 |
|
| 4016 |
if (mask & BlkAttr.NO_SCAN) |
| 4017 |
noscan.data[dataIndex] &= keep; |
| 4018 |
if (mask & BlkAttr.APPENDABLE) |
| 4019 |
appendable.data[dataIndex] &= keep; |
| 4020 |
if (nointerior.nbits && (mask & BlkAttr.NO_INTERIOR)) |
| 4021 |
nointerior.data[dataIndex] &= keep; |
| 4022 |
} |
| 4023 |
|
| 4024 |
/** |
| 4025 |
* |
| 4026 |
*/ |
| 4027 |
void setBits(size_t biti, uint mask) nothrow |
| 4028 |
{ |
| 4029 |
// Calculate the mask and bit offset once and then use it to |
| 4030 |
// set all of the bits we need to set. |
| 4031 |
immutable dataIndex = biti >> GCBits.BITS_SHIFT; |
| 4032 |
immutable bitOffset = biti & GCBits.BITS_MASK; |
| 4033 |
immutable orWith = GCBits.BITS_1 << bitOffset; |
| 4034 |
|
| 4035 |
if (mask & BlkAttr.STRUCTFINAL) |
| 4036 |
{ |
| 4037 |
if (!structFinals.nbits) |
| 4038 |
structFinals.alloc(mark.nbits); |
| 4039 |
structFinals.data[dataIndex] |= orWith; |
| 4040 |
} |
| 4041 |
|
| 4042 |
if (mask & BlkAttr.FINALIZE) |
| 4043 |
{ |
| 4044 |
if (!finals.nbits) |
| 4045 |
finals.alloc(mark.nbits); |
| 4046 |
finals.data[dataIndex] |= orWith; |
| 4047 |
} |
| 4048 |
|
| 4049 |
if (mask & BlkAttr.NO_SCAN) |
| 4050 |
{ |
| 4051 |
noscan.data[dataIndex] |= orWith; |
| 4052 |
} |
| 4053 |
// if (mask & BlkAttr.NO_MOVE) |
| 4054 |
// { |
| 4055 |
// if (!nomove.nbits) |
| 4056 |
// nomove.alloc(mark.nbits); |
| 4057 |
// nomove.data[dataIndex] |= orWith; |
| 4058 |
// } |
| 4059 |
if (mask & BlkAttr.APPENDABLE) |
| 4060 |
{ |
| 4061 |
appendable.data[dataIndex] |= orWith; |
| 4062 |
} |
| 4063 |
|
| 4064 |
if (isLargeObject && (mask & BlkAttr.NO_INTERIOR)) |
| 4065 |
{ |
| 4066 |
if (!nointerior.nbits) |
| 4067 |
nointerior.alloc(mark.nbits); |
| 4068 |
nointerior.data[dataIndex] |= orWith; |
| 4069 |
} |
| 4070 |
} |
| 4071 |
|
| 4072 |
void freePageBits(size_t pagenum, const scope ref PageBits toFree) nothrow |
| 4073 |
{ |
| 4074 |
assert(!isLargeObject); |
| 4075 |
assert(!nointerior.nbits); // only for large objects |
| 4076 |
|
| 4077 |
import core.internal.traits : staticIota; |
| 4078 |
immutable beg = pagenum * (PAGESIZE / 16 / GCBits.BITS_PER_WORD); |
| 4079 |
foreach (i; staticIota!(0, PageBits.length)) |
| 4080 |
{ |
| 4081 |
immutable w = toFree[i]; |
| 4082 |
if (!w) continue; |
| 4083 |
|
| 4084 |
immutable wi = beg + i; |
| 4085 |
freebits.data[wi] |= w; |
| 4086 |
noscan.data[wi] &= ~w; |
| 4087 |
appendable.data[wi] &= ~w; |
| 4088 |
} |
| 4089 |
|
| 4090 |
if (finals.nbits) |
| 4091 |
{ |
| 4092 |
foreach (i; staticIota!(0, PageBits.length)) |
| 4093 |
if (toFree[i]) |
| 4094 |
finals.data[beg + i] &= ~toFree[i]; |
| 4095 |
} |
| 4096 |
|
| 4097 |
if (structFinals.nbits) |
| 4098 |
{ |
| 4099 |
foreach (i; staticIota!(0, PageBits.length)) |
| 4100 |
if (toFree[i]) |
| 4101 |
structFinals.data[beg + i] &= ~toFree[i]; |
| 4102 |
} |
| 4103 |
} |
| 4104 |
|
| 4105 |
void freeAllPageBits(size_t pagenum) nothrow |
| 4106 |
{ |
| 4107 |
assert(!isLargeObject); |
| 4108 |
assert(!nointerior.nbits); // only for large objects |
| 4109 |
|
| 4110 |
immutable beg = pagenum * PageBits.length; |
| 4111 |
static foreach (i; 0 .. PageBits.length) |
| 4112 |
{{ |
| 4113 |
immutable w = beg + i; |
| 4114 |
freebits.data[w] = ~0; |
| 4115 |
noscan.data[w] = 0; |
| 4116 |
appendable.data[w] = 0; |
| 4117 |
if (finals.data) |
| 4118 |
finals.data[w] = 0; |
| 4119 |
if (structFinals.data) |
| 4120 |
structFinals.data[w] = 0; |
| 4121 |
}} |
| 4122 |
} |
| 4123 |
|
| 4124 |
/** |
| 4125 |
* Given a pointer p in the p, return the pagenum. |
| 4126 |
*/ |
| 4127 |
size_t pagenumOf(void *p) const nothrow @nogc |
| 4128 |
in |
| 4129 |
{ |
| 4130 |
assert(p >= baseAddr); |
| 4131 |
assert(p < topAddr); |
| 4132 |
} |
| 4133 |
do |
| 4134 |
{ |
| 4135 |
return cast(size_t)(p - baseAddr) / PAGESIZE; |
| 4136 |
} |
| 4137 |
|
| 4138 |
public |
| 4139 |
@property bool isFree() const scope @safe pure nothrow @nogc |
| 4140 |
{ |
| 4141 |
return npages == freepages; |
| 4142 |
} |
| 4143 |
|
| 4144 |
/** |
| 4145 |
* Return number of pages necessary for an allocation of the given size |
| 4146 |
* |
| 4147 |
* returns size_t.max if more than uint.max pages are requested |
| 4148 |
* (return type is still size_t to avoid truncation when being used |
| 4149 |
* in calculations, e.g. npages * PAGESIZE) |
| 4150 |
*/ |
| 4151 |
static size_t numPages(size_t size) nothrow @nogc |
| 4152 |
{ |
| 4153 |
version (D_LP64) |
| 4154 |
{ |
| 4155 |
if (size > PAGESIZE * cast(size_t)uint.max) |
| 4156 |
return size_t.max; |
| 4157 |
} |
| 4158 |
else |
| 4159 |
{ |
| 4160 |
if (size > size_t.max - PAGESIZE) |
| 4161 |
return size_t.max; |
| 4162 |
} |
| 4163 |
return (size + PAGESIZE - 1) / PAGESIZE; |
| 4164 |
} |
| 4165 |
|
| 4166 |
void* findBase(void* p) nothrow @nogc |
| 4167 |
{ |
| 4168 |
size_t offset = cast(size_t)(p - baseAddr); |
| 4169 |
size_t pn = offset / PAGESIZE; |
| 4170 |
Bins bin = pagetable[pn]; |
| 4171 |
|
| 4172 |
// Adjust bit to be at start of allocated memory block |
| 4173 |
if (bin < Bins.B_NUMSMALL) |
| 4174 |
{ |
| 4175 |
auto baseOff = baseOffset(offset, bin); |
| 4176 |
const biti = baseOff >> Pool.ShiftBy.Small; |
| 4177 |
if (freebits.test (biti)) |
| 4178 |
return null; |
| 4179 |
return baseAddr + baseOff; |
| 4180 |
} |
| 4181 |
if (bin == Bins.B_PAGE) |
| 4182 |
{ |
| 4183 |
return baseAddr + (offset & (offset.max ^ (PAGESIZE-1))); |
| 4184 |
} |
| 4185 |
if (bin == Bins.B_PAGEPLUS) |
| 4186 |
{ |
| 4187 |
size_t pageOffset = bPageOffsets[pn]; |
| 4188 |
offset -= pageOffset * PAGESIZE; |
| 4189 |
pn -= pageOffset; |
| 4190 |
|
| 4191 |
return baseAddr + (offset & (offset.max ^ (PAGESIZE-1))); |
| 4192 |
} |
| 4193 |
// we are in a B_FREE page |
| 4194 |
assert(bin == Bins.B_FREE); |
| 4195 |
return null; |
| 4196 |
} |
| 4197 |
|
| 4198 |
size_t slGetSize(void* p) nothrow @nogc |
| 4199 |
{ |
| 4200 |
if (isLargeObject) |
| 4201 |
return (cast(LargeObjectPool*)&this).getPages(p) * PAGESIZE; |
| 4202 |
else |
| 4203 |
return (cast(SmallObjectPool*)&this).getSize(p); |
| 4204 |
} |
| 4205 |
|
| 4206 |
BlkInfo slGetInfo(void* p) nothrow |
| 4207 |
{ |
| 4208 |
if (isLargeObject) |
| 4209 |
return (cast(LargeObjectPool*)&this).getInfo(p); |
| 4210 |
else |
| 4211 |
return (cast(SmallObjectPool*)&this).getInfo(p); |
| 4212 |
} |
| 4213 |
|
| 4214 |
|
| 4215 |
void Invariant() const {} |
| 4216 |
|
| 4217 |
debug(INVARIANT) |
| 4218 |
invariant |
| 4219 |
{ |
| 4220 |
if (baseAddr) |
| 4221 |
{ |
| 4222 |
//if (baseAddr + npages * PAGESIZE != topAddr) |
| 4223 |
//printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr); |
| 4224 |
assert(baseAddr + npages * PAGESIZE == topAddr); |
| 4225 |
} |
| 4226 |
|
| 4227 |
if (pagetable !is null) |
| 4228 |
{ |
| 4229 |
for (size_t i = 0; i < npages; i++) |
| 4230 |
{ |
| 4231 |
Bins bin = pagetable[i]; |
| 4232 |
assert(bin < Bins.B_MAX); |
| 4233 |
} |
| 4234 |
} |
| 4235 |
} |
| 4236 |
|
| 4237 |
void setPointerBitmapSmall(void* p, size_t s, size_t allocSize, uint attr, const TypeInfo ti) nothrow |
| 4238 |
{ |
| 4239 |
if (!(attr & BlkAttr.NO_SCAN)) |
| 4240 |
setPointerBitmap(p, s, allocSize, ti, attr); |
| 4241 |
} |
| 4242 |
|
| 4243 |
pragma(inline,false) |
| 4244 |
void setPointerBitmap(void* p, size_t s, size_t allocSize, const TypeInfo ti, uint attr) nothrow |
| 4245 |
{ |
| 4246 |
size_t offset = p - baseAddr; |
| 4247 |
//debug(PRINTF) printGCBits(&pool.is_pointer); |
| 4248 |
|
| 4249 |
debug(PRINTF) |
| 4250 |
printf("Setting a pointer bitmap for %s at %p + %llu\n", debugTypeName(ti).ptr, p, cast(ulong)s); |
| 4251 |
|
| 4252 |
if (ti) |
| 4253 |
{ |
| 4254 |
if (attr & BlkAttr.APPENDABLE) |
| 4255 |
{ |
| 4256 |
// an array of classes is in fact an array of pointers |
| 4257 |
if (typeid(ti) is typeid(TypeInfo_Class)) |
| 4258 |
goto L_conservative; |
| 4259 |
s = allocSize; |
| 4260 |
} |
| 4261 |
|
| 4262 |
auto rtInfo = cast(const(size_t)*)ti.rtInfo(); |
| 4263 |
|
| 4264 |
if (rtInfo is rtinfoNoPointers) |
| 4265 |
{ |
| 4266 |
debug(PRINTF) printf("\tCompiler generated rtInfo: no pointers\n"); |
| 4267 |
is_pointer.clrRange(offset/(void*).sizeof, s/(void*).sizeof); |
| 4268 |
} |
| 4269 |
else if (rtInfo is rtinfoHasPointers) |
| 4270 |
{ |
| 4271 |
debug(PRINTF) printf("\tCompiler generated rtInfo: has pointers\n"); |
| 4272 |
is_pointer.setRange(offset/(void*).sizeof, s/(void*).sizeof); |
| 4273 |
} |
| 4274 |
else |
| 4275 |
{ |
| 4276 |
const(size_t)* bitmap = cast (size_t*) rtInfo; |
| 4277 |
//first element of rtInfo is the size of the object the bitmap encodes |
| 4278 |
size_t element_size = * bitmap; |
| 4279 |
bitmap++; |
| 4280 |
size_t tocopy; |
| 4281 |
if (attr & BlkAttr.APPENDABLE) |
| 4282 |
{ |
| 4283 |
tocopy = s/(void*).sizeof; |
| 4284 |
is_pointer.copyRangeRepeating(offset/(void*).sizeof, tocopy, bitmap, element_size/(void*).sizeof); |
| 4285 |
} |
| 4286 |
else |
| 4287 |
{ |
| 4288 |
tocopy = (s < element_size ? s : element_size)/(void*).sizeof; |
| 4289 |
is_pointer.copyRange(offset/(void*).sizeof, tocopy, bitmap); |
| 4290 |
} |
| 4291 |
|
| 4292 |
debug(PRINTF) printf("\tSetting bitmap for new object (%s)\n\t\tat %p\t\tcopying from %p + %llu: ", |
| 4293 |
debugTypeName(ti).ptr, p, bitmap, cast(ulong)element_size); |
| 4294 |
debug(PRINTF) |
| 4295 |
for (size_t i = 0; i < element_size/((void*).sizeof); i++) |
| 4296 |
printf("%zd", (bitmap[i/(8*size_t.sizeof)] >> (i%(8*size_t.sizeof))) & 1); |
| 4297 |
debug(PRINTF) printf("\n"); |
| 4298 |
|
| 4299 |
if (tocopy * (void*).sizeof < s) // better safe than sorry: if allocated more, assume pointers inside |
| 4300 |
{ |
| 4301 |
debug(PRINTF) printf(" Appending %zd pointer bits\n", s/(void*).sizeof - tocopy); |
| 4302 |
is_pointer.setRange(offset/(void*).sizeof + tocopy, s/(void*).sizeof - tocopy); |
| 4303 |
} |
| 4304 |
} |
| 4305 |
|
| 4306 |
if (s < allocSize) |
| 4307 |
{ |
| 4308 |
offset = (offset + s + (void*).sizeof - 1) & ~((void*).sizeof - 1); |
| 4309 |
is_pointer.clrRange(offset/(void*).sizeof, (allocSize - s)/(void*).sizeof); |
| 4310 |
} |
| 4311 |
} |
| 4312 |
else |
| 4313 |
{ |
| 4314 |
L_conservative: |
| 4315 |
// limit pointers to actual size of allocation? might fail for arrays that append |
| 4316 |
// without notifying the GC |
| 4317 |
s = allocSize; |
| 4318 |
|
| 4319 |
debug(PRINTF) printf("Allocating a block without TypeInfo\n"); |
| 4320 |
is_pointer.setRange(offset/(void*).sizeof, s/(void*).sizeof); |
| 4321 |
} |
| 4322 |
//debug(PRINTF) printGCBits(&pool.is_pointer); |
| 4323 |
} |
| 4324 |
} |
| 4325 |
|
| 4326 |
struct LargeObjectPool |
| 4327 |
{ |
| 4328 |
Pool base; |
| 4329 |
alias base this; |
| 4330 |
|
| 4331 |
debug(INVARIANT) |
| 4332 |
void Invariant() |
| 4333 |
{ |
| 4334 |
//base.Invariant(); |
| 4335 |
for (size_t n = 0; n < npages; ) |
| 4336 |
{ |
| 4337 |
uint np = bPageOffsets[n]; |
| 4338 |
assert(np > 0 && np <= npages - n); |
| 4339 |
|
| 4340 |
if (pagetable[n] == Bins.B_PAGE) |
| 4341 |
{ |
| 4342 |
for (uint p = 1; p < np; p++) |
| 4343 |
{ |
| 4344 |
assert(pagetable[n + p] == Bins.B_PAGEPLUS); |
| 4345 |
assert(bPageOffsets[n + p] == p); |
| 4346 |
} |
| 4347 |
} |
| 4348 |
else if (pagetable[n] == Bins.B_FREE) |
| 4349 |
{ |
| 4350 |
for (uint p = 1; p < np; p++) |
| 4351 |
{ |
| 4352 |
assert(pagetable[n + p] == Bins.B_FREE); |
| 4353 |
} |
| 4354 |
assert(bPageOffsets[n + np - 1] == np); |
| 4355 |
} |
| 4356 |
else |
| 4357 |
assert(false); |
| 4358 |
n += np; |
| 4359 |
} |
| 4360 |
} |
| 4361 |
|
| 4362 |
/** |
| 4363 |
* Allocate n pages from Pool. |
| 4364 |
* Returns OPFAIL on failure. |
| 4365 |
*/ |
| 4366 |
size_t allocPages(size_t n) nothrow |
| 4367 |
{ |
| 4368 |
if (largestFree < n || searchStart + n > npages) |
| 4369 |
return OPFAIL; |
| 4370 |
|
| 4371 |
//debug(PRINTF) printf("Pool::allocPages(n = %d)\n", n); |
| 4372 |
size_t largest = 0; |
| 4373 |
if (pagetable[searchStart] == Bins.B_PAGEPLUS) |
| 4374 |
{ |
| 4375 |
searchStart -= bPageOffsets[searchStart]; // jump to B_PAGE |
| 4376 |
searchStart += bPageOffsets[searchStart]; |
| 4377 |
} |
| 4378 |
while (searchStart < npages && pagetable[searchStart] == Bins.B_PAGE) |
| 4379 |
searchStart += bPageOffsets[searchStart]; |
| 4380 |
|
| 4381 |
for (size_t i = searchStart; i < npages; ) |
| 4382 |
{ |
| 4383 |
assert(pagetable[i] == Bins.B_FREE); |
| 4384 |
|
| 4385 |
auto p = bPageOffsets[i]; |
| 4386 |
if (p > n) |
| 4387 |
{ |
| 4388 |
setFreePageOffsets(i + n, p - n); |
| 4389 |
goto L_found; |
| 4390 |
} |
| 4391 |
if (p == n) |
| 4392 |
{ |
| 4393 |
L_found: |
| 4394 |
pagetable[i] = Bins.B_PAGE; |
| 4395 |
bPageOffsets[i] = cast(uint) n; |
| 4396 |
if (n > 1) |
| 4397 |
{ |
| 4398 |
memset(&pagetable[i + 1], Bins.B_PAGEPLUS, n - 1); |
| 4399 |
for (auto offset = 1; offset < n; offset++) |
| 4400 |
bPageOffsets[i + offset] = cast(uint) offset; |
| 4401 |
} |
| 4402 |
freepages -= n; |
| 4403 |
return i; |
| 4404 |
} |
| 4405 |
if (p > largest) |
| 4406 |
largest = p; |
| 4407 |
|
| 4408 |
i += p; |
| 4409 |
while (i < npages && pagetable[i] == Bins.B_PAGE) |
| 4410 |
{ |
| 4411 |
// we have the size information, so we skip a whole bunch of pages. |
| 4412 |
i += bPageOffsets[i]; |
| 4413 |
} |
| 4414 |
} |
| 4415 |
|
| 4416 |
// not enough free pages found, remember largest free chunk |
| 4417 |
largestFree = largest; |
| 4418 |
return OPFAIL; |
| 4419 |
} |
| 4420 |
|
| 4421 |
/** |
| 4422 |
* Free npages pages starting with pagenum. |
| 4423 |
*/ |
| 4424 |
void freePages(size_t pagenum, size_t npages) nothrow @nogc |
| 4425 |
{ |
| 4426 |
//memset(&pagetable[pagenum], B_FREE, npages); |
| 4427 |
if (pagenum < searchStart) |
| 4428 |
searchStart = pagenum; |
| 4429 |
|
| 4430 |
for (size_t i = pagenum; i < npages + pagenum; i++) |
| 4431 |
{ |
| 4432 |
assert(pagetable[i] < Bins.B_FREE); |
| 4433 |
pagetable[i] = Bins.B_FREE; |
| 4434 |
} |
| 4435 |
freepages += npages; |
| 4436 |
largestFree = freepages; // invalidate |
| 4437 |
} |
| 4438 |
|
| 4439 |
/** |
| 4440 |
* Set the first and the last entry of a B_FREE block to the size |
| 4441 |
*/ |
| 4442 |
void setFreePageOffsets(size_t page, size_t num) nothrow @nogc |
| 4443 |
{ |
| 4444 |
assert(pagetable[page] == Bins.B_FREE); |
| 4445 |
assert(pagetable[page + num - 1] == Bins.B_FREE); |
| 4446 |
bPageOffsets[page] = cast(uint)num; |
| 4447 |
if (num > 1) |
| 4448 |
bPageOffsets[page + num - 1] = cast(uint)num; |
| 4449 |
} |
| 4450 |
|
| 4451 |
void mergeFreePageOffsets(bool bwd, bool fwd)(size_t page, size_t num) nothrow @nogc |
| 4452 |
{ |
| 4453 |
static if (bwd) |
| 4454 |
{ |
| 4455 |
if (page > 0 && pagetable[page - 1] == Bins.B_FREE) |
| 4456 |
{ |
| 4457 |
auto sz = bPageOffsets[page - 1]; |
| 4458 |
page -= sz; |
| 4459 |
num += sz; |
| 4460 |
} |
| 4461 |
} |
| 4462 |
static if (fwd) |
| 4463 |
{ |
| 4464 |
if (page + num < npages && pagetable[page + num] == Bins.B_FREE) |
| 4465 |
num += bPageOffsets[page + num]; |
| 4466 |
} |
| 4467 |
setFreePageOffsets(page, num); |
| 4468 |
} |
| 4469 |
|
| 4470 |
/** |
| 4471 |
* Get pages of allocation at pointer p in pool. |
| 4472 |
*/ |
| 4473 |
size_t getPages(void *p) const nothrow @nogc |
| 4474 |
in |
| 4475 |
{ |
| 4476 |
assert(p >= baseAddr); |
| 4477 |
assert(p < topAddr); |
| 4478 |
} |
| 4479 |
do |
| 4480 |
{ |
| 4481 |
if (cast(size_t)p & (PAGESIZE - 1)) // check for interior pointer |
| 4482 |
return 0; |
| 4483 |
size_t pagenum = pagenumOf(p); |
| 4484 |
Bins bin = pagetable[pagenum]; |
| 4485 |
if (bin != Bins.B_PAGE) |
| 4486 |
return 0; |
| 4487 |
return bPageOffsets[pagenum]; |
| 4488 |
} |
| 4489 |
|
| 4490 |
/** |
| 4491 |
* Get size of allocation at page pn in pool. |
| 4492 |
*/ |
| 4493 |
size_t getSize(size_t pn) const nothrow @nogc |
| 4494 |
{ |
| 4495 |
assert(pagetable[pn] == Bins.B_PAGE); |
| 4496 |
return cast(size_t) bPageOffsets[pn] * PAGESIZE; |
| 4497 |
} |
| 4498 |
|
| 4499 |
/** |
| 4500 |
* |
| 4501 |
*/ |
| 4502 |
BlkInfo getInfo(void* p) nothrow |
| 4503 |
{ |
| 4504 |
BlkInfo info; |
| 4505 |
|
| 4506 |
size_t offset = cast(size_t)(p - baseAddr); |
| 4507 |
size_t pn = offset / PAGESIZE; |
| 4508 |
Bins bin = pagetable[pn]; |
| 4509 |
|
| 4510 |
if (bin == Bins.B_PAGEPLUS) |
| 4511 |
pn -= bPageOffsets[pn]; |
| 4512 |
else if (bin != Bins.B_PAGE) |
| 4513 |
return info; // no info for free pages |
| 4514 |
|
| 4515 |
info.base = baseAddr + pn * PAGESIZE; |
| 4516 |
info.size = getSize(pn); |
| 4517 |
info.attr = getBits(pn); |
| 4518 |
return info; |
| 4519 |
} |
| 4520 |
|
| 4521 |
void runFinalizers(const scope void[] segment) nothrow |
| 4522 |
{ |
| 4523 |
foreach (pn; 0 .. npages) |
| 4524 |
{ |
| 4525 |
Bins bin = pagetable[pn]; |
| 4526 |
if (bin > Bins.B_PAGE) |
| 4527 |
continue; |
| 4528 |
size_t biti = pn; |
| 4529 |
|
| 4530 |
if (!finals.test(biti)) |
| 4531 |
continue; |
| 4532 |
|
| 4533 |
auto p = sentinel_add(baseAddr + pn * PAGESIZE); |
| 4534 |
size_t size = sentinel_size(p, getSize(pn)); |
| 4535 |
uint attr = getBits(biti); |
| 4536 |
|
| 4537 |
import core.internal.gc.blockmeta; |
| 4538 |
auto ti = __getBlockFinalizerInfo(p, size, attr); |
| 4539 |
if (!rt_hasFinalizerInSegment(p, size, ti, segment)) |
| 4540 |
continue; |
| 4541 |
|
| 4542 |
__trimExtents(p, size, attr); |
| 4543 |
rt_finalizeFromGC(p, size, attr, ti); |
| 4544 |
|
| 4545 |
clrBits(biti, ~BlkAttr.NONE); |
| 4546 |
|
| 4547 |
if (pn < searchStart) |
| 4548 |
searchStart = pn; |
| 4549 |
|
| 4550 |
debug(COLLECT_PRINTF) printf("\tcollecting big %p\n", p); |
| 4551 |
//log_free(sentinel_add(p)); |
| 4552 |
|
| 4553 |
size_t n = 1; |
| 4554 |
for (; pn + n < npages; ++n) |
| 4555 |
if (pagetable[pn + n] != Bins.B_PAGEPLUS) |
| 4556 |
break; |
| 4557 |
invalidate((baseAddr + pn * PAGESIZE)[0 .. n * PAGESIZE], 0xF3, false); |
| 4558 |
freePages(pn, n); |
| 4559 |
mergeFreePageOffsets!(true, true)(pn, n); |
| 4560 |
} |
| 4561 |
} |
| 4562 |
} |
| 4563 |
|
| 4564 |
|
| 4565 |
struct SmallObjectPool |
| 4566 |
{ |
| 4567 |
Pool base; |
| 4568 |
alias base this; |
| 4569 |
|
| 4570 |
debug(INVARIANT) |
| 4571 |
void Invariant() |
| 4572 |
{ |
| 4573 |
//base.Invariant(); |
| 4574 |
uint cntRecover = 0; |
| 4575 |
foreach (Bins bin; Bins.B_16 .. Bins.B_NUMSMALL) |
| 4576 |
{ |
| 4577 |
for (auto pn = recoverPageFirst[bin]; pn < npages; pn = binPageChain[pn]) |
| 4578 |
{ |
| 4579 |
assert(pagetable[pn] == bin); |
| 4580 |
cntRecover++; |
| 4581 |
} |
| 4582 |
} |
| 4583 |
uint cntFree = 0; |
| 4584 |
for (auto pn = searchStart; pn < npages; pn = binPageChain[pn]) |
| 4585 |
{ |
| 4586 |
assert(pagetable[pn] == Bins.B_FREE); |
| 4587 |
cntFree++; |
| 4588 |
} |
| 4589 |
assert(cntFree == freepages); |
| 4590 |
assert(cntFree + cntRecover <= npages); |
| 4591 |
} |
| 4592 |
|
| 4593 |
/** |
| 4594 |
* Get size of pointer p in pool. |
| 4595 |
*/ |
| 4596 |
size_t getSize(void *p) const nothrow @nogc |
| 4597 |
in |
| 4598 |
{ |
| 4599 |
assert(p >= baseAddr); |
| 4600 |
assert(p < topAddr); |
| 4601 |
} |
| 4602 |
do |
| 4603 |
{ |
| 4604 |
size_t pagenum = pagenumOf(p); |
| 4605 |
Bins bin = pagetable[pagenum]; |
| 4606 |
assert(bin < Bins.B_PAGE); |
| 4607 |
if (p != cast(void*)baseOffset(cast(size_t)p, bin)) // check for interior pointer |
| 4608 |
return 0; |
| 4609 |
const biti = cast(size_t)(p - baseAddr) >> ShiftBy.Small; |
| 4610 |
if (freebits.test (biti)) |
| 4611 |
return 0; |
| 4612 |
return binsize[bin]; |
| 4613 |
} |
| 4614 |
|
| 4615 |
BlkInfo getInfo(void* p) nothrow |
| 4616 |
{ |
| 4617 |
BlkInfo info; |
| 4618 |
size_t offset = cast(size_t)(p - baseAddr); |
| 4619 |
size_t pn = offset / PAGESIZE; |
| 4620 |
Bins bin = pagetable[pn]; |
| 4621 |
|
| 4622 |
if (bin >= Bins.B_PAGE) |
| 4623 |
return info; |
| 4624 |
|
| 4625 |
auto base = cast(void*)baseOffset(cast(size_t)p, bin); |
| 4626 |
const biti = cast(size_t)(base - baseAddr) >> ShiftBy.Small; |
| 4627 |
if (freebits.test (biti)) |
| 4628 |
return info; |
| 4629 |
|
| 4630 |
info.base = base; |
| 4631 |
info.size = binsize[bin]; |
| 4632 |
offset = info.base - baseAddr; |
| 4633 |
info.attr = getBits(biti); |
| 4634 |
|
| 4635 |
return info; |
| 4636 |
} |
| 4637 |
|
| 4638 |
void runFinalizers(const scope void[] segment) nothrow |
| 4639 |
{ |
| 4640 |
foreach (pn; 0 .. npages) |
| 4641 |
{ |
| 4642 |
Bins bin = pagetable[pn]; |
| 4643 |
if (bin >= Bins.B_PAGE) |
| 4644 |
continue; |
| 4645 |
|
| 4646 |
immutable size = binsize[bin]; |
| 4647 |
auto p = baseAddr + pn * PAGESIZE; |
| 4648 |
const ptop = p + PAGESIZE - size + 1; |
| 4649 |
immutable base = pn * (PAGESIZE/16); |
| 4650 |
immutable bitstride = size / 16; |
| 4651 |
|
| 4652 |
bool freeBits; |
| 4653 |
PageBits toFree; |
| 4654 |
|
| 4655 |
for (size_t i; p < ptop; p += size, i += bitstride) |
| 4656 |
{ |
| 4657 |
immutable biti = base + i; |
| 4658 |
|
| 4659 |
if (!finals.test(biti)) |
| 4660 |
continue; |
| 4661 |
|
| 4662 |
auto q = sentinel_add(p); |
| 4663 |
uint attr = getBits(biti); |
| 4664 |
auto ssize = sentinel_size(q, size); |
| 4665 |
import core.internal.gc.blockmeta; |
| 4666 |
auto ti = __getBlockFinalizerInfo(q, ssize, attr); |
| 4667 |
if (!rt_hasFinalizerInSegment(q, ssize, ti, segment)) |
| 4668 |
continue; |
| 4669 |
|
| 4670 |
__trimExtents(q, ssize, attr); |
| 4671 |
rt_finalizeFromGC(q, ssize, attr, ti); |
| 4672 |
|
| 4673 |
freeBits = true; |
| 4674 |
toFree.set(i); |
| 4675 |
|
| 4676 |
debug(COLLECT_PRINTF) printf("\tcollecting %p\n", p); |
| 4677 |
//log_free(sentinel_add(p)); |
| 4678 |
|
| 4679 |
invalidate(p[0 .. size], 0xF3, false); |
| 4680 |
} |
| 4681 |
|
| 4682 |
if (freeBits) |
| 4683 |
freePageBits(pn, toFree); |
| 4684 |
} |
| 4685 |
} |
| 4686 |
|
| 4687 |
/** |
| 4688 |
* Allocate a page of bin's. |
| 4689 |
* Returns: |
| 4690 |
* head of a single linked list of new entries |
| 4691 |
*/ |
| 4692 |
List* allocPage(Bins bin) nothrow |
| 4693 |
{ |
| 4694 |
if (searchStart >= npages) |
| 4695 |
return null; |
| 4696 |
|
| 4697 |
assert(pagetable[searchStart] == Bins.B_FREE); |
| 4698 |
|
| 4699 |
L1: |
| 4700 |
size_t pn = searchStart; |
| 4701 |
searchStart = binPageChain[searchStart]; |
| 4702 |
binPageChain[pn] = Pool.PageRecovered; |
| 4703 |
pagetable[pn] = bin; |
| 4704 |
freepages--; |
| 4705 |
|
| 4706 |
// Convert page to free list |
| 4707 |
size_t size = binsize[bin]; |
| 4708 |
void* p = baseAddr + pn * PAGESIZE; |
| 4709 |
auto first = cast(List*) p; |
| 4710 |
|
| 4711 |
// ensure 2 <size> bytes blocks are available below ptop, one |
| 4712 |
// being set in the loop, and one for the tail block |
| 4713 |
void* ptop = p + PAGESIZE - 2 * size + 1; |
| 4714 |
for (; p < ptop; p += size) |
| 4715 |
{ |
| 4716 |
undefinedWrite((cast(List *)p).next, cast(List *)(p + size)); |
| 4717 |
undefinedWrite((cast(List *)p).pool, &base); |
| 4718 |
} |
| 4719 |
undefinedWrite((cast(List *)p).next, null); |
| 4720 |
undefinedWrite((cast(List *)p).pool, &base); |
| 4721 |
return first; |
| 4722 |
} |
| 4723 |
} |
| 4724 |
|
| 4725 |
debug(SENTINEL) {} else // no additional capacity with SENTINEL |
| 4726 |
unittest // https://issues.dlang.org/show_bug.cgi?id=14467 |
| 4727 |
{ |
| 4728 |
int[] arr = new int[10]; |
| 4729 |
assert(arr.capacity); |
| 4730 |
arr = arr[$..$]; |
| 4731 |
assert(arr.capacity); |
| 4732 |
} |
| 4733 |
|
| 4734 |
unittest // https://issues.dlang.org/show_bug.cgi?id=15353 |
| 4735 |
{ |
| 4736 |
import core.memory : GC; |
| 4737 |
|
| 4738 |
static struct Foo |
| 4739 |
{ |
| 4740 |
~this() |
| 4741 |
{ |
| 4742 |
GC.free(buf); // ignored in finalizer |
| 4743 |
} |
| 4744 |
|
| 4745 |
void* buf; |
| 4746 |
} |
| 4747 |
new Foo(GC.malloc(10)); |
| 4748 |
GC.collect(); |
| 4749 |
} |
| 4750 |
|
| 4751 |
unittest // https://issues.dlang.org/show_bug.cgi?id=15822 |
| 4752 |
{ |
| 4753 |
import core.memory : GC; |
| 4754 |
|
| 4755 |
__gshared ubyte[16] buf; |
| 4756 |
static struct Foo |
| 4757 |
{ |
| 4758 |
~this() |
| 4759 |
{ |
| 4760 |
GC.removeRange(ptr); |
| 4761 |
GC.removeRoot(ptr); |
| 4762 |
} |
| 4763 |
|
| 4764 |
ubyte* ptr; |
| 4765 |
} |
| 4766 |
GC.addRoot(buf.ptr); |
| 4767 |
GC.addRange(buf.ptr, buf.length); |
| 4768 |
new Foo(buf.ptr); |
| 4769 |
GC.collect(); |
| 4770 |
} |
| 4771 |
|
| 4772 |
unittest // https://issues.dlang.org/show_bug.cgi?id=1180 |
| 4773 |
{ |
| 4774 |
import core.exception; |
| 4775 |
try |
| 4776 |
{ |
| 4777 |
size_t x = size_t.max - 100; |
| 4778 |
byte[] big_buf = new byte[x]; |
| 4779 |
} |
| 4780 |
catch (OutOfMemoryError) |
| 4781 |
{ |
| 4782 |
} |
| 4783 |
} |
| 4784 |
|
| 4785 |
/* ============================ PRINTF =============================== */ |
| 4786 |
|
| 4787 |
debug(PRINTF_TO_FILE) |
| 4788 |
{ |
| 4789 |
private __gshared MonoTime gcStartTick; |
| 4790 |
private __gshared FILE* gcx_fh; |
| 4791 |
private __gshared bool hadNewline = false; |
| 4792 |
import core.internal.spinlock; |
| 4793 |
static printLock = shared(AlignedSpinLock)(SpinLock.Contention.lengthy); |
| 4794 |
|
| 4795 |
private int printf(ARGS...)(const char* fmt, ARGS args) nothrow |
| 4796 |
{ |
| 4797 |
printLock.lock(); |
| 4798 |
scope(exit) printLock.unlock(); |
| 4799 |
|
| 4800 |
if (!gcx_fh) |
| 4801 |
gcx_fh = fopen("gcx.log", "w"); |
| 4802 |
if (!gcx_fh) |
| 4803 |
return 0; |
| 4804 |
|
| 4805 |
int len; |
| 4806 |
if (MonoTime.ticksPerSecond == 0) |
| 4807 |
{ |
| 4808 |
len = fprintf(gcx_fh, "before init: "); |
| 4809 |
} |
| 4810 |
else if (hadNewline) |
| 4811 |
{ |
| 4812 |
if (gcStartTick == MonoTime.init) |
| 4813 |
gcStartTick = MonoTime.currTime; |
| 4814 |
immutable timeElapsed = MonoTime.currTime - gcStartTick; |
| 4815 |
immutable secondsAsDouble = timeElapsed.total!"hnsecs" / cast(double)convert!("seconds", "hnsecs")(1); |
| 4816 |
len = fprintf(gcx_fh, "%10.6f: ", secondsAsDouble); |
| 4817 |
} |
| 4818 |
len += fprintf(gcx_fh, fmt, args); |
| 4819 |
fflush(gcx_fh); |
| 4820 |
import core.stdc.string : strlen; |
| 4821 |
hadNewline = fmt && fmt[0] && fmt[strlen(fmt) - 1] == '\n'; |
| 4822 |
return len; |
| 4823 |
} |
| 4824 |
} |
| 4825 |
|
| 4826 |
debug(PRINTF) void printFreeInfo(Pool* pool) nothrow |
| 4827 |
{ |
| 4828 |
uint nReallyFree; |
| 4829 |
foreach (i; 0..pool.npages) { |
| 4830 |
if (pool.pagetable[i] >= Bins.B_FREE) nReallyFree++; |
| 4831 |
} |
| 4832 |
|
| 4833 |
printf("Pool %p: %d really free, %zd supposedly free\n", pool, nReallyFree, pool.freepages); |
| 4834 |
} |
| 4835 |
|
| 4836 |
debug(PRINTF) |
| 4837 |
void printGCBits(GCBits* bits) |
| 4838 |
{ |
| 4839 |
for (size_t i = 0; i < bits.nwords; i++) |
| 4840 |
{ |
| 4841 |
if (i % 32 == 0) printf("\n\t"); |
| 4842 |
printf("%zx ", bits.data[i]); |
| 4843 |
} |
| 4844 |
printf("\n"); |
| 4845 |
} |
| 4846 |
|
| 4847 |
// we can assume the name is always from a literal, so it is zero terminated |
| 4848 |
debug(PRINTF) |
| 4849 |
string debugTypeName(const(TypeInfo) ti) nothrow |
| 4850 |
{ |
| 4851 |
string name; |
| 4852 |
if (ti is null) |
| 4853 |
name = "null"; |
| 4854 |
else if (auto ci = cast(TypeInfo_Class)ti) |
| 4855 |
name = ci.name; |
| 4856 |
else if (auto si = cast(TypeInfo_Struct)ti) |
| 4857 |
name = si.mangledName; // .name() might GC-allocate, avoid deadlock |
| 4858 |
else if (auto ci = cast(TypeInfo_Const)ti) |
| 4859 |
static if (__traits(compiles,ci.base)) // different whether compiled with object.di or object.d |
| 4860 |
return debugTypeName(ci.base); |
| 4861 |
else |
| 4862 |
return debugTypeName(ci.next); |
| 4863 |
else |
| 4864 |
name = typeid(ti).name; |
| 4865 |
return name; |
| 4866 |
} |
| 4867 |
|
| 4868 |
/* ======================= Leak Detector =========================== */ |
| 4869 |
|
| 4870 |
debug (LOGGING) |
| 4871 |
{ |
| 4872 |
struct Log |
| 4873 |
{ |
| 4874 |
void* p; |
| 4875 |
size_t size; |
| 4876 |
size_t line; |
| 4877 |
char* file; |
| 4878 |
void* parent; |
| 4879 |
|
| 4880 |
void print() nothrow |
| 4881 |
{ |
| 4882 |
printf(" p = %p, size = %lld, parent = %p ", p, cast(ulong)size, parent); |
| 4883 |
if (file) |
| 4884 |
{ |
| 4885 |
printf("%s(%u)", file, cast(uint)line); |
| 4886 |
} |
| 4887 |
printf("\n"); |
| 4888 |
} |
| 4889 |
} |
| 4890 |
|
| 4891 |
|
| 4892 |
struct LogArray |
| 4893 |
{ |
| 4894 |
size_t dim; |
| 4895 |
size_t allocdim; |
| 4896 |
Log *data; |
| 4897 |
|
| 4898 |
void Dtor() nothrow @nogc |
| 4899 |
{ |
| 4900 |
if (data) |
| 4901 |
cstdlib.free(data); |
| 4902 |
data = null; |
| 4903 |
} |
| 4904 |
|
| 4905 |
void reserve(size_t nentries) nothrow @nogc |
| 4906 |
{ |
| 4907 |
assert(dim <= allocdim); |
| 4908 |
if (allocdim - dim < nentries) |
| 4909 |
{ |
| 4910 |
allocdim = (dim + nentries) * 2; |
| 4911 |
assert(dim + nentries <= allocdim); |
| 4912 |
if (!data) |
| 4913 |
{ |
| 4914 |
data = cast(Log*)cstdlib.malloc(allocdim * Log.sizeof); |
| 4915 |
if (!data && allocdim) |
| 4916 |
onOutOfMemoryError(); |
| 4917 |
} |
| 4918 |
else |
| 4919 |
{ Log *newdata; |
| 4920 |
|
| 4921 |
newdata = cast(Log*)cstdlib.malloc(allocdim * Log.sizeof); |
| 4922 |
if (!newdata && allocdim) |
| 4923 |
onOutOfMemoryError(); |
| 4924 |
memcpy(newdata, data, dim * Log.sizeof); |
| 4925 |
cstdlib.free(data); |
| 4926 |
data = newdata; |
| 4927 |
} |
| 4928 |
} |
| 4929 |
} |
| 4930 |
|
| 4931 |
|
| 4932 |
void push(Log log) nothrow @nogc |
| 4933 |
{ |
| 4934 |
reserve(1); |
| 4935 |
data[dim++] = log; |
| 4936 |
} |
| 4937 |
|
| 4938 |
void remove(size_t i) nothrow @nogc |
| 4939 |
{ |
| 4940 |
memmove(data + i, data + i + 1, (dim - i) * Log.sizeof); |
| 4941 |
dim--; |
| 4942 |
} |
| 4943 |
|
| 4944 |
|
| 4945 |
size_t find(void *p) nothrow @nogc |
| 4946 |
{ |
| 4947 |
for (size_t i = 0; i < dim; i++) |
| 4948 |
{ |
| 4949 |
if (data[i].p == p) |
| 4950 |
return i; |
| 4951 |
} |
| 4952 |
return OPFAIL; // not found |
| 4953 |
} |
| 4954 |
|
| 4955 |
|
| 4956 |
void copy(LogArray *from) nothrow @nogc |
| 4957 |
{ |
| 4958 |
if (allocdim < from.dim) |
| 4959 |
reserve(from.dim - dim); |
| 4960 |
assert(from.dim <= allocdim); |
| 4961 |
memcpy(data, from.data, from.dim * Log.sizeof); |
| 4962 |
dim = from.dim; |
| 4963 |
} |
| 4964 |
} |
| 4965 |
|
| 4966 |
struct LeakDetector |
| 4967 |
{ |
| 4968 |
Gcx* gcx; |
| 4969 |
LogArray current; |
| 4970 |
LogArray prev; |
| 4971 |
|
| 4972 |
private void initialize(Gcx* gc) |
| 4973 |
{ |
| 4974 |
gcx = gc; |
| 4975 |
//debug(PRINTF) printf("+log_init()\n"); |
| 4976 |
current.reserve(1000); |
| 4977 |
prev.reserve(1000); |
| 4978 |
//debug(PRINTF) printf("-log_init()\n"); |
| 4979 |
} |
| 4980 |
|
| 4981 |
|
| 4982 |
private void log_malloc(void *p, size_t size) nothrow |
| 4983 |
{ |
| 4984 |
//debug(PRINTF) printf("+log_malloc(p = %p, size = %zd)\n", p, size); |
| 4985 |
Log log; |
| 4986 |
|
| 4987 |
log.p = p; |
| 4988 |
log.size = size; |
| 4989 |
log.line = ConservativeGC.line; |
| 4990 |
log.file = ConservativeGC.file; |
| 4991 |
log.parent = null; |
| 4992 |
|
| 4993 |
ConservativeGC.line = 0; |
| 4994 |
ConservativeGC.file = null; |
| 4995 |
|
| 4996 |
current.push(log); |
| 4997 |
//debug(PRINTF) printf("-log_malloc()\n"); |
| 4998 |
} |
| 4999 |
|
| 5000 |
|
| 5001 |
private void log_free(void *p, size_t size) nothrow @nogc |
| 5002 |
{ |
| 5003 |
//debug(PRINTF) printf("+log_free(%p)\n", p); |
| 5004 |
auto i = current.find(p); |
| 5005 |
if (i == OPFAIL) |
| 5006 |
{ |
| 5007 |
debug(PRINTF) printf("free'ing unallocated memory %p (size %zu)\n", p, size); |
| 5008 |
} |
| 5009 |
else |
| 5010 |
current.remove(i); |
| 5011 |
//debug(PRINTF) printf("-log_free()\n"); |
| 5012 |
} |
| 5013 |
|
| 5014 |
|
| 5015 |
private void log_collect() nothrow |
| 5016 |
{ |
| 5017 |
//debug(PRINTF) printf("+log_collect()\n"); |
| 5018 |
// Print everything in current that is not in prev |
| 5019 |
|
| 5020 |
debug(PRINTF) printf("New pointers this cycle: --------------------------------\n"); |
| 5021 |
size_t used = 0; |
| 5022 |
for (size_t i = 0; i < current.dim; i++) |
| 5023 |
{ |
| 5024 |
auto j = prev.find(current.data[i].p); |
| 5025 |
if (j == OPFAIL) |
| 5026 |
current.data[i].print(); |
| 5027 |
else |
| 5028 |
used++; |
| 5029 |
} |
| 5030 |
|
| 5031 |
debug(PRINTF) printf("All roots this cycle: --------------------------------\n"); |
| 5032 |
for (size_t i = 0; i < current.dim; i++) |
| 5033 |
{ |
| 5034 |
void* p = current.data[i].p; |
| 5035 |
if (!gcx.findPool(current.data[i].parent)) |
| 5036 |
{ |
| 5037 |
auto j = prev.find(current.data[i].p); |
| 5038 |
debug(PRINTF) printf(j == OPFAIL ? "N" : " "); |
| 5039 |
current.data[i].print(); |
| 5040 |
} |
| 5041 |
} |
| 5042 |
|
| 5043 |
debug(PRINTF) printf("Used = %d-------------------------------------------------\n", used); |
| 5044 |
prev.copy(¤t); |
| 5045 |
|
| 5046 |
debug(PRINTF) printf("-log_collect()\n"); |
| 5047 |
} |
| 5048 |
|
| 5049 |
|
| 5050 |
private void log_parent(void *p, void *parent) nothrow |
| 5051 |
{ |
| 5052 |
//debug(PRINTF) printf("+log_parent()\n"); |
| 5053 |
auto i = current.find(p); |
| 5054 |
if (i == OPFAIL) |
| 5055 |
{ |
| 5056 |
debug(PRINTF) printf("parent'ing unallocated memory %p, parent = %p\n", p, parent); |
| 5057 |
Pool *pool; |
| 5058 |
pool = gcx.findPool(p); |
| 5059 |
assert(pool); |
| 5060 |
size_t offset = cast(size_t)(p - pool.baseAddr); |
| 5061 |
size_t biti; |
| 5062 |
size_t pn = offset / PAGESIZE; |
| 5063 |
Bins bin = pool.pagetable[pn]; |
| 5064 |
biti = (offset & (PAGESIZE - 1)) >> pool.shiftBy; |
| 5065 |
debug(PRINTF) printf("\tbin = %d, offset = x%x, biti = x%x\n", bin, offset, biti); |
| 5066 |
} |
| 5067 |
else |
| 5068 |
{ |
| 5069 |
current.data[i].parent = parent; |
| 5070 |
} |
| 5071 |
//debug(PRINTF) printf("-log_parent()\n"); |
| 5072 |
} |
| 5073 |
} |
| 5074 |
} |
| 5075 |
else |
| 5076 |
{ |
| 5077 |
struct LeakDetector |
| 5078 |
{ |
| 5079 |
static void initialize(Gcx* gcx) nothrow { } |
| 5080 |
static void log_malloc(void *p, size_t size) nothrow { } |
| 5081 |
static void log_free(void *p, size_t size) nothrow @nogc {} |
| 5082 |
static void log_collect() nothrow { } |
| 5083 |
static void log_parent(void *p, void *parent) nothrow { } |
| 5084 |
} |
| 5085 |
} |
| 5086 |
|
| 5087 |
/* ============================ SENTINEL =============================== */ |
| 5088 |
|
| 5089 |
debug (SENTINEL) |
| 5090 |
{ |
| 5091 |
// pre-sentinel must be smaller than 16 bytes so that the same GC bits |
| 5092 |
// are used for the allocated pointer and the user pointer |
| 5093 |
// so use uint for both 32 and 64 bit platforms, limiting usage to < 4GB |
| 5094 |
const uint SENTINEL_PRE = 0xF4F4F4F4; |
| 5095 |
const ubyte SENTINEL_POST = 0xF5; // 8 bits |
| 5096 |
const uint SENTINEL_EXTRA = 2 * uint.sizeof + 1; |
| 5097 |
|
| 5098 |
|
| 5099 |
inout(uint*) sentinel_psize(inout void *p) nothrow @nogc { return &(cast(inout uint *)p)[-2]; } |
| 5100 |
inout(uint*) sentinel_pre(inout void *p) nothrow @nogc { return &(cast(inout uint *)p)[-1]; } |
| 5101 |
inout(ubyte*) sentinel_post(inout void *p) nothrow @nogc { return &(cast(inout ubyte *)p)[*sentinel_psize(p)]; } |
| 5102 |
|
| 5103 |
|
| 5104 |
void sentinel_init(void *p, size_t size) nothrow @nogc |
| 5105 |
{ |
| 5106 |
assert(size <= uint.max); |
| 5107 |
*sentinel_psize(p) = cast(uint)size; |
| 5108 |
debug (VALGRIND) |
| 5109 |
{ |
| 5110 |
makeMemNoAccess(sentinel_pre(p)[0..1]); |
| 5111 |
makeMemNoAccess(sentinel_post(p)[0..1]); |
| 5112 |
} |
| 5113 |
else |
| 5114 |
{ |
| 5115 |
*sentinel_pre(p) = SENTINEL_PRE; |
| 5116 |
*sentinel_post(p) = SENTINEL_POST; |
| 5117 |
} |
| 5118 |
} |
| 5119 |
|
| 5120 |
|
| 5121 |
void sentinel_Invariant(const void *p) nothrow @nogc |
| 5122 |
{ |
| 5123 |
debug (VALGRIND) {} else |
| 5124 |
debug |
| 5125 |
{ |
| 5126 |
assert(*sentinel_pre(p) == SENTINEL_PRE); |
| 5127 |
assert(*sentinel_post(p) == SENTINEL_POST); |
| 5128 |
} |
| 5129 |
else if (*sentinel_pre(p) != SENTINEL_PRE || *sentinel_post(p) != SENTINEL_POST) |
| 5130 |
onInvalidMemoryOperationError(); // also trigger in release build |
| 5131 |
} |
| 5132 |
|
| 5133 |
size_t sentinel_size(const void *p, size_t alloc_size) nothrow @nogc |
| 5134 |
{ |
| 5135 |
return *sentinel_psize(p); |
| 5136 |
} |
| 5137 |
|
| 5138 |
void *sentinel_add(void *p) nothrow @nogc |
| 5139 |
{ |
| 5140 |
return p + 2 * uint.sizeof; |
| 5141 |
} |
| 5142 |
|
| 5143 |
|
| 5144 |
void *sentinel_sub(void *p) nothrow @nogc |
| 5145 |
{ |
| 5146 |
return p - 2 * uint.sizeof; |
| 5147 |
} |
| 5148 |
} |
| 5149 |
else |
| 5150 |
{ |
| 5151 |
const uint SENTINEL_EXTRA = 0; |
| 5152 |
|
| 5153 |
|
| 5154 |
void sentinel_init(void *p, size_t size) nothrow @nogc |
| 5155 |
{ |
| 5156 |
} |
| 5157 |
|
| 5158 |
|
| 5159 |
void sentinel_Invariant(const void *p) nothrow @nogc |
| 5160 |
{ |
| 5161 |
} |
| 5162 |
|
| 5163 |
size_t sentinel_size(const void *p, size_t alloc_size) nothrow @nogc |
| 5164 |
{ |
| 5165 |
return alloc_size; |
| 5166 |
} |
| 5167 |
|
| 5168 |
void *sentinel_add(void *p) nothrow @nogc |
| 5169 |
{ |
| 5170 |
return p; |
| 5171 |
} |
| 5172 |
|
| 5173 |
|
| 5174 |
void *sentinel_sub(void *p) nothrow @nogc |
| 5175 |
{ |
| 5176 |
return p; |
| 5177 |
} |
| 5178 |
} |
| 5179 |
|
| 5180 |
debug (MEMSTOMP) |
| 5181 |
unittest |
| 5182 |
{ |
| 5183 |
import core.memory; |
| 5184 |
auto p = cast(size_t*)GC.malloc(size_t.sizeof*3); |
| 5185 |
assert(*p == cast(size_t)0xF0F0F0F0F0F0F0F0); |
| 5186 |
p[2] = 0; // First two will be used for free list |
| 5187 |
GC.free(p); |
| 5188 |
assert(p[2] == cast(size_t)0xF2F2F2F2F2F2F2F2); |
| 5189 |
} |
| 5190 |
|
| 5191 |
debug (SENTINEL) |
| 5192 |
unittest |
| 5193 |
{ |
| 5194 |
import core.memory; |
| 5195 |
auto p = cast(ubyte*)GC.malloc(1); |
| 5196 |
assert(p[-1] == 0xF4); |
| 5197 |
assert(p[ 1] == 0xF5); |
| 5198 |
|
| 5199 |
// See also stand-alone tests in test/gc |
| 5200 |
} |
| 5201 |
|
| 5202 |
unittest |
| 5203 |
{ |
| 5204 |
import core.memory; |
| 5205 |
|
| 5206 |
// https://issues.dlang.org/show_bug.cgi?id=9275 |
| 5207 |
GC.removeRoot(null); |
| 5208 |
GC.removeRoot(cast(void*)13); |
| 5209 |
} |
| 5210 |
|
| 5211 |
// improve predictability of coverage of code that is eventually not hit by other tests |
| 5212 |
debug (SENTINEL) {} else // cannot extend with SENTINEL |
| 5213 |
debug (MARK_PRINTF) {} else // takes forever |
| 5214 |
version (OnlyLowMemUnittests) {} else |
| 5215 |
unittest |
| 5216 |
{ |
| 5217 |
import core.memory; |
| 5218 |
auto p = GC.malloc(260 << 20); // new pool has 390 MB |
| 5219 |
auto q = GC.malloc(65 << 20); // next chunk (larger than 64MB to ensure the same pool is used) |
| 5220 |
auto r = GC.malloc(65 << 20); // another chunk in same pool |
| 5221 |
assert(p + (260 << 20) == q); |
| 5222 |
assert(q + (65 << 20) == r); |
| 5223 |
GC.free(q); |
| 5224 |
// should trigger "assert(bin == Bins.B_FREE);" in mark due to dangling pointer q: |
| 5225 |
GC.collect(); |
| 5226 |
// should trigger "break;" in extendNoSync: |
| 5227 |
size_t sz = GC.extend(p, 64 << 20, 66 << 20); // trigger size after p large enough (but limited) |
| 5228 |
assert(sz == 325 << 20); |
| 5229 |
GC.free(p); |
| 5230 |
GC.free(r); |
| 5231 |
r = q; // ensure q is not trashed before collection above |
| 5232 |
|
| 5233 |
p = GC.malloc(70 << 20); // from the same pool |
| 5234 |
q = GC.malloc(70 << 20); |
| 5235 |
r = GC.malloc(70 << 20); |
| 5236 |
auto s = GC.malloc(70 << 20); |
| 5237 |
auto t = GC.malloc(70 << 20); // 350 MB of 390 MB used |
| 5238 |
assert(p + (70 << 20) == q); |
| 5239 |
assert(q + (70 << 20) == r); |
| 5240 |
assert(r + (70 << 20) == s); |
| 5241 |
assert(s + (70 << 20) == t); |
| 5242 |
GC.free(r); // ensure recalculation of largestFree in nxxt allocPages |
| 5243 |
auto z = GC.malloc(75 << 20); // needs new pool |
| 5244 |
|
| 5245 |
GC.free(p); |
| 5246 |
GC.free(q); |
| 5247 |
GC.free(s); |
| 5248 |
GC.free(t); |
| 5249 |
GC.free(z); |
| 5250 |
GC.minimize(); // release huge pool |
| 5251 |
} |
| 5252 |
|
| 5253 |
// https://issues.dlang.org/show_bug.cgi?id=19281 |
| 5254 |
debug (SENTINEL) {} else // cannot allow >= 4 GB with SENTINEL |
| 5255 |
debug (MEMSTOMP) {} else // might take too long to actually touch the memory |
| 5256 |
version (D_LP64) unittest |
| 5257 |
{ |
| 5258 |
static if (__traits(compiles, os_physical_mem)) |
| 5259 |
{ |
| 5260 |
// only run if the system has enough physical memory |
| 5261 |
size_t sz = 2L^^32; |
| 5262 |
size_t phys_mem = os_physical_mem(true); |
| 5263 |
if (phys_mem > sz) |
| 5264 |
{ |
| 5265 |
import core.memory; |
| 5266 |
import core.exception; |
| 5267 |
GC.collect(); |
| 5268 |
GC.minimize(); |
| 5269 |
try |
| 5270 |
{ |
| 5271 |
auto stats = GC.stats(); |
| 5272 |
auto ptr = GC.malloc(sz, BlkAttr.NO_SCAN); |
| 5273 |
auto info = GC.query(ptr); |
| 5274 |
//printf("info.size = %lld", info.size); |
| 5275 |
assert(info.size >= sz); |
| 5276 |
GC.free(ptr); |
| 5277 |
GC.minimize(); |
| 5278 |
auto nstats = GC.stats(); |
| 5279 |
assert(nstats.usedSize == stats.usedSize); |
| 5280 |
assert(nstats.freeSize == stats.freeSize); |
| 5281 |
assert(nstats.allocatedInCurrentThread - sz == stats.allocatedInCurrentThread); |
| 5282 |
} |
| 5283 |
catch (OutOfMemoryError) |
| 5284 |
{ |
| 5285 |
// ignore if the system still doesn't have enough virtual memory |
| 5286 |
import core.stdc.stdio : printf; |
| 5287 |
printf("%s(%d): out-of-memory exception ignored, phys_mem = %zd", |
| 5288 |
__FILE__.ptr, __LINE__, phys_mem); |
| 5289 |
} |
| 5290 |
} |
| 5291 |
} |
| 5292 |
} |
| 5293 |
|
| 5294 |
// https://issues.dlang.org/show_bug.cgi?id=19522 |
| 5295 |
unittest |
| 5296 |
{ |
| 5297 |
import core.memory; |
| 5298 |
|
| 5299 |
void test(void* p) |
| 5300 |
{ |
| 5301 |
assert(GC.getAttr(p) == BlkAttr.NO_SCAN); |
| 5302 |
assert(GC.setAttr(p + 4, BlkAttr.NO_SCAN) == 0); // interior pointer should fail |
| 5303 |
assert(GC.clrAttr(p + 4, BlkAttr.NO_SCAN) == 0); // interior pointer should fail |
| 5304 |
GC.free(p); |
| 5305 |
assert(GC.query(p).base == null); |
| 5306 |
assert(GC.query(p).size == 0); |
| 5307 |
assert(GC.addrOf(p) == null); |
| 5308 |
assert(GC.sizeOf(p) == 0); // fails |
| 5309 |
assert(GC.getAttr(p) == 0); |
| 5310 |
assert(GC.setAttr(p, BlkAttr.NO_SCAN) == 0); |
| 5311 |
assert(GC.clrAttr(p, BlkAttr.NO_SCAN) == 0); |
| 5312 |
} |
| 5313 |
void* large = GC.malloc(10000, BlkAttr.NO_SCAN); |
| 5314 |
test(large); |
| 5315 |
|
| 5316 |
void* small = GC.malloc(100, BlkAttr.NO_SCAN); |
| 5317 |
test(small); |
| 5318 |
} |
| 5319 |
|
| 5320 |
unittest |
| 5321 |
{ |
| 5322 |
import core.memory; |
| 5323 |
|
| 5324 |
auto now = currTime; |
| 5325 |
GC.ProfileStats stats1 = GC.profileStats(); |
| 5326 |
GC.collect(); |
| 5327 |
GC.ProfileStats stats2 = GC.profileStats(); |
| 5328 |
auto diff = currTime - now; |
| 5329 |
|
| 5330 |
assert(stats2.totalCollectionTime - stats1.totalCollectionTime <= diff); |
| 5331 |
assert(stats2.totalPauseTime - stats1.totalPauseTime <= stats2.totalCollectionTime - stats1.totalCollectionTime); |
| 5332 |
|
| 5333 |
assert(stats2.maxPauseTime >= stats1.maxPauseTime); |
| 5334 |
assert(stats2.maxCollectionTime >= stats1.maxCollectionTime); |
| 5335 |
} |
| 5336 |
|
| 5337 |
// https://issues.dlang.org/show_bug.cgi?id=20214 |
| 5338 |
unittest |
| 5339 |
{ |
| 5340 |
import core.memory; |
| 5341 |
import core.stdc.stdio : printf; |
| 5342 |
|
| 5343 |
// allocate from large pool |
| 5344 |
auto o = GC.malloc(10); |
| 5345 |
auto p = (cast(void**)GC.malloc(4096 * (void*).sizeof))[0 .. 4096]; |
| 5346 |
auto q = (cast(void**)GC.malloc(4096 * (void*).sizeof))[0 .. 4096]; |
| 5347 |
if (p.ptr + p.length is q.ptr) |
| 5348 |
{ |
| 5349 |
q[] = o; // fill with pointers |
| 5350 |
|
| 5351 |
// shrink, unused area cleared? |
| 5352 |
auto nq = (cast(void**)GC.realloc(q.ptr, 4000 * (void*).sizeof))[0 .. 4000]; |
| 5353 |
assert(q.ptr is nq.ptr); |
| 5354 |
assert(q.ptr[4095] !is o); |
| 5355 |
|
| 5356 |
GC.free(q.ptr); |
| 5357 |
// expected to extend in place |
| 5358 |
auto np = (cast(void**)GC.realloc(p.ptr, 4200 * (void*).sizeof))[0 .. 4200]; |
| 5359 |
assert(p.ptr is np.ptr); |
| 5360 |
assert(q.ptr[4200] !is o); |
| 5361 |
} |
| 5362 |
else |
| 5363 |
{ |
| 5364 |
// adjacent allocations likely but not guaranteed |
| 5365 |
printf("unexpected pointers %p and %p\n", p.ptr, q.ptr); |
| 5366 |
} |
| 5367 |
} |
| 5368 |
|
| 5369 |
/* ============================ MEMSTOMP =============================== */ |
| 5370 |
|
| 5371 |
/// Mark the specified memory region as uninitialized - |
| 5372 |
/// reading from this region is an error. |
| 5373 |
/// If writable is false, writing to it is also an error. |
| 5374 |
pragma(inline, true) |
| 5375 |
void invalidate(void[] mem, ubyte pattern, bool writable) nothrow @nogc |
| 5376 |
{ |
| 5377 |
debug (MEMSTOMP) memset(mem.ptr, pattern, mem.length); |
| 5378 |
debug (VALGRIND) |
| 5379 |
{ |
| 5380 |
if (writable) |
| 5381 |
makeMemUndefined(mem); |
| 5382 |
else |
| 5383 |
makeMemNoAccess(mem); |
| 5384 |
} |
| 5385 |
} |
| 5386 |
|
| 5387 |
/// Read memory that should otherwise be marked as unreadable |
| 5388 |
/// (e.g. free lists overlapped with unallocated heap objects). |
| 5389 |
pragma(inline, true) |
| 5390 |
T undefinedRead(T)(ref T var) nothrow |
| 5391 |
{ |
| 5392 |
debug (VALGRIND) |
| 5393 |
{ |
| 5394 |
auto varArr = (&var)[0..1]; |
| 5395 |
disableAddrReportingInRange(varArr); |
| 5396 |
T result = var; |
| 5397 |
enableAddrReportingInRange(varArr); |
| 5398 |
return result; |
| 5399 |
} |
| 5400 |
else |
| 5401 |
return var; |
| 5402 |
} |
| 5403 |
|
| 5404 |
/// Write memory that should otherwise be marked as unwritable. |
| 5405 |
pragma(inline, true) |
| 5406 |
void undefinedWrite(T)(ref T var, T value) nothrow |
| 5407 |
{ |
| 5408 |
debug (VALGRIND) |
| 5409 |
{ |
| 5410 |
auto varArr = (&var)[0..1]; |
| 5411 |
disableAddrReportingInRange(varArr); |
| 5412 |
var = value; |
| 5413 |
enableAddrReportingInRange(varArr); |
| 5414 |
} |
| 5415 |
else |
| 5416 |
var = value; |
| 5417 |
} |
| 5418 |
|
| 5419 |
private void adjustAttrs(ref uint attrs, const TypeInfo ti) nothrow |
| 5420 |
{ |
| 5421 |
bool hasContext = ti !is null; |
| 5422 |
if((attrs & BlkAttr.FINALIZE) && hasContext && typeid(ti) is typeid(TypeInfo_Struct)) |
| 5423 |
attrs |= BlkAttr.STRUCTFINAL; |
| 5424 |
else |
| 5425 |
// STRUCTFINAL now just means "has a context pointer added to the block" |
| 5426 |
attrs &= ~BlkAttr.STRUCTFINAL; |
| 5427 |
} |
| 5428 |
|
| 5429 |
// sets up the array/context pointer metadata based on the block allocated. |
| 5430 |
// This is called on any block *creation*, and not on updating the array |
| 5431 |
// metadata. |
| 5432 |
// |
| 5433 |
// The return value is the true data that the user can use. |
| 5434 |
private void[] setupMetadata(void[] block, uint bits, size_t padding, size_t used, const TypeInfo ti) nothrow |
| 5435 |
{ |
| 5436 |
import core.internal.gc.blockmeta; |
| 5437 |
import core.internal.array.utils; |
| 5438 |
|
| 5439 |
BlkInfo info = BlkInfo( |
| 5440 |
base: block.ptr, |
| 5441 |
attr: bits, |
| 5442 |
size: block.length |
| 5443 |
); |
| 5444 |
|
| 5445 |
|
| 5446 |
__setBlockFinalizerInfo(info, ti); |
| 5447 |
|
| 5448 |
if (bits & BlkAttr.APPENDABLE) { |
| 5449 |
auto typeInfoSize = (bits & BlkAttr.STRUCTFINAL) ? (void*).sizeof : 0; |
| 5450 |
auto success = __setArrayAllocLengthImpl(info, used, false, size_t.max, typeInfoSize); |
| 5451 |
assert(success); |
| 5452 |
return __arrayStart(info)[0 .. block.length - padding]; |
| 5453 |
} |
| 5454 |
|
| 5455 |
return block.ptr[0 .. block.length - padding]; |
| 5456 |
} |