Debian Codegraph @

libgo/go/internal/intern/intern.go

raw
1 // Copyright 2020 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 // Package intern lets you make smaller comparable values by boxing
6 // a larger comparable value (such as a 16 byte string header) down
7 // into a globally unique 8 byte pointer.
8 //
9 // The globally unique pointers are garbage collected with weak
10 // references and finalizers. This package hides that.
11 package intern
12
13 import (
14 "internal/godebug"
15 "runtime"
16 "sync"
17 "unsafe"
18 )
19
20 // A Value pointer is the handle to an underlying comparable value.
21 // See func Get for how Value pointers may be used.
22 type Value struct {
23 _ [0]func() // prevent people from accidentally using value type as comparable
24 cmpVal any
25 // resurrected is guarded by mu (for all instances of Value).
26 // It is set true whenever v is synthesized from a uintptr.
27 resurrected bool
28 }
29
30 // Get returns the comparable value passed to the Get func
31 // that returned v.
32 func (v *Value) Get() any { return v.cmpVal }
33
34 // key is a key in our global value map.
35 // It contains type-specialized fields to avoid allocations
36 // when converting common types to empty interfaces.
37 type key struct {
38 s string
39 cmpVal any
40 // isString reports whether key contains a string.
41 // Without it, the zero value of key is ambiguous.
42 isString bool
43 }
44
45 // keyFor returns a key to use with cmpVal.
46 func keyFor(cmpVal any) key {
47 if s, ok := cmpVal.(string); ok {
48 return key{s: s, isString: true}
49 }
50 return key{cmpVal: cmpVal}
51 }
52
53 // Value returns a *Value built from k.
54 func (k key) Value() *Value {
55 if k.isString {
56 return &Value{cmpVal: k.s}
57 }
58 return &Value{cmpVal: k.cmpVal}
59 }
60
61 var (
62 // mu guards valMap, a weakref map of *Value by underlying value.
63 // It also guards the resurrected field of all *Values.
64 mu sync.Mutex
65 valMap = map[key]uintptr{} // to uintptr(*Value)
66 valSafe = safeMap() // non-nil in safe+leaky mode
67 )
68
69 // safeMap returns a non-nil map if we're in safe-but-leaky mode,
70 // as controlled by GODEBUG=intern=leaky
71 func safeMap() map[key]*Value {
72 if godebug.Get("intern") == "leaky" {
73 return map[key]*Value{}
74 }
75 return nil
76 }
77
78 // Get returns a pointer representing the comparable value cmpVal.
79 //
80 // The returned pointer will be the same for Get(v) and Get(v2)
81 // if and only if v == v2, and can be used as a map key.
82 func Get(cmpVal any) *Value {
83 return get(keyFor(cmpVal))
84 }
85
86 // GetByString is identical to Get, except that it is specialized for strings.
87 // This avoids an allocation from putting a string into an interface{}
88 // to pass as an argument to Get.
89 func GetByString(s string) *Value {
90 return get(key{s: s, isString: true})
91 }
92
93 // We play unsafe games that violate Go's rules (and assume a non-moving
94 // collector). So we quiet Go here.
95 // See the comment below Get for more implementation details.
96 //go:nocheckptr
97 func get(k key) *Value {
98 mu.Lock()
99 defer mu.Unlock()
100
101 var v *Value
102 if valSafe != nil {
103 v = valSafe[k]
104 } else if addr, ok := valMap[k]; ok {
105 v = (*Value)(unsafe.Pointer(addr))
106 v.resurrected = true
107 }
108 if v != nil {
109 return v
110 }
111 v = k.Value()
112 if valSafe != nil {
113 valSafe[k] = v
114 } else {
115 // SetFinalizer before uintptr conversion (theoretical concern;
116 // see https://github.com/go4org/intern/issues/13)
117 runtime.SetFinalizer(v, finalize)
118 valMap[k] = uintptr(unsafe.Pointer(v))
119 }
120 return v
121 }
122
123 func finalize(v *Value) {
124 mu.Lock()
125 defer mu.Unlock()
126 if v.resurrected {
127 // We lost the race. Somebody resurrected it while we
128 // were about to finalize it. Try again next round.
129 v.resurrected = false
130 runtime.SetFinalizer(v, finalize)
131 return
132 }
133 delete(valMap, keyFor(v.cmpVal))
134 }
135
136 // Interning is simple if you don't require that unused values be
137 // garbage collectable. But we do require that; we don't want to be
138 // DOS vector. We do this by using a uintptr to hide the pointer from
139 // the garbage collector, and using a finalizer to eliminate the
140 // pointer when no other code is using it.
141 //
142 // The obvious implementation of this is to use a
143 // map[interface{}]uintptr-of-*interface{}, and set up a finalizer to
144 // delete from the map. Unfortunately, this is racy. Because pointers
145 // are being created in violation of Go's unsafety rules, it's
146 // possible to create a pointer to a value concurrently with the GC
147 // concluding that the value can be collected. There are other races
148 // that break the equality invariant as well, but the use-after-free
149 // will cause a runtime crash.
150 //
151 // To make this work, the finalizer needs to know that no references
152 // have been unsafely created since the finalizer was set up. To do
153 // this, values carry a "resurrected" sentinel, which gets set
154 // whenever a pointer is unsafely created. If the finalizer encounters
155 // the sentinel, it clears the sentinel and delays collection for one
156 // additional GC cycle, by re-installing itself as finalizer. This
157 // ensures that the unsafely created pointer is visible to the GC, and
158 // will correctly prevent collection.
159 //
160 // This technique does mean that interned values that get reused take
161 // at least 3 GC cycles to fully collect (1 to clear the sentinel, 1
162 // to clean up the unsafe map, 1 to be actually deleted).
163 //
164 // @ianlancetaylor commented in
165 // https://github.com/golang/go/issues/41303#issuecomment-717401656
166 // that it is possible to implement weak references in terms of
167 // finalizers without unsafe. Unfortunately, the approach he outlined
168 // does not work here, for two reasons. First, there is no way to
169 // construct a strong pointer out of a weak pointer; our map stores
170 // weak pointers, but we must return strong pointers to callers.
171 // Second, and more fundamentally, we must return not just _a_ strong
172 // pointer to callers, but _the same_ strong pointer to callers. In
173 // order to return _the same_ strong pointer to callers, we must track
174 // it, which is exactly what we cannot do with strong pointers.
175 //
176 // See https://github.com/inetaf/netaddr/issues/53 for more
177 // discussion, and https://github.com/go4org/intern/issues/2 for an
178 // illustration of the subtleties at play.