github.com/ck00004/CobaltStrikeParser-Go@v1.0.14/lib/http/pprof/pprof_test.go (about) 1 // Copyright 2018 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 pprof 6 7 import ( 8 "bytes" 9 "fmt" 10 "io" 11 "runtime" 12 "runtime/pprof" 13 "strings" 14 "sync" 15 "sync/atomic" 16 "testing" 17 "time" 18 19 "github.com/ck00004/CobaltStrikeParser-Go/lib/internal/profile" 20 21 "github.com/ck00004/CobaltStrikeParser-Go/lib/http" 22 23 "github.com/ck00004/CobaltStrikeParser-Go/lib/http/httptest" 24 ) 25 26 // TestDescriptions checks that the profile names under runtime/pprof package 27 // have a key in the description map. 28 func TestDescriptions(t *testing.T) { 29 for _, p := range pprof.Profiles() { 30 _, ok := profileDescriptions[p.Name()] 31 if ok != true { 32 t.Errorf("%s does not exist in profileDescriptions map\n", p.Name()) 33 } 34 } 35 } 36 37 func TestHandlers(t *testing.T) { 38 testCases := []struct { 39 path string 40 handler http.HandlerFunc 41 statusCode int 42 contentType string 43 contentDisposition string 44 resp []byte 45 }{ 46 {"/debug/pprof/<script>scripty<script>", Index, http.StatusNotFound, "text/plain; charset=utf-8", "", []byte("Unknown profile\n")}, 47 {"/debug/pprof/heap", Index, http.StatusOK, "application/octet-stream", `attachment; filename="heap"`, nil}, 48 {"/debug/pprof/heap?debug=1", Index, http.StatusOK, "text/plain; charset=utf-8", "", nil}, 49 {"/debug/pprof/cmdline", Cmdline, http.StatusOK, "text/plain; charset=utf-8", "", nil}, 50 {"/debug/pprof/profile?seconds=1", Profile, http.StatusOK, "application/octet-stream", `attachment; filename="profile"`, nil}, 51 {"/debug/pprof/symbol", Symbol, http.StatusOK, "text/plain; charset=utf-8", "", nil}, 52 {"/debug/pprof/trace", Trace, http.StatusOK, "application/octet-stream", `attachment; filename="trace"`, nil}, 53 {"/debug/pprof/mutex", Index, http.StatusOK, "application/octet-stream", `attachment; filename="mutex"`, nil}, 54 {"/debug/pprof/block?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="block-delta"`, nil}, 55 {"/debug/pprof/goroutine?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="goroutine-delta"`, nil}, 56 {"/debug/pprof/", Index, http.StatusOK, "text/html; charset=utf-8", "", []byte("Types of profiles available:")}, 57 } 58 for _, tc := range testCases { 59 t.Run(tc.path, func(t *testing.T) { 60 req := httptest.NewRequest("GET", "http://example.com"+tc.path, nil) 61 w := httptest.NewRecorder() 62 tc.handler(w, req) 63 64 resp := w.Result() 65 if got, want := resp.StatusCode, tc.statusCode; got != want { 66 t.Errorf("status code: got %d; want %d", got, want) 67 } 68 69 body, err := io.ReadAll(resp.Body) 70 if err != nil { 71 t.Errorf("when reading response body, expected non-nil err; got %v", err) 72 } 73 if got, want := resp.Header.Get("X-Content-Type-Options"), "nosniff"; got != want { 74 t.Errorf("X-Content-Type-Options: got %q; want %q", got, want) 75 } 76 if got, want := resp.Header.Get("Content-Type"), tc.contentType; got != want { 77 t.Errorf("Content-Type: got %q; want %q", got, want) 78 } 79 if got, want := resp.Header.Get("Content-Disposition"), tc.contentDisposition; got != want { 80 t.Errorf("Content-Disposition: got %q; want %q", got, want) 81 } 82 83 if resp.StatusCode == http.StatusOK { 84 return 85 } 86 if got, want := resp.Header.Get("X-Go-Pprof"), "1"; got != want { 87 t.Errorf("X-Go-Pprof: got %q; want %q", got, want) 88 } 89 if !bytes.Equal(body, tc.resp) { 90 t.Errorf("response: got %q; want %q", body, tc.resp) 91 } 92 }) 93 } 94 } 95 96 var Sink uint32 97 98 func mutexHog1(mu1, mu2 *sync.Mutex, start time.Time, dt time.Duration) { 99 atomic.AddUint32(&Sink, 1) 100 for time.Since(start) < dt { 101 // When using gccgo the loop of mutex operations is 102 // not preemptible. This can cause the loop to block a GC, 103 // causing the time limits in TestDeltaContentionz to fail. 104 // Since this loop is not very realistic, when using 105 // gccgo add preemption points 100 times a second. 106 t1 := time.Now() 107 for time.Since(start) < dt && time.Since(t1) < 10*time.Millisecond { 108 mu1.Lock() 109 mu2.Lock() 110 mu1.Unlock() 111 mu2.Unlock() 112 } 113 if runtime.Compiler == "gccgo" { 114 runtime.Gosched() 115 } 116 } 117 } 118 119 // mutexHog2 is almost identical to mutexHog but we keep them separate 120 // in order to distinguish them with function names in the stack trace. 121 // We make them slightly different, using Sink, because otherwise 122 // gccgo -c opt will merge them. 123 func mutexHog2(mu1, mu2 *sync.Mutex, start time.Time, dt time.Duration) { 124 atomic.AddUint32(&Sink, 2) 125 for time.Since(start) < dt { 126 // See comment in mutexHog. 127 t1 := time.Now() 128 for time.Since(start) < dt && time.Since(t1) < 10*time.Millisecond { 129 mu1.Lock() 130 mu2.Lock() 131 mu1.Unlock() 132 mu2.Unlock() 133 } 134 if runtime.Compiler == "gccgo" { 135 runtime.Gosched() 136 } 137 } 138 } 139 140 // mutexHog starts multiple goroutines that runs the given hogger function for the specified duration. 141 // The hogger function will be given two mutexes to lock & unlock. 142 func mutexHog(duration time.Duration, hogger func(mu1, mu2 *sync.Mutex, start time.Time, dt time.Duration)) { 143 start := time.Now() 144 mu1 := new(sync.Mutex) 145 mu2 := new(sync.Mutex) 146 var wg sync.WaitGroup 147 wg.Add(10) 148 for i := 0; i < 10; i++ { 149 go func() { 150 defer wg.Done() 151 hogger(mu1, mu2, start, duration) 152 }() 153 } 154 wg.Wait() 155 } 156 157 func TestDeltaProfile(t *testing.T) { 158 rate := runtime.SetMutexProfileFraction(1) 159 defer func() { 160 runtime.SetMutexProfileFraction(rate) 161 }() 162 163 // mutexHog1 will appear in non-delta mutex profile 164 // if the mutex profile works. 165 mutexHog(20*time.Millisecond, mutexHog1) 166 167 // If mutexHog1 does not appear in the mutex profile, 168 // skip this test. Mutex profile is likely not working, 169 // so is the delta profile. 170 171 p, err := query("/debug/pprof/mutex") 172 if err != nil { 173 t.Skipf("mutex profile is unsupported: %v", err) 174 } 175 176 if !seen(p, "mutexHog1") { 177 t.Skipf("mutex profile is not working: %v", p) 178 } 179 180 // causes mutexHog2 call stacks to appear in the mutex profile. 181 done := make(chan bool) 182 go func() { 183 for { 184 mutexHog(20*time.Millisecond, mutexHog2) 185 select { 186 case <-done: 187 done <- true 188 return 189 default: 190 time.Sleep(10 * time.Millisecond) 191 } 192 } 193 }() 194 defer func() { // cleanup the above goroutine. 195 done <- true 196 <-done // wait for the goroutine to exit. 197 }() 198 199 for _, d := range []int{1, 4, 16, 32} { 200 endpoint := fmt.Sprintf("/debug/pprof/mutex?seconds=%d", d) 201 p, err := query(endpoint) 202 if err != nil { 203 t.Fatalf("failed to query %q: %v", endpoint, err) 204 } 205 if !seen(p, "mutexHog1") && seen(p, "mutexHog2") && p.DurationNanos > 0 { 206 break // pass 207 } 208 if d == 32 { 209 t.Errorf("want mutexHog2 but no mutexHog1 in the profile, and non-zero p.DurationNanos, got %v", p) 210 } 211 } 212 p, err = query("/debug/pprof/mutex") 213 if err != nil { 214 t.Fatalf("failed to query mutex profile: %v", err) 215 } 216 if !seen(p, "mutexHog1") || !seen(p, "mutexHog2") { 217 t.Errorf("want both mutexHog1 and mutexHog2 in the profile, got %v", p) 218 } 219 } 220 221 var srv = httptest.NewServer(nil) 222 223 func query(endpoint string) (*profile.Profile, error) { 224 url := srv.URL + endpoint 225 r, err := http.Get(url) 226 if err != nil { 227 return nil, fmt.Errorf("failed to fetch %q: %v", url, err) 228 } 229 if r.StatusCode != http.StatusOK { 230 return nil, fmt.Errorf("failed to fetch %q: %v", url, r.Status) 231 } 232 233 b, err := io.ReadAll(r.Body) 234 r.Body.Close() 235 if err != nil { 236 return nil, fmt.Errorf("failed to read and parse the result from %q: %v", url, err) 237 } 238 return profile.Parse(bytes.NewBuffer(b)) 239 } 240 241 // seen returns true if the profile includes samples whose stacks include 242 // the specified function name (fname). 243 func seen(p *profile.Profile, fname string) bool { 244 locIDs := map[*profile.Location]bool{} 245 for _, loc := range p.Location { 246 for _, l := range loc.Line { 247 if strings.Contains(l.Function.Name, fname) { 248 locIDs[loc] = true 249 break 250 } 251 } 252 } 253 for _, sample := range p.Sample { 254 for _, loc := range sample.Location { 255 if locIDs[loc] { 256 return true 257 } 258 } 259 } 260 return false 261 }