Debian Codegraph @

libgo/go/runtime/testdata/testprogcgo/threadpprof.go

raw
1 // Copyright 2016 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 //go:build !plan9 && !windows && !gccgo
6
7 package main
8
9 // Run a slow C function saving a CPU profile.
10
11 /*
12 #include <stdint.h>
13 #include <time.h>
14 #include <pthread.h>
15
16 int threadSalt1;
17 int threadSalt2;
18
19 void cpuHogThread() {
20 int foo = threadSalt1;
21 int i;
22
23 for (i = 0; i < 100000; i++) {
24 if (foo > 0) {
25 foo *= foo;
26 } else {
27 foo *= foo + 1;
28 }
29 }
30 threadSalt2 = foo;
31 }
32
33 void cpuHogThread2() {
34 }
35
36 struct cgoTracebackArg {
37 uintptr_t context;
38 uintptr_t sigContext;
39 uintptr_t* buf;
40 uintptr_t max;
41 };
42
43 // pprofCgoThreadTraceback is passed to runtime.SetCgoTraceback.
44 // For testing purposes it pretends that all CPU hits in C code are in cpuHog.
45 void pprofCgoThreadTraceback(void* parg) {
46 struct cgoTracebackArg* arg = (struct cgoTracebackArg*)(parg);
47 arg->buf[0] = (uintptr_t)(cpuHogThread) + 0x10;
48 arg->buf[1] = (uintptr_t)(cpuHogThread2) + 0x4;
49 arg->buf[2] = 0;
50 }
51
52 static void* cpuHogDriver(void* arg __attribute__ ((unused))) {
53 while (1) {
54 cpuHogThread();
55 }
56 return 0;
57 }
58
59 void runCPUHogThread(void) {
60 pthread_t tid;
61 pthread_create(&tid, 0, cpuHogDriver, 0);
62 }
63 */
64 import "C"
65
66 import (
67 "context"
68 "fmt"
69 "os"
70 "runtime"
71 "runtime/pprof"
72 "time"
73 "unsafe"
74 )
75
76 func init() {
77 register("CgoPprofThread", CgoPprofThread)
78 register("CgoPprofThreadNoTraceback", CgoPprofThreadNoTraceback)
79 }
80
81 func CgoPprofThread() {
82 runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)
83 pprofThread()
84 }
85
86 func CgoPprofThreadNoTraceback() {
87 pprofThread()
88 }
89
90 func pprofThread() {
91 f, err := os.CreateTemp("", "prof")
92 if err != nil {
93 fmt.Fprintln(os.Stderr, err)
94 os.Exit(2)
95 }
96
97 if err := pprof.StartCPUProfile(f); err != nil {
98 fmt.Fprintln(os.Stderr, err)
99 os.Exit(2)
100 }
101
102 // This goroutine may receive a profiling signal while creating the C-owned
103 // thread. If it does, the SetCgoTraceback handler will make the leaf end of
104 // the stack look almost (but not exactly) like the stacks the test case is
105 // trying to find. Attach a profiler label so the test can filter out those
106 // confusing samples.
107 pprof.Do(context.Background(), pprof.Labels("ignore", "ignore"), func(ctx context.Context) {
108 C.runCPUHogThread()
109 })
110
111 time.Sleep(1 * time.Second)
112
113 pprof.StopCPUProfile()
114
115 name := f.Name()
116 if err := f.Close(); err != nil {
117 fmt.Fprintln(os.Stderr, err)
118 os.Exit(2)
119 }
120
121 fmt.Println(name)
122 }