]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mfinal.go
[dev.unified] all: merge master (85d87b9) into dev.unified
[gostls13.git] / src / runtime / mfinal.go
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.
4
5 // Garbage collector: finalizers and block profiling.
6
7 package runtime
8
9 import (
10         "internal/abi"
11         "internal/goarch"
12         "runtime/internal/atomic"
13         "unsafe"
14 )
15
16 // finblock is an array of finalizers to be executed. finblocks are
17 // arranged in a linked list for the finalizer queue.
18 //
19 // finblock is allocated from non-GC'd memory, so any heap pointers
20 // must be specially handled. GC currently assumes that the finalizer
21 // queue does not grow during marking (but it can shrink).
22 //
23 //go:notinheap
24 type finblock struct {
25         alllink *finblock
26         next    *finblock
27         cnt     uint32
28         _       int32
29         fin     [(_FinBlockSize - 2*goarch.PtrSize - 2*4) / unsafe.Sizeof(finalizer{})]finalizer
30 }
31
32 var finlock mutex  // protects the following variables
33 var fing *g        // goroutine that runs finalizers
34 var finq *finblock // list of finalizers that are to be executed
35 var finc *finblock // cache of free blocks
36 var finptrmask [_FinBlockSize / goarch.PtrSize / 8]byte
37 var fingwait bool
38 var fingwake bool
39 var allfin *finblock // list of all blocks
40
41 // NOTE: Layout known to queuefinalizer.
42 type finalizer struct {
43         fn   *funcval       // function to call (may be a heap pointer)
44         arg  unsafe.Pointer // ptr to object (may be a heap pointer)
45         nret uintptr        // bytes of return values from fn
46         fint *_type         // type of first argument of fn
47         ot   *ptrtype       // type of ptr to object (may be a heap pointer)
48 }
49
50 var finalizer1 = [...]byte{
51         // Each Finalizer is 5 words, ptr ptr INT ptr ptr (INT = uintptr here)
52         // Each byte describes 8 words.
53         // Need 8 Finalizers described by 5 bytes before pattern repeats:
54         //      ptr ptr INT ptr ptr
55         //      ptr ptr INT ptr ptr
56         //      ptr ptr INT ptr ptr
57         //      ptr ptr INT ptr ptr
58         //      ptr ptr INT ptr ptr
59         //      ptr ptr INT ptr ptr
60         //      ptr ptr INT ptr ptr
61         //      ptr ptr INT ptr ptr
62         // aka
63         //
64         //      ptr ptr INT ptr ptr ptr ptr INT
65         //      ptr ptr ptr ptr INT ptr ptr ptr
66         //      ptr INT ptr ptr ptr ptr INT ptr
67         //      ptr ptr ptr INT ptr ptr ptr ptr
68         //      INT ptr ptr ptr ptr INT ptr ptr
69         //
70         // Assumptions about Finalizer layout checked below.
71         1<<0 | 1<<1 | 0<<2 | 1<<3 | 1<<4 | 1<<5 | 1<<6 | 0<<7,
72         1<<0 | 1<<1 | 1<<2 | 1<<3 | 0<<4 | 1<<5 | 1<<6 | 1<<7,
73         1<<0 | 0<<1 | 1<<2 | 1<<3 | 1<<4 | 1<<5 | 0<<6 | 1<<7,
74         1<<0 | 1<<1 | 1<<2 | 0<<3 | 1<<4 | 1<<5 | 1<<6 | 1<<7,
75         0<<0 | 1<<1 | 1<<2 | 1<<3 | 1<<4 | 0<<5 | 1<<6 | 1<<7,
76 }
77
78 // lockRankMayQueueFinalizer records the lock ranking effects of a
79 // function that may call queuefinalizer.
80 func lockRankMayQueueFinalizer() {
81         lockWithRankMayAcquire(&finlock, getLockRank(&finlock))
82 }
83
84 func queuefinalizer(p unsafe.Pointer, fn *funcval, nret uintptr, fint *_type, ot *ptrtype) {
85         if gcphase != _GCoff {
86                 // Currently we assume that the finalizer queue won't
87                 // grow during marking so we don't have to rescan it
88                 // during mark termination. If we ever need to lift
89                 // this assumption, we can do it by adding the
90                 // necessary barriers to queuefinalizer (which it may
91                 // have automatically).
92                 throw("queuefinalizer during GC")
93         }
94
95         lock(&finlock)
96         if finq == nil || finq.cnt == uint32(len(finq.fin)) {
97                 if finc == nil {
98                         finc = (*finblock)(persistentalloc(_FinBlockSize, 0, &memstats.gcMiscSys))
99                         finc.alllink = allfin
100                         allfin = finc
101                         if finptrmask[0] == 0 {
102                                 // Build pointer mask for Finalizer array in block.
103                                 // Check assumptions made in finalizer1 array above.
104                                 if (unsafe.Sizeof(finalizer{}) != 5*goarch.PtrSize ||
105                                         unsafe.Offsetof(finalizer{}.fn) != 0 ||
106                                         unsafe.Offsetof(finalizer{}.arg) != goarch.PtrSize ||
107                                         unsafe.Offsetof(finalizer{}.nret) != 2*goarch.PtrSize ||
108                                         unsafe.Offsetof(finalizer{}.fint) != 3*goarch.PtrSize ||
109                                         unsafe.Offsetof(finalizer{}.ot) != 4*goarch.PtrSize) {
110                                         throw("finalizer out of sync")
111                                 }
112                                 for i := range finptrmask {
113                                         finptrmask[i] = finalizer1[i%len(finalizer1)]
114                                 }
115                         }
116                 }
117                 block := finc
118                 finc = block.next
119                 block.next = finq
120                 finq = block
121         }
122         f := &finq.fin[finq.cnt]
123         atomic.Xadd(&finq.cnt, +1) // Sync with markroots
124         f.fn = fn
125         f.nret = nret
126         f.fint = fint
127         f.ot = ot
128         f.arg = p
129         fingwake = true
130         unlock(&finlock)
131 }
132
133 //go:nowritebarrier
134 func iterate_finq(callback func(*funcval, unsafe.Pointer, uintptr, *_type, *ptrtype)) {
135         for fb := allfin; fb != nil; fb = fb.alllink {
136                 for i := uint32(0); i < fb.cnt; i++ {
137                         f := &fb.fin[i]
138                         callback(f.fn, f.arg, f.nret, f.fint, f.ot)
139                 }
140         }
141 }
142
143 func wakefing() *g {
144         var res *g
145         lock(&finlock)
146         if fingwait && fingwake {
147                 fingwait = false
148                 fingwake = false
149                 res = fing
150         }
151         unlock(&finlock)
152         return res
153 }
154
155 var (
156         fingCreate  uint32
157         fingRunning bool
158 )
159
160 func createfing() {
161         // start the finalizer goroutine exactly once
162         if fingCreate == 0 && atomic.Cas(&fingCreate, 0, 1) {
163                 go runfinq()
164         }
165 }
166
167 // This is the goroutine that runs all of the finalizers
168 func runfinq() {
169         var (
170                 frame    unsafe.Pointer
171                 framecap uintptr
172                 argRegs  int
173         )
174
175         gp := getg()
176         lock(&finlock)
177         fing = gp
178         unlock(&finlock)
179
180         for {
181                 lock(&finlock)
182                 fb := finq
183                 finq = nil
184                 if fb == nil {
185                         fingwait = true
186                         goparkunlock(&finlock, waitReasonFinalizerWait, traceEvGoBlock, 1)
187                         continue
188                 }
189                 argRegs = intArgRegs
190                 unlock(&finlock)
191                 if raceenabled {
192                         racefingo()
193                 }
194                 for fb != nil {
195                         for i := fb.cnt; i > 0; i-- {
196                                 f := &fb.fin[i-1]
197
198                                 var regs abi.RegArgs
199                                 // The args may be passed in registers or on stack. Even for
200                                 // the register case, we still need the spill slots.
201                                 // TODO: revisit if we remove spill slots.
202                                 //
203                                 // Unfortunately because we can have an arbitrary
204                                 // amount of returns and it would be complex to try and
205                                 // figure out how many of those can get passed in registers,
206                                 // just conservatively assume none of them do.
207                                 framesz := unsafe.Sizeof((any)(nil)) + f.nret
208                                 if framecap < framesz {
209                                         // The frame does not contain pointers interesting for GC,
210                                         // all not yet finalized objects are stored in finq.
211                                         // If we do not mark it as FlagNoScan,
212                                         // the last finalized object is not collected.
213                                         frame = mallocgc(framesz, nil, true)
214                                         framecap = framesz
215                                 }
216
217                                 if f.fint == nil {
218                                         throw("missing type in runfinq")
219                                 }
220                                 r := frame
221                                 if argRegs > 0 {
222                                         r = unsafe.Pointer(&regs.Ints)
223                                 } else {
224                                         // frame is effectively uninitialized
225                                         // memory. That means we have to clear
226                                         // it before writing to it to avoid
227                                         // confusing the write barrier.
228                                         *(*[2]uintptr)(frame) = [2]uintptr{}
229                                 }
230                                 switch f.fint.kind & kindMask {
231                                 case kindPtr:
232                                         // direct use of pointer
233                                         *(*unsafe.Pointer)(r) = f.arg
234                                 case kindInterface:
235                                         ityp := (*interfacetype)(unsafe.Pointer(f.fint))
236                                         // set up with empty interface
237                                         (*eface)(r)._type = &f.ot.typ
238                                         (*eface)(r).data = f.arg
239                                         if len(ityp.mhdr) != 0 {
240                                                 // convert to interface with methods
241                                                 // this conversion is guaranteed to succeed - we checked in SetFinalizer
242                                                 (*iface)(r).tab = assertE2I(ityp, (*eface)(r)._type)
243                                         }
244                                 default:
245                                         throw("bad kind in runfinq")
246                                 }
247                                 fingRunning = true
248                                 reflectcall(nil, unsafe.Pointer(f.fn), frame, uint32(framesz), uint32(framesz), uint32(framesz), &regs)
249                                 fingRunning = false
250
251                                 // Drop finalizer queue heap references
252                                 // before hiding them from markroot.
253                                 // This also ensures these will be
254                                 // clear if we reuse the finalizer.
255                                 f.fn = nil
256                                 f.arg = nil
257                                 f.ot = nil
258                                 atomic.Store(&fb.cnt, i-1)
259                         }
260                         next := fb.next
261                         lock(&finlock)
262                         fb.next = finc
263                         finc = fb
264                         unlock(&finlock)
265                         fb = next
266                 }
267         }
268 }
269
270 // SetFinalizer sets the finalizer associated with obj to the provided
271 // finalizer function. When the garbage collector finds an unreachable block
272 // with an associated finalizer, it clears the association and runs
273 // finalizer(obj) in a separate goroutine. This makes obj reachable again,
274 // but now without an associated finalizer. Assuming that SetFinalizer
275 // is not called again, the next time the garbage collector sees
276 // that obj is unreachable, it will free obj.
277 //
278 // SetFinalizer(obj, nil) clears any finalizer associated with obj.
279 //
280 // The argument obj must be a pointer to an object allocated by calling
281 // new, by taking the address of a composite literal, or by taking the
282 // address of a local variable.
283 // The argument finalizer must be a function that takes a single argument
284 // to which obj's type can be assigned, and can have arbitrary ignored return
285 // values. If either of these is not true, SetFinalizer may abort the
286 // program.
287 //
288 // Finalizers are run in dependency order: if A points at B, both have
289 // finalizers, and they are otherwise unreachable, only the finalizer
290 // for A runs; once A is freed, the finalizer for B can run.
291 // If a cyclic structure includes a block with a finalizer, that
292 // cycle is not guaranteed to be garbage collected and the finalizer
293 // is not guaranteed to run, because there is no ordering that
294 // respects the dependencies.
295 //
296 // The finalizer is scheduled to run at some arbitrary time after the
297 // program can no longer reach the object to which obj points.
298 // There is no guarantee that finalizers will run before a program exits,
299 // so typically they are useful only for releasing non-memory resources
300 // associated with an object during a long-running program.
301 // For example, an os.File object could use a finalizer to close the
302 // associated operating system file descriptor when a program discards
303 // an os.File without calling Close, but it would be a mistake
304 // to depend on a finalizer to flush an in-memory I/O buffer such as a
305 // bufio.Writer, because the buffer would not be flushed at program exit.
306 //
307 // It is not guaranteed that a finalizer will run if the size of *obj is
308 // zero bytes.
309 //
310 // It is not guaranteed that a finalizer will run for objects allocated
311 // in initializers for package-level variables. Such objects may be
312 // linker-allocated, not heap-allocated.
313 //
314 // A finalizer may run as soon as an object becomes unreachable.
315 // In order to use finalizers correctly, the program must ensure that
316 // the object is reachable until it is no longer required.
317 // Objects stored in global variables, or that can be found by tracing
318 // pointers from a global variable, are reachable. For other objects,
319 // pass the object to a call of the KeepAlive function to mark the
320 // last point in the function where the object must be reachable.
321 //
322 // For example, if p points to a struct, such as os.File, that contains
323 // a file descriptor d, and p has a finalizer that closes that file
324 // descriptor, and if the last use of p in a function is a call to
325 // syscall.Write(p.d, buf, size), then p may be unreachable as soon as
326 // the program enters syscall.Write. The finalizer may run at that moment,
327 // closing p.d, causing syscall.Write to fail because it is writing to
328 // a closed file descriptor (or, worse, to an entirely different
329 // file descriptor opened by a different goroutine). To avoid this problem,
330 // call KeepAlive(p) after the call to syscall.Write.
331 //
332 // A single goroutine runs all finalizers for a program, sequentially.
333 // If a finalizer must run for a long time, it should do so by starting
334 // a new goroutine.
335 //
336 // In the terminology of the Go memory model, a call
337 // SetFinalizer(x, f) “synchronizes before” the finalization call f(x).
338 // However, there is no guarantee that KeepAlive(x) or any other use of x
339 // “synchronizes before” f(x), so in general a finalizer should use a mutex
340 // or other synchronization mechanism if it needs to access mutable state in x.
341 // For example, consider a finalizer that inspects a mutable field in x
342 // that is modified from time to time in the main program before x
343 // becomes unreachable and the finalizer is invoked.
344 // The modifications in the main program and the inspection in the finalizer
345 // need to use appropriate synchronization, such as mutexes or atomic updates,
346 // to avoid read-write races.
347 func SetFinalizer(obj any, finalizer any) {
348         if debug.sbrk != 0 {
349                 // debug.sbrk never frees memory, so no finalizers run
350                 // (and we don't have the data structures to record them).
351                 return
352         }
353         e := efaceOf(&obj)
354         etyp := e._type
355         if etyp == nil {
356                 throw("runtime.SetFinalizer: first argument is nil")
357         }
358         if etyp.kind&kindMask != kindPtr {
359                 throw("runtime.SetFinalizer: first argument is " + etyp.string() + ", not pointer")
360         }
361         ot := (*ptrtype)(unsafe.Pointer(etyp))
362         if ot.elem == nil {
363                 throw("nil elem type!")
364         }
365
366         // find the containing object
367         base, _, _ := findObject(uintptr(e.data), 0, 0)
368
369         if base == 0 {
370                 // 0-length objects are okay.
371                 if e.data == unsafe.Pointer(&zerobase) {
372                         return
373                 }
374
375                 // Global initializers might be linker-allocated.
376                 //      var Foo = &Object{}
377                 //      func main() {
378                 //              runtime.SetFinalizer(Foo, nil)
379                 //      }
380                 // The relevant segments are: noptrdata, data, bss, noptrbss.
381                 // We cannot assume they are in any order or even contiguous,
382                 // due to external linking.
383                 for datap := &firstmoduledata; datap != nil; datap = datap.next {
384                         if datap.noptrdata <= uintptr(e.data) && uintptr(e.data) < datap.enoptrdata ||
385                                 datap.data <= uintptr(e.data) && uintptr(e.data) < datap.edata ||
386                                 datap.bss <= uintptr(e.data) && uintptr(e.data) < datap.ebss ||
387                                 datap.noptrbss <= uintptr(e.data) && uintptr(e.data) < datap.enoptrbss {
388                                 return
389                         }
390                 }
391                 throw("runtime.SetFinalizer: pointer not in allocated block")
392         }
393
394         if uintptr(e.data) != base {
395                 // As an implementation detail we allow to set finalizers for an inner byte
396                 // of an object if it could come from tiny alloc (see mallocgc for details).
397                 if ot.elem == nil || ot.elem.ptrdata != 0 || ot.elem.size >= maxTinySize {
398                         throw("runtime.SetFinalizer: pointer not at beginning of allocated block")
399                 }
400         }
401
402         f := efaceOf(&finalizer)
403         ftyp := f._type
404         if ftyp == nil {
405                 // switch to system stack and remove finalizer
406                 systemstack(func() {
407                         removefinalizer(e.data)
408                 })
409                 return
410         }
411
412         if ftyp.kind&kindMask != kindFunc {
413                 throw("runtime.SetFinalizer: second argument is " + ftyp.string() + ", not a function")
414         }
415         ft := (*functype)(unsafe.Pointer(ftyp))
416         if ft.dotdotdot() {
417                 throw("runtime.SetFinalizer: cannot pass " + etyp.string() + " to finalizer " + ftyp.string() + " because dotdotdot")
418         }
419         if ft.inCount != 1 {
420                 throw("runtime.SetFinalizer: cannot pass " + etyp.string() + " to finalizer " + ftyp.string())
421         }
422         fint := ft.in()[0]
423         switch {
424         case fint == etyp:
425                 // ok - same type
426                 goto okarg
427         case fint.kind&kindMask == kindPtr:
428                 if (fint.uncommon() == nil || etyp.uncommon() == nil) && (*ptrtype)(unsafe.Pointer(fint)).elem == ot.elem {
429                         // ok - not same type, but both pointers,
430                         // one or the other is unnamed, and same element type, so assignable.
431                         goto okarg
432                 }
433         case fint.kind&kindMask == kindInterface:
434                 ityp := (*interfacetype)(unsafe.Pointer(fint))
435                 if len(ityp.mhdr) == 0 {
436                         // ok - satisfies empty interface
437                         goto okarg
438                 }
439                 if iface := assertE2I2(ityp, *efaceOf(&obj)); iface.tab != nil {
440                         goto okarg
441                 }
442         }
443         throw("runtime.SetFinalizer: cannot pass " + etyp.string() + " to finalizer " + ftyp.string())
444 okarg:
445         // compute size needed for return parameters
446         nret := uintptr(0)
447         for _, t := range ft.out() {
448                 nret = alignUp(nret, uintptr(t.align)) + uintptr(t.size)
449         }
450         nret = alignUp(nret, goarch.PtrSize)
451
452         // make sure we have a finalizer goroutine
453         createfing()
454
455         systemstack(func() {
456                 if !addfinalizer(e.data, (*funcval)(f.data), nret, fint, ot) {
457                         throw("runtime.SetFinalizer: finalizer already set")
458                 }
459         })
460 }
461
462 // Mark KeepAlive as noinline so that it is easily detectable as an intrinsic.
463 //
464 //go:noinline
465
466 // KeepAlive marks its argument as currently reachable.
467 // This ensures that the object is not freed, and its finalizer is not run,
468 // before the point in the program where KeepAlive is called.
469 //
470 // A very simplified example showing where KeepAlive is required:
471 //
472 //      type File struct { d int }
473 //      d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
474 //      // ... do something if err != nil ...
475 //      p := &File{d}
476 //      runtime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })
477 //      var buf [10]byte
478 //      n, err := syscall.Read(p.d, buf[:])
479 //      // Ensure p is not finalized until Read returns.
480 //      runtime.KeepAlive(p)
481 //      // No more uses of p after this point.
482 //
483 // Without the KeepAlive call, the finalizer could run at the start of
484 // syscall.Read, closing the file descriptor before syscall.Read makes
485 // the actual system call.
486 //
487 // Note: KeepAlive should only be used to prevent finalizers from
488 // running prematurely. In particular, when used with unsafe.Pointer,
489 // the rules for valid uses of unsafe.Pointer still apply.
490 func KeepAlive(x any) {
491         // Introduce a use of x that the compiler can't eliminate.
492         // This makes sure x is alive on entry. We need x to be alive
493         // on entry for "defer runtime.KeepAlive(x)"; see issue 21402.
494         if cgoAlwaysFalse {
495                 println(x)
496         }
497 }