Debian Codegraph @

internal/driver/fetch_test.go

raw symbols SCIP
1 // Copyright 2014 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package driver
16
17 import (
18 "crypto/ecdsa"
19 "crypto/elliptic"
20 "crypto/rand"
21 "crypto/tls"
22 "crypto/x509"
23 "encoding/pem"
24 "fmt"
25 "math/big"
26 "net"
27 "net/http"
28 "os"
29 "path/filepath"
30 "reflect"
31 "regexp"
32 "runtime"
33 "strings"
34 "testing"
35 "time"
36
37 "github.com/google/pprof/internal/binutils"
38 "github.com/google/pprof/internal/plugin"
39 "github.com/google/pprof/internal/proftest"
40 "github.com/google/pprof/internal/symbolizer"
41 "github.com/google/pprof/internal/transport"
42 "github.com/google/pprof/profile"
43 )
44
45 func TestSymbolizationPath(t *testing.T) {
46 if runtime.GOOS == "windows" {
47 t.Skip("test assumes Unix paths")
48 }
49
50 // Save environment variables to restore after test
51 saveHome := os.Getenv(homeEnv())
52 savePath := os.Getenv("PPROF_BINARY_PATH")
53
54 tempdir, err := os.MkdirTemp("", "home")
55 if err != nil {
56 t.Fatal("creating temp dir: ", err)
57 }
58 defer os.RemoveAll(tempdir)
59 os.MkdirAll(filepath.Join(tempdir, "pprof", "binaries", "abcde10001"), 0700)
60 os.Create(filepath.Join(tempdir, "pprof", "binaries", "abcde10001", "binary"))
61
62 os.MkdirAll(filepath.Join(tempdir, "pprof", "binaries", "fg"), 0700)
63 os.Create(filepath.Join(tempdir, "pprof", "binaries", "fg", "hij10001.debug"))
64
65 obj := testObj{tempdir}
66 os.Setenv(homeEnv(), tempdir)
67 for _, tc := range []struct {
68 env, file, buildID, want string
69 msgCount int
70 }{
71 {"", "/usr/bin/binary", "", "/usr/bin/binary", 0},
72 {"", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 0},
73 {"/usr", "/bin/binary", "", "/usr/bin/binary", 0},
74 {"", "/prod/path/binary", "abcde10001", filepath.Join(tempdir, "pprof/binaries/abcde10001/binary"), 0},
75 {"/alternate/architecture", "/usr/bin/binary", "", "/alternate/architecture/binary", 0},
76 {"/alternate/architecture", "/usr/bin/binary", "abcde10001", "/alternate/architecture/binary", 0},
77 {"", "", "fghij10001", filepath.Join(tempdir, "pprof/binaries/fg/hij10001.debug"), 0},
78 {"/nowhere:/alternate/architecture", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 1},
79 {"/nowhere:/alternate/architecture", "/usr/bin/binary", "abcde10002", "/usr/bin/binary", 1},
80 } {
81 os.Setenv("PPROF_BINARY_PATH", tc.env)
82 p := &profile.Profile{
83 Mapping: []*profile.Mapping{
84 {
85 File: tc.file,
86 BuildID: tc.buildID,
87 },
88 },
89 }
90 s := &source{}
91 locateBinaries(p, s, obj, &proftest.TestUI{T: t, Ignore: tc.msgCount})
92 if file := p.Mapping[0].File; file != tc.want {
93 t.Errorf("%s:%s:%s, want %s, got %s", tc.env, tc.file, tc.buildID, tc.want, file)
94 }
95 }
96 os.Setenv(homeEnv(), saveHome)
97 os.Setenv("PPROF_BINARY_PATH", savePath)
98 }
99
100 func TestCollectMappingSources(t *testing.T) {
101 const startAddress uint64 = 0x40000
102 const url = "http://example.com"
103 for _, tc := range []struct {
104 file, buildID string
105 want plugin.MappingSources
106 }{
107 {"/usr/bin/binary", "buildId", mappingSources("buildId", url, startAddress)},
108 {"/usr/bin/binary", "", mappingSources("/usr/bin/binary", url, startAddress)},
109 {"", "", mappingSources(url, url, startAddress)},
110 } {
111 p := &profile.Profile{
112 Mapping: []*profile.Mapping{
113 {
114 File: tc.file,
115 BuildID: tc.buildID,
116 Start: startAddress,
117 },
118 },
119 }
120 got := collectMappingSources(p, url)
121 if !reflect.DeepEqual(got, tc.want) {
122 t.Errorf("%s:%s, want %v, got %v", tc.file, tc.buildID, tc.want, got)
123 }
124 }
125 }
126
127 func TestUnsourceMappings(t *testing.T) {
128 for _, tc := range []struct {
129 os, file, buildID, want string
130 }{
131 {"any", "/usr/bin/binary", "buildId", "/usr/bin/binary"},
132 {"any", "http://example.com", "", ""},
133 {"windows", `C:\example.exe`, "", `C:\example.exe`},
134 {"windows", `c:/example.exe`, "", `c:/example.exe`},
135 } {
136 t.Run(tc.file+"-"+tc.os, func(t *testing.T) {
137 if tc.os != "any" && tc.os != runtime.GOOS {
138 t.Skipf("%s only test", tc.os)
139 }
140
141 p := &profile.Profile{
142 Mapping: []*profile.Mapping{
143 {
144 File: tc.file,
145 BuildID: tc.buildID,
146 },
147 },
148 }
149 unsourceMappings(p)
150 if got := p.Mapping[0].File; got != tc.want {
151 t.Errorf("%s:%s, want %s, got %s", tc.file, tc.buildID, tc.want, got)
152 }
153 })
154 }
155 }
156
157 type testObj struct {
158 home string
159 }
160
161 func (o testObj) Open(file string, start, limit, offset uint64, relocationSymbol string) (plugin.ObjFile, error) {
162 switch file {
163 case "/alternate/architecture/binary":
164 return testFile{file, "abcde10001"}, nil
165 case "/usr/bin/binary":
166 return testFile{file, "fedcb10000"}, nil
167 case filepath.Join(o.home, "pprof/binaries/abcde10001/binary"):
168 return testFile{file, "abcde10001"}, nil
169 case filepath.Join(o.home, "pprof/binaries/fg/hij10001.debug"):
170 return testFile{file, "fghij10001"}, nil
171 }
172 return nil, fmt.Errorf("not found: %s", file)
173 }
174 func (testObj) Demangler(_ string) func(names []string) (map[string]string, error) {
175 return func(names []string) (map[string]string, error) { return nil, nil }
176 }
177 func (testObj) Disasm(file string, start, end uint64, intelSyntax bool) ([]plugin.Inst, error) {
178 return nil, nil
179 }
180
181 type testFile struct{ name, buildID string }
182
183 func (f testFile) Name() string { return f.name }
184 func (testFile) ObjAddr(addr uint64) (uint64, error) { return addr, nil }
185 func (f testFile) BuildID() string { return f.buildID }
186 func (testFile) SourceLine(addr uint64) ([]plugin.Frame, error) { return nil, nil }
187 func (testFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) { return nil, nil }
188 func (testFile) Close() error { return nil }
189
190 func TestFetch(t *testing.T) {
191 const path = "testdata/"
192 type testcase struct {
193 source, execName string
194 wantErr bool
195 }
196 ts := []testcase{
197 {path + "go.crc32.cpu", "", false},
198 {path + "go.nomappings.crash", "/bin/gotest.exe", false},
199 {"http://localhost/profile?file=cppbench.cpu", "", false},
200 {"./missing", "", true},
201 }
202 // Test that paths with a colon character are recognized as file paths
203 // if the file exists, rather than as a URL. We have to skip this test
204 // on Windows since the colon char is not allowed in Windows paths.
205 if runtime.GOOS != "windows" {
206 src := filepath.Join(path, "go.crc32.cpu")
207 dst := filepath.Join(t.TempDir(), "go.crc32.cpu_2023-11-11_01:02:03")
208 data, err := os.ReadFile(src)
209 if err != nil {
210 t.Fatalf("read src file %s failed: %#v", src, err)
211 }
212 err = os.WriteFile(dst, data, 0644)
213 if err != nil {
214 t.Fatalf("create dst file %s failed: %#v", dst, err)
215 }
216 ts = append(ts, testcase{dst, "", false})
217 }
218 for _, tc := range ts {
219 t.Run(tc.source, func(t *testing.T) {
220 p, _, _, err := grabProfile(&source{ExecName: tc.execName}, tc.source, nil, testObj{}, &proftest.TestUI{T: t}, &httpTransport{})
221 if tc.wantErr {
222 if err == nil {
223 t.Fatal("got no error, want an error")
224 }
225 return
226 }
227 if err != nil {
228 t.Fatalf("got error %v, want no error", err)
229 }
230 if len(p.Sample) == 0 {
231 t.Error("got zero samples, want non-zero")
232 }
233 if e := tc.execName; e != "" {
234 switch {
235 case len(p.Mapping) == 0 || p.Mapping[0] == nil:
236 t.Errorf("got no mappings, want mapping[0].execName == %s", e)
237 case p.Mapping[0].File != e:
238 t.Errorf("got mapping[0].execName == %s, want %s", p.Mapping[0].File, e)
239 }
240 }
241 })
242 }
243 }
244
245 func TestFetchWithBase(t *testing.T) {
246 baseConfig := currentConfig()
247 defer setCurrentConfig(baseConfig)
248
249 type WantSample struct {
250 values []int64
251 labels map[string][]string
252 }
253
254 const path = "testdata/"
255 type testcase struct {
256 desc string
257 sources []string
258 bases []string
259 diffBases []string
260 normalize bool
261 wantSamples []WantSample
262 wantParseErrorMsg string
263 wantFetchErrorMsg string
264 }
265
266 testcases := []testcase{
267 {
268 "not normalized base is same as source",
269 []string{path + "cppbench.contention"},
270 []string{path + "cppbench.contention"},
271 nil,
272 false,
273 nil,
274 "",
275 "",
276 },
277 {
278 "not normalized base is same as source",
279 []string{path + "cppbench.contention"},
280 []string{path + "cppbench.contention"},
281 nil,
282 false,
283 nil,
284 "",
285 "",
286 },
287 {
288 "not normalized single source, multiple base (all profiles same)",
289 []string{path + "cppbench.contention"},
290 []string{path + "cppbench.contention", path + "cppbench.contention"},
291 nil,
292 false,
293 []WantSample{
294 {
295 values: []int64{-2700, -608881724},
296 labels: map[string][]string{},
297 },
298 {
299 values: []int64{-100, -23992},
300 labels: map[string][]string{},
301 },
302 {
303 values: []int64{-200, -179943},
304 labels: map[string][]string{},
305 },
306 {
307 values: []int64{-100, -17778444},
308 labels: map[string][]string{},
309 },
310 {
311 values: []int64{-100, -75976},
312 labels: map[string][]string{},
313 },
314 {
315 values: []int64{-300, -63568134},
316 labels: map[string][]string{},
317 },
318 },
319 "",
320 "",
321 },
322 {
323 "not normalized, different base and source",
324 []string{path + "cppbench.contention"},
325 []string{path + "cppbench.small.contention"},
326 nil,
327 false,
328 []WantSample{
329 {
330 values: []int64{1700, 608878600},
331 labels: map[string][]string{},
332 },
333 {
334 values: []int64{100, 23992},
335 labels: map[string][]string{},
336 },
337 {
338 values: []int64{200, 179943},
339 labels: map[string][]string{},
340 },
341 {
342 values: []int64{100, 17778444},
343 labels: map[string][]string{},
344 },
345 {
346 values: []int64{100, 75976},
347 labels: map[string][]string{},
348 },
349 {
350 values: []int64{300, 63568134},
351 labels: map[string][]string{},
352 },
353 },
354 "",
355 "",
356 },
357 {
358 "normalized base is same as source",
359 []string{path + "cppbench.contention"},
360 []string{path + "cppbench.contention"},
361 nil,
362 true,
363 nil,
364 "",
365 "",
366 },
367 {
368 "normalized single source, multiple base (all profiles same)",
369 []string{path + "cppbench.contention"},
370 []string{path + "cppbench.contention", path + "cppbench.contention"},
371 nil,
372 true,
373 nil,
374 "",
375 "",
376 },
377 {
378 "normalized different base and source",
379 []string{path + "cppbench.contention"},
380 []string{path + "cppbench.small.contention"},
381 nil,
382 true,
383 []WantSample{
384 {
385 values: []int64{-229, -369},
386 labels: map[string][]string{},
387 },
388 {
389 values: []int64{29, 0},
390 labels: map[string][]string{},
391 },
392 {
393 values: []int64{57, 1},
394 labels: map[string][]string{},
395 },
396 {
397 values: []int64{29, 80},
398 labels: map[string][]string{},
399 },
400 {
401 values: []int64{29, 0},
402 labels: map[string][]string{},
403 },
404 {
405 values: []int64{86, 288},
406 labels: map[string][]string{},
407 },
408 },
409 "",
410 "",
411 },
412 {
413 "not normalized diff base is same as source",
414 []string{path + "cppbench.contention"},
415 nil,
416 []string{path + "cppbench.contention"},
417 false,
418 []WantSample{
419 {
420 values: []int64{2700, 608881724},
421 labels: map[string][]string{},
422 },
423 {
424 values: []int64{100, 23992},
425 labels: map[string][]string{},
426 },
427 {
428 values: []int64{200, 179943},
429 labels: map[string][]string{},
430 },
431 {
432 values: []int64{100, 17778444},
433 labels: map[string][]string{},
434 },
435 {
436 values: []int64{100, 75976},
437 labels: map[string][]string{},
438 },
439 {
440 values: []int64{300, 63568134},
441 labels: map[string][]string{},
442 },
443 {
444 values: []int64{-2700, -608881724},
445 labels: map[string][]string{"pprof::base": {"true"}},
446 },
447 {
448 values: []int64{-100, -23992},
449 labels: map[string][]string{"pprof::base": {"true"}},
450 },
451 {
452 values: []int64{-200, -179943},
453 labels: map[string][]string{"pprof::base": {"true"}},
454 },
455 {
456 values: []int64{-100, -17778444},
457 labels: map[string][]string{"pprof::base": {"true"}},
458 },
459 {
460 values: []int64{-100, -75976},
461 labels: map[string][]string{"pprof::base": {"true"}},
462 },
463 {
464 values: []int64{-300, -63568134},
465 labels: map[string][]string{"pprof::base": {"true"}},
466 },
467 },
468 "",
469 "",
470 },
471 {
472 "diff_base and base both specified",
473 []string{path + "cppbench.contention"},
474 []string{path + "cppbench.contention"},
475 []string{path + "cppbench.contention"},
476 false,
477 nil,
478 "-base and -diff_base flags cannot both be specified",
479 "",
480 },
481 {
482 "input profiles with different sample types (non empty intersection)",
483 []string{path + "cppbench.cpu", path + "cppbench.cpu_no_samples_type"},
484 []string{path + "cppbench.cpu", path + "cppbench.cpu_no_samples_type"},
485 nil,
486 false,
487 nil,
488 "",
489 "",
490 },
491 {
492 "input profiles with different sample types (empty intersection)",
493 []string{path + "cppbench.cpu", path + "cppbench.contention"},
494 []string{path + "cppbench.cpu", path + "cppbench.contention"},
495 nil,
496 false,
497 nil,
498 "",
499 "problem fetching source profiles: profiles have empty common sample type list",
500 },
501 }
502
503 for _, tc := range testcases {
504 t.Run(tc.desc, func(t *testing.T) {
505 setCurrentConfig(baseConfig)
506 f := testFlags{
507 stringLists: map[string][]string{
508 "base": tc.bases,
509 "diff_base": tc.diffBases,
510 },
511 bools: map[string]bool{
512 "normalize": tc.normalize,
513 },
514 }
515 f.args = tc.sources
516
517 o := setDefaults(&plugin.Options{
518 UI: &proftest.TestUI{T: t, AllowRx: "Local symbolization failed|Some binary filenames not available"},
519 Flagset: f,
520 HTTPTransport: transport.New(nil),
521 })
522 src, _, err := parseFlags(o)
523
524 if tc.wantParseErrorMsg != "" {
525 if err == nil {
526 t.Fatalf("got nil, want error %q", tc.wantParseErrorMsg)
527 }
528
529 if gotErrMsg := err.Error(); gotErrMsg != tc.wantParseErrorMsg {
530 t.Fatalf("got error %q, want error %q", gotErrMsg, tc.wantParseErrorMsg)
531 }
532 return
533 }
534
535 if err != nil {
536 t.Fatalf("got error %q, want no error", err)
537 }
538
539 p, err := fetchProfiles(src, o)
540
541 if tc.wantFetchErrorMsg != "" {
542 if err == nil {
543 t.Fatalf("got nil, want error %q", tc.wantFetchErrorMsg)
544 }
545
546 if gotErrMsg := err.Error(); gotErrMsg != tc.wantFetchErrorMsg {
547 t.Fatalf("got error %q, want error %q", gotErrMsg, tc.wantFetchErrorMsg)
548 }
549 return
550 }
551
552 if err != nil {
553 t.Fatalf("got error %q, want no error", err)
554 }
555
556 if got, want := len(p.Sample), len(tc.wantSamples); got != want {
557 t.Fatalf("got %d samples want %d", got, want)
558 }
559
560 for i, sample := range p.Sample {
561 if !reflect.DeepEqual(tc.wantSamples[i].values, sample.Value) {
562 t.Errorf("for sample %d got values %v, want %v", i, sample.Value, tc.wantSamples[i])
563 }
564 if !reflect.DeepEqual(tc.wantSamples[i].labels, sample.Label) {
565 t.Errorf("for sample %d got labels %v, want %v", i, sample.Label, tc.wantSamples[i].labels)
566 }
567 }
568 })
569 }
570 }
571
572 // mappingSources creates MappingSources map with a single item.
573 func mappingSources(key, source string, start uint64) plugin.MappingSources {
574 return plugin.MappingSources{
575 key: []struct {
576 Source string
577 Start uint64
578 }{
579 {Source: source, Start: start},
580 },
581 }
582 }
583
584 type httpTransport struct{}
585
586 func (tr *httpTransport) RoundTrip(req *http.Request) (*http.Response, error) {
587 values := req.URL.Query()
588 file := values.Get("file")
589
590 if file == "" {
591 return nil, fmt.Errorf("want .../file?profile, got %s", req.URL.String())
592 }
593
594 t := &http.Transport{}
595 t.RegisterProtocol("file", http.NewFileTransport(http.Dir("testdata/")))
596
597 c := &http.Client{Transport: t}
598 return c.Get("file:///" + file)
599 }
600
601 func closedError() string {
602 if runtime.GOOS == "plan9" {
603 return "listen hungup"
604 }
605 return "use of closed"
606 }
607
608 func TestHTTPSInsecure(t *testing.T) {
609 if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
610 t.Skip("test assumes tcp available")
611 }
612 saveHome := os.Getenv(homeEnv())
613 tempdir, err := os.MkdirTemp("", "home")
614 if err != nil {
615 t.Fatal("creating temp dir: ", err)
616 }
617 defer os.RemoveAll(tempdir)
618
619 // pprof writes to $HOME/pprof by default which is not necessarily
620 // writeable (e.g. on a Debian build) so set $HOME to something we
621 // know we can write to for the duration of the test.
622 os.Setenv(homeEnv(), tempdir)
623 defer os.Setenv(homeEnv(), saveHome)
624
625 baseConfig := currentConfig()
626 defer setCurrentConfig(baseConfig)
627
628 tlsCert, _, _ := selfSignedCert(t, "")
629 tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
630
631 l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
632 if err != nil {
633 t.Fatalf("net.Listen: got error %v, want no error", err)
634 }
635
636 donec := make(chan error, 1)
637 go func(donec chan<- error) {
638 donec <- http.Serve(l, nil)
639 }(donec)
640 defer func() {
641 if got, want := <-donec, closedError(); !strings.Contains(got.Error(), want) {
642 t.Fatalf("Serve got error %v, want %q", got, want)
643 }
644 }()
645 defer l.Close()
646
647 outputTempFile, err := os.CreateTemp("", "profile_output")
648 if err != nil {
649 t.Fatalf("Failed to create tempfile: %v", err)
650 }
651 defer os.Remove(outputTempFile.Name())
652 defer outputTempFile.Close()
653
654 address := "https+insecure://" + l.Addr().String() + "/debug/pprof/goroutine"
655 s := &source{
656 Sources: []string{address},
657 Timeout: 10,
658 Symbolize: "remote",
659 }
660 o := &plugin.Options{
661 Obj: &binutils.Binutils{},
662 UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
663 HTTPTransport: transport.New(nil),
664 }
665 o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI}
666 p, err := fetchProfiles(s, o)
667 if err != nil {
668 t.Fatal(err)
669 }
670 if len(p.SampleType) == 0 {
671 t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
672 }
673 if len(p.Function) == 0 {
674 t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
675 }
676 if err := checkProfileHasFunction(p, "TestHTTPSInsecure"); err != nil {
677 t.Fatalf("fetchProfiles(%s) %v", address, err)
678 }
679 }
680
681 func TestHTTPSWithServerCertFetch(t *testing.T) {
682 if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
683 t.Skip("test assumes tcp available")
684 }
685 saveHome := os.Getenv(homeEnv())
686 tempdir, err := os.MkdirTemp("", "home")
687 if err != nil {
688 t.Fatal("creating temp dir: ", err)
689 }
690 defer os.RemoveAll(tempdir)
691
692 // pprof writes to $HOME/pprof by default which is not necessarily
693 // writeable (e.g. on a Debian build) so set $HOME to something we
694 // know we can write to for the duration of the test.
695 os.Setenv(homeEnv(), tempdir)
696 defer os.Setenv(homeEnv(), saveHome)
697
698 baseConfig := currentConfig()
699 defer setCurrentConfig(baseConfig)
700
701 cert, certBytes, keyBytes := selfSignedCert(t, "localhost")
702 cas := x509.NewCertPool()
703 cas.AppendCertsFromPEM(certBytes)
704
705 tlsConfig := &tls.Config{
706 RootCAs: cas,
707 Certificates: []tls.Certificate{cert},
708 ClientAuth: tls.RequireAndVerifyClientCert,
709 ClientCAs: cas,
710 }
711
712 l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
713 if err != nil {
714 t.Fatalf("net.Listen: got error %v, want no error", err)
715 }
716
717 donec := make(chan error, 1)
718 go func(donec chan<- error) {
719 donec <- http.Serve(l, nil)
720 }(donec)
721 defer func() {
722 if got, want := <-donec, closedError(); !strings.Contains(got.Error(), want) {
723 t.Fatalf("Serve got error %v, want %q", got, want)
724 }
725 }()
726 defer l.Close()
727
728 outputTempFile, err := os.CreateTemp("", "profile_output")
729 if err != nil {
730 t.Fatalf("Failed to create tempfile: %v", err)
731 }
732 defer os.Remove(outputTempFile.Name())
733 defer outputTempFile.Close()
734
735 // Get port from the address, so request to the server can be made using
736 // the host name specified in certificates.
737 _, portStr, err := net.SplitHostPort(l.Addr().String())
738 if err != nil {
739 t.Fatalf("cannot get port from URL: %v", err)
740 }
741 address := "https://" + "localhost:" + portStr + "/debug/pprof/goroutine"
742 s := &source{
743 Sources: []string{address},
744 Timeout: 10,
745 Symbolize: "remote",
746 }
747
748 certTempFile, err := os.CreateTemp("", "cert_output")
749 if err != nil {
750 t.Errorf("cannot create cert tempfile: %v", err)
751 }
752 defer os.Remove(certTempFile.Name())
753 defer certTempFile.Close()
754 certTempFile.Write(certBytes)
755
756 keyTempFile, err := os.CreateTemp("", "key_output")
757 if err != nil {
758 t.Errorf("cannot create key tempfile: %v", err)
759 }
760 defer os.Remove(keyTempFile.Name())
761 defer keyTempFile.Close()
762 keyTempFile.Write(keyBytes)
763
764 f := &testFlags{
765 strings: map[string]string{
766 "tls_cert": certTempFile.Name(),
767 "tls_key": keyTempFile.Name(),
768 "tls_ca": certTempFile.Name(),
769 },
770 }
771 o := &plugin.Options{
772 Obj: &binutils.Binutils{},
773 UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
774 Flagset: f,
775 HTTPTransport: transport.New(f),
776 }
777
778 o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI, Transport: o.HTTPTransport}
779 p, err := fetchProfiles(s, o)
780 if err != nil {
781 t.Fatal(err)
782 }
783 if len(p.SampleType) == 0 {
784 t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
785 }
786 if len(p.Function) == 0 {
787 t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
788 }
789 if err := checkProfileHasFunction(p, "TestHTTPSWithServerCertFetch"); err != nil {
790 t.Fatalf("fetchProfiles(%s) %v", address, err)
791 }
792 }
793
794 func checkProfileHasFunction(p *profile.Profile, fname string) error {
795 for _, f := range p.Function {
796 if strings.Contains(f.Name, fname) {
797 return nil
798 }
799 }
800 return fmt.Errorf("got %s, want function %q", p.String(), fname)
801 }
802
803 // selfSignedCert generates a self-signed certificate, and returns the
804 // generated certificate, and byte arrays containing the certificate and
805 // key associated with the certificate.
806 func selfSignedCert(t *testing.T, host string) (tls.Certificate, []byte, []byte) {
807 privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
808 if err != nil {
809 t.Fatalf("failed to generate private key: %v", err)
810 }
811 b, err := x509.MarshalECPrivateKey(privKey)
812 if err != nil {
813 t.Fatalf("failed to marshal private key: %v", err)
814 }
815 bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
816
817 tmpl := x509.Certificate{
818 SerialNumber: big.NewInt(1),
819 NotBefore: time.Now(),
820 NotAfter: time.Now().Add(10 * time.Minute),
821 IsCA: true,
822 DNSNames: []string{host},
823 }
824
825 b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
826 if err != nil {
827 t.Fatalf("failed to create cert: %v", err)
828 }
829 bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
830
831 cert, err := tls.X509KeyPair(bc, bk)
832 if err != nil {
833 t.Fatalf("failed to create TLS key pair: %v", err)
834 }
835 return cert, bc, bk
836 }