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 // finblock is an array of finalizers to be executed. finblocks are
16 // arranged in a linked list for the finalizer queue.
18 // finblock is allocated from non-GC'd memory, so any heap pointers
19 // must be specially handled. GC currently assumes that the finalizer
20 // queue does not grow during marking (but it can shrink).
23 type finblock
struct {
28 fin
[(_FinBlockSize
- 2*sys
.PtrSize
- 2*4) / unsafe
.Sizeof(finalizer
{})]finalizer
31 var finlock mutex
// protects the following variables
32 var fing
*g
// goroutine that runs finalizers
33 var finq
*finblock
// list of finalizers that are to be executed
34 var finc
*finblock
// cache of free blocks
35 var finptrmask
[_FinBlockSize
/ sys
.PtrSize
/ 8]byte
38 var allfin
*finblock
// list of all blocks
40 // NOTE: Layout known to queuefinalizer.
41 type finalizer
struct {
42 fn
*funcval
// function to call (may be a heap pointer)
43 arg unsafe
.Pointer
// ptr to object (may be a heap pointer)
44 ft
*functype
// type of fn (unlikely, but may be a heap pointer)
45 ot
*ptrtype
// type of ptr to object (may be a heap pointer)
48 func queuefinalizer(p unsafe
.Pointer
, fn
*funcval
, ft
*functype
, ot
*ptrtype
) {
49 if gcphase
!= _GCoff
{
50 // Currently we assume that the finalizer queue won't
51 // grow during marking so we don't have to rescan it
52 // during mark termination. If we ever need to lift
53 // this assumption, we can do it by adding the
54 // necessary barriers to queuefinalizer (which it may
55 // have automatically).
56 throw("queuefinalizer during GC")
60 if finq
== nil || finq
.cnt
== uint32(len(finq
.fin
)) {
62 finc
= (*finblock
)(persistentalloc(_FinBlockSize
, 0, &memstats
.gc_sys
))
65 if finptrmask
[0] == 0 {
66 // Build pointer mask for Finalizer array in block.
67 // We allocate values of type finalizer in
68 // finblock values. Since these values are
69 // allocated by persistentalloc, they require
70 // special scanning during GC. finptrmask is a
71 // pointer mask to use while scanning.
72 // Since all the values in finalizer are
73 // pointers, just turn all bits on.
74 for i
:= range finptrmask
{
84 f
:= &finq
.fin
[finq
.cnt
]
85 atomic
.Xadd(&finq
.cnt
, +1) // Sync with markroots
95 func iterate_finq(callback
func(*funcval
, unsafe
.Pointer
, *functype
, *ptrtype
)) {
96 for fb
:= allfin
; fb
!= nil; fb
= fb
.alllink
{
97 for i
:= uint32(0); i
< fb
.cnt
; i
++ {
99 callback(f
.fn
, f
.arg
, f
.ft
, f
.ot
)
107 if fingwait
&& fingwake
{
121 // start the finalizer goroutine exactly once
122 if fingCreate
== 0 && atomic
.Cas(&fingCreate
, 0, 1) {
123 expectSystemGoroutine()
128 // This is the goroutine that runs all of the finalizers
145 goparkunlock(&finlock
, "finalizer wait", traceEvGoBlock
, 1)
150 for i
:= fb
.cnt
; i
> 0; i
-- {
154 throw("missing type in runfinq")
157 var param unsafe
.Pointer
158 switch fint
.kind
& kindMask
{
160 // direct use of pointer
161 param
= unsafe
.Pointer(&f
.arg
)
163 ityp
:= (*interfacetype
)(unsafe
.Pointer(fint
))
164 if len(ityp
.methods
) == 0 {
165 // set up with empty interface
168 param
= unsafe
.Pointer(&ef
)
170 // convert to interface with methods
171 // this conversion is guaranteed to succeed - we checked in SetFinalizer
172 ifac
.tab
= getitab(fint
, &f
.ot
.typ
, true)
174 param
= unsafe
.Pointer(&ifac
)
177 throw("bad kind in runfinq")
179 // This is not a system goroutine while
180 // running the actual finalizer.
181 // This matters because we want this
182 // goroutine to appear in a stack dump
183 // if the finalizer crashes.
184 // The gc toolchain handles this using
185 // a global variable fingRunning,
186 // but we don't need that.
187 gp
.isSystemGoroutine
= false
188 reflectcall(f
.ft
, f
.fn
, false, false, ¶m
, nil)
189 gp
.isSystemGoroutine
= true
191 // Drop finalizer queue heap references
192 // before hiding them from markroot.
193 // This also ensures these will be
194 // clear if we reuse the finalizer.
198 atomic
.Store(&fb
.cnt
, i
-1)
210 // SetFinalizer sets the finalizer associated with obj to the provided
211 // finalizer function. When the garbage collector finds an unreachable block
212 // with an associated finalizer, it clears the association and runs
213 // finalizer(obj) in a separate goroutine. This makes obj reachable again,
214 // but now without an associated finalizer. Assuming that SetFinalizer
215 // is not called again, the next time the garbage collector sees
216 // that obj is unreachable, it will free obj.
218 // SetFinalizer(obj, nil) clears any finalizer associated with obj.
220 // The argument obj must be a pointer to an object allocated by calling
221 // new, by taking the address of a composite literal, or by taking the
222 // address of a local variable.
223 // The argument finalizer must be a function that takes a single argument
224 // to which obj's type can be assigned, and can have arbitrary ignored return
225 // values. If either of these is not true, SetFinalizer may abort the
228 // Finalizers are run in dependency order: if A points at B, both have
229 // finalizers, and they are otherwise unreachable, only the finalizer
230 // for A runs; once A is freed, the finalizer for B can run.
231 // If a cyclic structure includes a block with a finalizer, that
232 // cycle is not guaranteed to be garbage collected and the finalizer
233 // is not guaranteed to run, because there is no ordering that
234 // respects the dependencies.
236 // The finalizer for obj is scheduled to run at some arbitrary time after
237 // obj becomes unreachable.
238 // There is no guarantee that finalizers will run before a program exits,
239 // so typically they are useful only for releasing non-memory resources
240 // associated with an object during a long-running program.
241 // For example, an os.File object could use a finalizer to close the
242 // associated operating system file descriptor when a program discards
243 // an os.File without calling Close, but it would be a mistake
244 // to depend on a finalizer to flush an in-memory I/O buffer such as a
245 // bufio.Writer, because the buffer would not be flushed at program exit.
247 // It is not guaranteed that a finalizer will run if the size of *obj is
250 // It is not guaranteed that a finalizer will run for objects allocated
251 // in initializers for package-level variables. Such objects may be
252 // linker-allocated, not heap-allocated.
254 // A finalizer may run as soon as an object becomes unreachable.
255 // In order to use finalizers correctly, the program must ensure that
256 // the object is reachable until it is no longer required.
257 // Objects stored in global variables, or that can be found by tracing
258 // pointers from a global variable, are reachable. For other objects,
259 // pass the object to a call of the KeepAlive function to mark the
260 // last point in the function where the object must be reachable.
262 // For example, if p points to a struct that contains a file descriptor d,
263 // and p has a finalizer that closes that file descriptor, and if the last
264 // use of p in a function is a call to syscall.Write(p.d, buf, size), then
265 // p may be unreachable as soon as the program enters syscall.Write. The
266 // finalizer may run at that moment, closing p.d, causing syscall.Write
267 // to fail because it is writing to a closed file descriptor (or, worse,
268 // to an entirely different file descriptor opened by a different goroutine).
269 // To avoid this problem, call runtime.KeepAlive(p) after the call to
272 // A single goroutine runs all finalizers for a program, sequentially.
273 // If a finalizer must run for a long time, it should do so by starting
275 func SetFinalizer(obj
interface{}, finalizer
interface{}) {
277 // debug.sbrk never frees memory, so no finalizers run
278 // (and we don't have the data structures to record them).
284 throw("runtime.SetFinalizer: first argument is nil")
286 if etyp
.kind
&kindMask
!= kindPtr
{
287 throw("runtime.SetFinalizer: first argument is " + *etyp
.string + ", not pointer")
289 ot
:= (*ptrtype
)(unsafe
.Pointer(etyp
))
291 throw("nil elem type!")
294 // find the containing object
295 _
, base
, _
:= findObject(e
.data
)
298 // 0-length objects are okay.
299 if e
.data
== unsafe
.Pointer(&zerobase
) {
303 // Global initializers might be linker-allocated.
304 // var Foo = &Object{}
306 // runtime.SetFinalizer(Foo, nil)
308 // The relevant segments are: noptrdata, data, bss, noptrbss.
309 // We cannot assume they are in any order or even contiguous,
310 // due to external linking.
312 // For gccgo we have no reliable way to detect them,
313 // so we just return.
318 // As an implementation detail we allow to set finalizers for an inner byte
319 // of an object if it could come from tiny alloc (see mallocgc for details).
320 if ot
.elem
== nil || ot
.elem
.kind
&kindNoPointers
== 0 || ot
.elem
.size
>= maxTinySize
{
321 throw("runtime.SetFinalizer: pointer not at beginning of allocated block")
325 f
:= efaceOf(&finalizer
)
328 // switch to system stack and remove finalizer
330 removefinalizer(e
.data
)
335 if ftyp
.kind
&kindMask
!= kindFunc
{
336 throw("runtime.SetFinalizer: second argument is " + *ftyp
.string + ", not a function")
338 ft
:= (*functype
)(unsafe
.Pointer(ftyp
))
340 throw("runtime.SetFinalizer: cannot pass " + *etyp
.string + " to finalizer " + *ftyp
.string + " because dotdotdot")
343 throw("runtime.SetFinalizer: cannot pass " + *etyp
.string + " to finalizer " + *ftyp
.string)
350 case fint
.kind
&kindMask
== kindPtr
:
351 if (fint
.uncommontype
== nil || etyp
.uncommontype
== nil) && (*ptrtype
)(unsafe
.Pointer(fint
)).elem
== ot
.elem
{
352 // ok - not same type, but both pointers,
353 // one or the other is unnamed, and same element type, so assignable.
356 case fint
.kind
&kindMask
== kindInterface
:
357 ityp
:= (*interfacetype
)(unsafe
.Pointer(fint
))
358 if len(ityp
.methods
) == 0 {
359 // ok - satisfies empty interface
362 if getitab(fint
, etyp
, true) == nil {
366 throw("runtime.SetFinalizer: cannot pass " + *etyp
.string + " to finalizer " + *ftyp
.string)
368 // make sure we have a finalizer goroutine
373 if !isDirectIface(ftyp
) {
374 data
= *(*unsafe
.Pointer
)(data
)
376 if !addfinalizer(e
.data
, (*funcval
)(data
), ft
, ot
) {
377 throw("runtime.SetFinalizer: finalizer already set")
382 // Look up pointer v in heap. Return the span containing the object,
383 // the start of the object, and the size of the object. If the object
384 // does not exist, return nil, nil, 0.
385 func findObject(v unsafe
.Pointer
) (s
*mspan
, x unsafe
.Pointer
, n
uintptr) {
388 if sys
.PtrSize
== 4 && c
.local_nlookup
>= 1<<30 {
389 // purge cache stats to prevent overflow
396 arena_start
:= mheap_
.arena_start
397 arena_used
:= mheap_
.arena_used
398 if uintptr(v
) < arena_start ||
uintptr(v
) >= arena_used
{
401 p
:= uintptr(v
) >> pageShift
402 q
:= p
- arena_start
>>pageShift
407 x
= unsafe
.Pointer(s
.base())
409 if uintptr(v
) < uintptr(x
) ||
uintptr(v
) >= uintptr(unsafe
.Pointer(s
.limit
)) || s
.state
!= mSpanInUse
{
416 if s
.spanclass
.sizeclass() != 0 {
417 x
= add(x
, (uintptr(v
)-uintptr(x
))/n
*n
)
422 // Mark KeepAlive as noinline so that the current compiler will ensure
423 // that the argument is alive at the point of the function call.
424 // If it were inlined, it would disappear, and there would be nothing
425 // keeping the argument alive. Perhaps a future compiler will recognize
426 // runtime.KeepAlive specially and do something more efficient.
429 // KeepAlive marks its argument as currently reachable.
430 // This ensures that the object is not freed, and its finalizer is not run,
431 // before the point in the program where KeepAlive is called.
433 // A very simplified example showing where KeepAlive is required:
434 // type File struct { d int }
435 // d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
436 // // ... do something if err != nil ...
438 // runtime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })
440 // n, err := syscall.Read(p.d, buf[:])
441 // // Ensure p is not finalized until Read returns.
442 // runtime.KeepAlive(p)
443 // // No more uses of p after this point.
445 // Without the KeepAlive call, the finalizer could run at the start of
446 // syscall.Read, closing the file descriptor before syscall.Read makes
447 // the actual system call.
448 func KeepAlive(interface{}) {}