summaryrefslogtreecommitdiffstats
path: root/src/runtime/debug/heapdump_test.go
blob: ee6b054b117afd3c6459ed1becf3ffee46f112cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package debug_test

import (
	"os"
	"runtime"
	. "runtime/debug"
	"testing"
)

func TestWriteHeapDumpNonempty(t *testing.T) {
	if runtime.GOOS == "js" {
		t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS)
	}
	f, err := os.CreateTemp("", "heapdumptest")
	if err != nil {
		t.Fatalf("TempFile failed: %v", err)
	}
	defer os.Remove(f.Name())
	defer f.Close()
	WriteHeapDump(f.Fd())
	fi, err := f.Stat()
	if err != nil {
		t.Fatalf("Stat failed: %v", err)
	}
	const minSize = 1
	if size := fi.Size(); size < minSize {
		t.Fatalf("Heap dump size %d bytes, expected at least %d bytes", size, minSize)
	}
}

type Obj struct {
	x, y int
}

func objfin(x *Obj) {
	//println("finalized", x)
}

func TestWriteHeapDumpFinalizers(t *testing.T) {
	if runtime.GOOS == "js" {
		t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS)
	}
	f, err := os.CreateTemp("", "heapdumptest")
	if err != nil {
		t.Fatalf("TempFile failed: %v", err)
	}
	defer os.Remove(f.Name())
	defer f.Close()

	// bug 9172: WriteHeapDump couldn't handle more than one finalizer
	println("allocating objects")
	x := &Obj{}
	runtime.SetFinalizer(x, objfin)
	y := &Obj{}
	runtime.SetFinalizer(y, objfin)

	// Trigger collection of x and y, queueing of their finalizers.
	println("starting gc")
	runtime.GC()

	// Make sure WriteHeapDump doesn't fail with multiple queued finalizers.
	println("starting dump")
	WriteHeapDump(f.Fd())
	println("done dump")
}

type G[T any] struct{}
type I interface {
	M()
}

//go:noinline
func (g G[T]) M() {}

var dummy I = G[int]{}
var dummy2 I = G[G[int]]{}

func TestWriteHeapDumpTypeName(t *testing.T) {
	if runtime.GOOS == "js" {
		t.Skipf("WriteHeapDump is not available on %s.", runtime.GOOS)
	}
	f, err := os.CreateTemp("", "heapdumptest")
	if err != nil {
		t.Fatalf("TempFile failed: %v", err)
	}
	defer os.Remove(f.Name())
	defer f.Close()
	WriteHeapDump(f.Fd())
	dummy.M()
	dummy2.M()
}