runtime: scan register backing store on ia64
[official-gcc.git] / libgo / go / runtime / mfinal.go
blob19573d8b8d3eabb2468deeaf07f0597d36e59d17
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.
7 package runtime
9 import (
10 "runtime/internal/atomic"
11 "runtime/internal/sys"
12 "unsafe"
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).
22 //go:notinheap
23 type finblock struct {
24 alllink *finblock
25 next *finblock
26 cnt uint32
27 _ int32
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
36 var fingwait bool
37 var fingwake bool
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")
59 lock(&finlock)
60 if finq == nil || finq.cnt == uint32(len(finq.fin)) {
61 if finc == nil {
62 finc = (*finblock)(persistentalloc(_FinBlockSize, 0, &memstats.gc_sys))
63 finc.alllink = allfin
64 allfin = finc
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 {
75 finptrmask[i] = 0xff
79 block := finc
80 finc = block.next
81 block.next = finq
82 finq = block
84 f := &finq.fin[finq.cnt]
85 atomic.Xadd(&finq.cnt, +1) // Sync with markroots
86 f.fn = fn
87 f.ft = ft
88 f.ot = ot
89 f.arg = p
90 fingwake = true
91 unlock(&finlock)
94 //go:nowritebarrier
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++ {
98 f := &fb.fin[i]
99 callback(f.fn, f.arg, f.ft, f.ot)
104 func wakefing() *g {
105 var res *g
106 lock(&finlock)
107 if fingwait && fingwake {
108 fingwait = false
109 fingwake = false
110 res = fing
112 unlock(&finlock)
113 return res
116 var (
117 fingCreate uint32
120 func createfing() {
121 // start the finalizer goroutine exactly once
122 if fingCreate == 0 && atomic.Cas(&fingCreate, 0, 1) {
123 expectSystemGoroutine()
124 go runfinq()
128 // This is the goroutine that runs all of the finalizers
129 func runfinq() {
130 setSystemGoroutine()
132 var (
133 ef eface
134 ifac iface
137 gp := getg()
138 for {
139 lock(&finlock)
140 fb := finq
141 finq = nil
142 if fb == nil {
143 fing = gp
144 fingwait = true
145 goparkunlock(&finlock, "finalizer wait", traceEvGoBlock, 1)
146 continue
148 unlock(&finlock)
149 for fb != nil {
150 for i := fb.cnt; i > 0; i-- {
151 f := &fb.fin[i-1]
153 if f.ft == nil {
154 throw("missing type in runfinq")
156 fint := f.ft.in[0]
157 var param unsafe.Pointer
158 switch fint.kind & kindMask {
159 case kindPtr:
160 // direct use of pointer
161 param = unsafe.Pointer(&f.arg)
162 case kindInterface:
163 ityp := (*interfacetype)(unsafe.Pointer(fint))
164 if len(ityp.methods) == 0 {
165 // set up with empty interface
166 ef._type = &f.ot.typ
167 ef.data = f.arg
168 param = unsafe.Pointer(&ef)
169 } else {
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)
173 ifac.data = f.arg
174 param = unsafe.Pointer(&ifac)
176 default:
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, &param, 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.
195 f.fn = nil
196 f.arg = nil
197 f.ot = nil
198 atomic.Store(&fb.cnt, i-1)
200 next := fb.next
201 lock(&finlock)
202 fb.next = finc
203 finc = fb
204 unlock(&finlock)
205 fb = next
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
226 // program.
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
248 // zero bytes.
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
270 // syscall.Write.
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
274 // a new goroutine.
275 func SetFinalizer(obj interface{}, finalizer interface{}) {
276 if debug.sbrk != 0 {
277 // debug.sbrk never frees memory, so no finalizers run
278 // (and we don't have the data structures to record them).
279 return
281 e := efaceOf(&obj)
282 etyp := e._type
283 if etyp == nil {
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))
290 if ot.elem == nil {
291 throw("nil elem type!")
294 // find the containing object
295 _, base, _ := findObject(e.data)
297 if base == nil {
298 // 0-length objects are okay.
299 if e.data == unsafe.Pointer(&zerobase) {
300 return
303 // Global initializers might be linker-allocated.
304 // var Foo = &Object{}
305 // func main() {
306 // runtime.SetFinalizer(Foo, nil)
307 // }
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.
314 return
317 if e.data != base {
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)
326 ftyp := f._type
327 if ftyp == nil {
328 // switch to system stack and remove finalizer
329 systemstack(func() {
330 removefinalizer(e.data)
332 return
335 if ftyp.kind&kindMask != kindFunc {
336 throw("runtime.SetFinalizer: second argument is " + *ftyp.string + ", not a function")
338 ft := (*functype)(unsafe.Pointer(ftyp))
339 if ft.dotdotdot {
340 throw("runtime.SetFinalizer: cannot pass " + *etyp.string + " to finalizer " + *ftyp.string + " because dotdotdot")
342 if len(ft.in) != 1 {
343 throw("runtime.SetFinalizer: cannot pass " + *etyp.string + " to finalizer " + *ftyp.string)
345 fint := ft.in[0]
346 switch {
347 case fint == etyp:
348 // ok - same type
349 goto okarg
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.
354 goto okarg
356 case fint.kind&kindMask == kindInterface:
357 ityp := (*interfacetype)(unsafe.Pointer(fint))
358 if len(ityp.methods) == 0 {
359 // ok - satisfies empty interface
360 goto okarg
362 if getitab(fint, etyp, true) == nil {
363 goto okarg
366 throw("runtime.SetFinalizer: cannot pass " + *etyp.string + " to finalizer " + *ftyp.string)
367 okarg:
368 // make sure we have a finalizer goroutine
369 createfing()
371 systemstack(func() {
372 data := f.data
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) {
386 c := gomcache()
387 c.local_nlookup++
388 if sys.PtrSize == 4 && c.local_nlookup >= 1<<30 {
389 // purge cache stats to prevent overflow
390 lock(&mheap_.lock)
391 purgecachedstats(c)
392 unlock(&mheap_.lock)
395 // find span
396 arena_start := mheap_.arena_start
397 arena_used := mheap_.arena_used
398 if uintptr(v) < arena_start || uintptr(v) >= arena_used {
399 return
401 p := uintptr(v) >> pageShift
402 q := p - arena_start>>pageShift
403 s = mheap_.spans[q]
404 if s == nil {
405 return
407 x = unsafe.Pointer(s.base())
409 if uintptr(v) < uintptr(x) || uintptr(v) >= uintptr(unsafe.Pointer(s.limit)) || s.state != mSpanInUse {
410 s = nil
411 x = nil
412 return
415 n = s.elemsize
416 if s.spanclass.sizeclass() != 0 {
417 x = add(x, (uintptr(v)-uintptr(x))/n*n)
419 return
422 // Mark KeepAlive as noinline so that it is easily detectable as an intrinsic.
423 //go:noinline
425 // KeepAlive marks its argument as currently reachable.
426 // This ensures that the object is not freed, and its finalizer is not run,
427 // before the point in the program where KeepAlive is called.
429 // A very simplified example showing where KeepAlive is required:
430 // type File struct { d int }
431 // d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
432 // // ... do something if err != nil ...
433 // p := &File{d}
434 // runtime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })
435 // var buf [10]byte
436 // n, err := syscall.Read(p.d, buf[:])
437 // // Ensure p is not finalized until Read returns.
438 // runtime.KeepAlive(p)
439 // // No more uses of p after this point.
441 // Without the KeepAlive call, the finalizer could run at the start of
442 // syscall.Read, closing the file descriptor before syscall.Read makes
443 // the actual system call.
444 func KeepAlive(x interface{}) {
445 // Introduce a use of x that the compiler can't eliminate.
446 // This makes sure x is alive on entry. We need x to be alive
447 // on entry for "defer runtime.KeepAlive(x)"; see issue 21402.
448 if cgoAlwaysFalse {
449 println(x)