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