1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Garbage collector: finalizers and block profiling.
10 "runtime/internal/atomic"
11 "runtime/internal/sys"
15 type finblock struct {
20 fin [(_FinBlockSize - 2*sys.PtrSize - 2*4) / unsafe.Sizeof(finalizer{})]finalizer
23 var finlock mutex // protects the following variables
24 var fing *g // goroutine that runs finalizers
25 var finq *finblock // list of finalizers that are to be executed
26 var finc *finblock // cache of free blocks
27 var finptrmask [_FinBlockSize / sys.PtrSize / 8]byte
30 var allfin *finblock // list of all blocks
32 // NOTE: Layout known to queuefinalizer.
33 type finalizer struct {
34 fn *funcval // function to call
35 arg unsafe.Pointer // ptr to object
36 nret uintptr // bytes of return values from fn
37 fint *_type // type of first argument of fn
38 ot *ptrtype // type of ptr to object
41 var finalizer1 = [...]byte{
42 // Each Finalizer is 5 words, ptr ptr INT ptr ptr (INT = uintptr here)
43 // Each byte describes 8 words.
44 // Need 8 Finalizers described by 5 bytes before pattern repeats:
45 // ptr ptr INT ptr ptr
46 // ptr ptr INT ptr ptr
47 // ptr ptr INT ptr ptr
48 // ptr ptr INT ptr ptr
49 // ptr ptr INT ptr ptr
50 // ptr ptr INT ptr ptr
51 // ptr ptr INT ptr ptr
52 // ptr ptr INT ptr ptr
55 // ptr ptr INT ptr ptr ptr ptr INT
56 // ptr ptr ptr ptr INT ptr ptr ptr
57 // ptr INT ptr ptr ptr ptr INT ptr
58 // ptr ptr ptr INT ptr ptr ptr ptr
59 // INT ptr ptr ptr ptr INT ptr ptr
61 // Assumptions about Finalizer layout checked below.
62 1<<0 | 1<<1 | 0<<2 | 1<<3 | 1<<4 | 1<<5 | 1<<6 | 0<<7,
63 1<<0 | 1<<1 | 1<<2 | 1<<3 | 0<<4 | 1<<5 | 1<<6 | 1<<7,
64 1<<0 | 0<<1 | 1<<2 | 1<<3 | 1<<4 | 1<<5 | 0<<6 | 1<<7,
65 1<<0 | 1<<1 | 1<<2 | 0<<3 | 1<<4 | 1<<5 | 1<<6 | 1<<7,
66 0<<0 | 1<<1 | 1<<2 | 1<<3 | 1<<4 | 0<<5 | 1<<6 | 1<<7,
69 func queuefinalizer(p unsafe.Pointer, fn *funcval, nret uintptr, fint *_type, ot *ptrtype) {
71 if finq == nil || finq.cnt == int32(len(finq.fin)) {
73 // Note: write barrier here, assigning to finc, but should be okay.
74 finc = (*finblock)(persistentalloc(_FinBlockSize, 0, &memstats.gc_sys))
77 if finptrmask[0] == 0 {
78 // Build pointer mask for Finalizer array in block.
79 // Check assumptions made in finalizer1 array above.
80 if (unsafe.Sizeof(finalizer{}) != 5*sys.PtrSize ||
81 unsafe.Offsetof(finalizer{}.fn) != 0 ||
82 unsafe.Offsetof(finalizer{}.arg) != sys.PtrSize ||
83 unsafe.Offsetof(finalizer{}.nret) != 2*sys.PtrSize ||
84 unsafe.Offsetof(finalizer{}.fint) != 3*sys.PtrSize ||
85 unsafe.Offsetof(finalizer{}.ot) != 4*sys.PtrSize) {
86 throw("finalizer out of sync")
88 for i := range finptrmask {
89 finptrmask[i] = finalizer1[i%len(finalizer1)]
98 f := &finq.fin[finq.cnt]
110 func iterate_finq(callback func(*funcval, unsafe.Pointer, uintptr, *_type, *ptrtype)) {
111 for fb := allfin; fb != nil; fb = fb.alllink {
112 for i := int32(0); i < fb.cnt; i++ {
114 callback(f.fn, f.arg, f.nret, f.fint, f.ot)
122 if fingwait && fingwake {
137 // start the finalizer goroutine exactly once
138 if fingCreate == 0 && atomic.Cas(&fingCreate, 0, 1) {
143 // This is the goroutine that runs all of the finalizers
158 goparkunlock(&finlock, "finalizer wait", traceEvGoBlock, 1)
166 for i := fb.cnt; i > 0; i-- {
169 framesz := unsafe.Sizeof((interface{})(nil)) + f.nret
170 if framecap < framesz {
171 // The frame does not contain pointers interesting for GC,
172 // all not yet finalized objects are stored in finq.
173 // If we do not mark it as FlagNoScan,
174 // the last finalized object is not collected.
175 frame = mallocgc(framesz, nil, true)
180 throw("missing type in runfinq")
182 switch f.fint.kind & kindMask {
184 // direct use of pointer
185 *(*unsafe.Pointer)(frame) = f.arg
187 ityp := (*interfacetype)(unsafe.Pointer(f.fint))
188 // set up with empty interface
189 (*eface)(frame)._type = &f.ot.typ
190 (*eface)(frame).data = f.arg
191 if len(ityp.mhdr) != 0 {
192 // convert to interface with methods
193 // this conversion is guaranteed to succeed - we checked in SetFinalizer
194 assertE2I(ityp, *(*eface)(frame), (*iface)(frame))
197 throw("bad kind in runfinq")
200 reflectcall(nil, unsafe.Pointer(f.fn), frame, uint32(framesz), uint32(framesz))
203 // drop finalizer queue references to finalized object
219 // SetFinalizer sets the finalizer associated with obj to the provided
220 // finalizer function. When the garbage collector finds an unreachable block
221 // with an associated finalizer, it clears the association and runs
222 // finalizer(obj) in a separate goroutine. This makes obj reachable again,
223 // but now without an associated finalizer. Assuming that SetFinalizer
224 // is not called again, the next time the garbage collector sees
225 // that obj is unreachable, it will free obj.
227 // SetFinalizer(obj, nil) clears any finalizer associated with obj.
229 // The argument obj must be a pointer to an object allocated by
230 // calling new or by taking the address of a composite literal.
231 // The argument finalizer must be a function that takes a single argument
232 // to which obj's type can be assigned, and can have arbitrary ignored return
233 // values. If either of these is not true, SetFinalizer aborts the
236 // Finalizers are run in dependency order: if A points at B, both have
237 // finalizers, and they are otherwise unreachable, only the finalizer
238 // for A runs; once A is freed, the finalizer for B can run.
239 // If a cyclic structure includes a block with a finalizer, that
240 // cycle is not guaranteed to be garbage collected and the finalizer
241 // is not guaranteed to run, because there is no ordering that
242 // respects the dependencies.
244 // The finalizer for obj is scheduled to run at some arbitrary time after
245 // obj becomes unreachable.
246 // There is no guarantee that finalizers will run before a program exits,
247 // so typically they are useful only for releasing non-memory resources
248 // associated with an object during a long-running program.
249 // For example, an os.File object could use a finalizer to close the
250 // associated operating system file descriptor when a program discards
251 // an os.File without calling Close, but it would be a mistake
252 // to depend on a finalizer to flush an in-memory I/O buffer such as a
253 // bufio.Writer, because the buffer would not be flushed at program exit.
255 // It is not guaranteed that a finalizer will run if the size of *obj is
258 // It is not guaranteed that a finalizer will run for objects allocated
259 // in initializers for package-level variables. Such objects may be
260 // linker-allocated, not heap-allocated.
262 // A single goroutine runs all finalizers for a program, sequentially.
263 // If a finalizer must run for a long time, it should do so by starting
265 func SetFinalizer(obj interface{}, finalizer interface{}) {
267 // debug.sbrk never frees memory, so no finalizers run
268 // (and we don't have the data structures to record them).
274 throw("runtime.SetFinalizer: first argument is nil")
276 if etyp.kind&kindMask != kindPtr {
277 throw("runtime.SetFinalizer: first argument is " + etyp.string() + ", not pointer")
279 ot := (*ptrtype)(unsafe.Pointer(etyp))
281 throw("nil elem type!")
284 // find the containing object
285 _, base, _ := findObject(e.data)
288 // 0-length objects are okay.
289 if e.data == unsafe.Pointer(&zerobase) {
293 // Global initializers might be linker-allocated.
294 // var Foo = &Object{}
296 // runtime.SetFinalizer(Foo, nil)
298 // The relevant segments are: noptrdata, data, bss, noptrbss.
299 // We cannot assume they are in any order or even contiguous,
300 // due to external linking.
301 for datap := &firstmoduledata; datap != nil; datap = datap.next {
302 if datap.noptrdata <= uintptr(e.data) && uintptr(e.data) < datap.enoptrdata ||
303 datap.data <= uintptr(e.data) && uintptr(e.data) < datap.edata ||
304 datap.bss <= uintptr(e.data) && uintptr(e.data) < datap.ebss ||
305 datap.noptrbss <= uintptr(e.data) && uintptr(e.data) < datap.enoptrbss {
309 throw("runtime.SetFinalizer: pointer not in allocated block")
313 // As an implementation detail we allow to set finalizers for an inner byte
314 // of an object if it could come from tiny alloc (see mallocgc for details).
315 if ot.elem == nil || ot.elem.kind&kindNoPointers == 0 || ot.elem.size >= maxTinySize {
316 throw("runtime.SetFinalizer: pointer not at beginning of allocated block")
320 f := efaceOf(&finalizer)
323 // switch to system stack and remove finalizer
325 removefinalizer(e.data)
330 if ftyp.kind&kindMask != kindFunc {
331 throw("runtime.SetFinalizer: second argument is " + ftyp.string() + ", not a function")
333 ft := (*functype)(unsafe.Pointer(ftyp))
335 throw("runtime.SetFinalizer: cannot pass " + etyp.string() + " to finalizer " + ftyp.string() + " because dotdotdot")
337 if ft.dotdotdot() || ft.inCount != 1 {
338 throw("runtime.SetFinalizer: cannot pass " + etyp.string() + " to finalizer " + ftyp.string())
345 case fint.kind&kindMask == kindPtr:
346 if (fint.uncommon() == nil || etyp.uncommon() == nil) && (*ptrtype)(unsafe.Pointer(fint)).elem == ot.elem {
347 // ok - not same type, but both pointers,
348 // one or the other is unnamed, and same element type, so assignable.
351 case fint.kind&kindMask == kindInterface:
352 ityp := (*interfacetype)(unsafe.Pointer(fint))
353 if len(ityp.mhdr) == 0 {
354 // ok - satisfies empty interface
357 if assertE2I2(ityp, *efaceOf(&obj), nil) {
361 throw("runtime.SetFinalizer: cannot pass " + etyp.string() + " to finalizer " + ftyp.string())
363 // compute size needed for return parameters
365 for _, t := range ft.out() {
366 nret = round(nret, uintptr(t.align)) + uintptr(t.size)
368 nret = round(nret, sys.PtrSize)
370 // make sure we have a finalizer goroutine
374 if !addfinalizer(e.data, (*funcval)(f.data), nret, fint, ot) {
375 throw("runtime.SetFinalizer: finalizer already set")
380 // Look up pointer v in heap. Return the span containing the object,
381 // the start of the object, and the size of the object. If the object
382 // does not exist, return nil, nil, 0.
383 func findObject(v unsafe.Pointer) (s *mspan, x unsafe.Pointer, n uintptr) {
386 if sys.PtrSize == 4 && c.local_nlookup >= 1<<30 {
387 // purge cache stats to prevent overflow
394 arena_start := mheap_.arena_start
395 arena_used := mheap_.arena_used
396 if uintptr(v) < arena_start || uintptr(v) >= arena_used {
399 p := uintptr(v) >> pageShift
400 q := p - arena_start>>pageShift
401 s = *(**mspan)(add(unsafe.Pointer(mheap_.spans), q*sys.PtrSize))
405 x = unsafe.Pointer(uintptr(s.start) << pageShift)
407 if uintptr(v) < uintptr(x) || uintptr(v) >= uintptr(unsafe.Pointer(s.limit)) || s.state != mSpanInUse {
414 if s.sizeclass != 0 {
415 x = add(x, (uintptr(v)-uintptr(x))/n*n)