Skip to content

Commit 931c476

Browse files
committed
runtime: implement weak.runtime_makeStrongFromWeak
The runtime had weak.runtime_registerWeakPointer but not its counterpart, so a program that reads a weak pointer back did not link. crypto/tls does this in the certificate cache that it keeps behind a weak.Pointer. Weak pointers are not weak here. registerWeakPointer returns the pointer that it got, so the value it refers to stays and the way back to a strong pointer is the identity too. weak.Pointer.Value thus never reports a collected value, which the documented contract permits. testdata/weak.go does not link on the current dev branch and prints the expected value with this change.
1 parent bdc4a21 commit 931c476

4 files changed

Lines changed: 30 additions & 0 deletions

File tree

main_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ func TestBuild(t *testing.T) {
108108
}
109109
if minor >= 24 {
110110
tests = append(tests, "typealias.go")
111+
tests = append(tests, "weak.go")
111112
}
112113

113114
if *testTarget != "" {

src/runtime/runtime.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,13 @@ func registerWeakPointer(ptr unsafe.Pointer) unsafe.Pointer {
139139
return ptr
140140
}
141141

142+
//go:linkname makeStrongFromWeak weak.runtime_makeStrongFromWeak
143+
func makeStrongFromWeak(ptr unsafe.Pointer) unsafe.Pointer {
144+
// Weak pointers are not weak here. registerWeakPointer above returns the
145+
// pointer that it got, so the value stays and this is the identity too.
146+
return ptr
147+
}
148+
142149
var godebugUpdate func(string, string)
143150

144151
//go:linkname godebug_setUpdate internal/godebug.setUpdate

testdata/weak.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package main
2+
3+
import (
4+
"runtime"
5+
"weak"
6+
)
7+
8+
type value struct {
9+
n int
10+
}
11+
12+
func main() {
13+
v := &value{n: 42}
14+
p := weak.Make(v)
15+
if got := p.Value(); got == nil {
16+
println("weak pointer lost its value")
17+
} else {
18+
println("weak value:", got.n)
19+
}
20+
runtime.KeepAlive(v)
21+
}

testdata/weak.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
weak value: 42

0 commit comments

Comments
 (0)