// Copyright 2015 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.

// Perf2pprof converts Linux perf profile data into Go pprof format.
// (The Linux perf suite is sometimes referred to as perf_events.)
//
// 	usage: perf2pprof [-list] [-o outfile] [-x exe] perf.data
//
// Perf2pprof converts perf.data, generated by the Linux perf suite,
// into pprof format. The default output file name is the input file
// name (including any directory) with .pprof appended.
// The -o flag instructs perf2pprof to write to outfile instead.
//
// Perf is a system-wide profiler for Linux: it captures data from every binary
// running on the system, along with the operating system kernel.
// Although in principle it should be possible to express those multiple
// event sources in a single pprof output file, the current perf2pprof
// is limited to extracting the samples from just one executable that
// was running. The -x flag specifies the executable, typically a full path.
// The -list flag causes perf2pprof to list all the executables with
// samples in the profile. One of -list or -x must be specified.
//
// Go and Perf
//
// By default, Go does not maintain x86 frame pointers, which means
// that perf cannot sample from Go's execution reliably.
// To build a Go 1.5 or later toolchain that works with perf, use:
//
//	GOEXPERIMENT=framepointer ./make.bash
//
// Bugs
//
// This is a very rough sketch. It does seem to work for simple perf profiles
// tracking only a single event, but it could be made much richer.
//
// It should not be necessary to specify the -x flag, as explained above.
// Even if limited to one executable's samples, perf2pprof could infer the
// correct setting for -x by reading the profile to count samples per executable,
// set -x to the executable with the most samples, and read the profile again.
//
package main // import "code.justin.tv/rhys/nursery/internal/rsc.io/perf2pprof"

import (
	"encoding/binary"
	"flag"
	"fmt"
	"log"
	"os"

	"code.justin.tv/rhys/nursery/internal/github.com/aclements/go-perf/perffile"
	"code.justin.tv/rhys/nursery/internal/rsc.io/perf2pprof/pprof"
)

var (
	listBinaries = flag.Bool("list", false, "list executables found in profile")
	outFlag      = flag.String("o", "", "output `file` name")
	targetBinary = flag.String("x", "", "include only samples from the named `executable`")
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: perf2pprof [-list] [-o outfile] [-x exe] perf.data\n")
	flag.PrintDefaults()
	os.Exit(2)
}

var numRecords int

func main() {
	log.SetPrefix("perf2pprof: ")
	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()
	if flag.NArg() != 1 {
		usage()
	}

	if !*listBinaries && *targetBinary == "" {
		fmt.Fprintf(os.Stderr, "-list or -x flag is required for now\n")
		os.Exit(2)
	}

	infile := flag.Arg(0)
	outfile := *outFlag
	if outfile == "" {
		outfile = infile + ".pprof"
	}
	perf, err := perffile.Open(infile)
	if err != nil {
		log.Fatal(err)
	}

	var w *os.File
	if !*listBinaries {
		w, err = os.Create(outfile)
		if err != nil {
			log.Fatal(err)
		}
	}

	printed := make(map[string]bool)
	rs := perf.Records(perffile.RecordsFileOrder)
	for rs.Next() {
		if numRecords++; numRecords&(numRecords-1) == 0 {
			fmt.Printf("%d records\n", numRecords)
		}
		switch r := rs.Record.(type) {
		case *perffile.RecordThrottle, *perffile.RecordComm, *perffile.RecordExit, *perffile.RecordFork:
			// ignore
		case *perffile.RecordMmap:
			if *listBinaries {
				if !printed[r.Filename] {
					printed[r.Filename] = true
					fmt.Printf("%q\n", r.Filename)
				}
				continue
			}
			rr := *r
			mmap[r.PID] = append(mmap[r.PID], &rr)
		case *perffile.RecordSample:
			if *listBinaries {
				continue
			}
			switch {
			default:
				fmt.Printf("bad sample: %+v\n", *r)
				continue
			case r.Format&perffile.SampleFormatCallchain != 0:
				addSample(r.PID, r.Callchain)
			case r.Format&perffile.SampleFormatIP != 0:
				addSample(r.PID, []uint64{r.IP})
			}
		default:
			fmt.Printf("found %T\n", rs.Record)
		}
	}
	if err := rs.Err(); err != nil {
		log.Fatalf("reading %s: %v", infile, err)
	}

	if *listBinaries {
		return
	}

	fmt.Printf("%d samples for %d records\n", len(samples), numRecords)

	// TODO(rsc): Get actual event type from profile.
	// TODO(rsc): A profile can actually have multiple events in it.
	// Include the event type in the stack trace map key.
	p := new(pprof.Profile)
	p.SampleType = []*pprof.ValueType{{Type: "event", Unit: "count"}}
	p.PeriodType = p.SampleType[0]
	p.Period = 1

	var stack []uint64
	var pid int
	locations := make(map[uint64]*pprof.Location)
	for _, s := range samples {
		pid, stack = decode(s.key, stack)
		_ = pid
		locs := make([]*pprof.Location, 0, len(stack))
		for _, pc := range stack {
			if len(locs) > 0 { // pprof stores caller PC with -1 added so it lands in the call instruction
				pc--
			}
			loc := locations[pc]
			if loc == nil {
				loc = &pprof.Location{
					Address: pc,
					ID:      uint64(1 + len(locations)),
				}
				locations[pc] = loc
				p.Location = append(p.Location, loc)
			}
			locs = append(locs, loc)
		}
		p.Sample = append(p.Sample, &pprof.Sample{
			Location: locs,
			Value:    []int64{s.count},
		})
	}

	if err := p.Write(w); err != nil {
		log.Fatal("writing %s: %v", outfile, err)
	}
	if err := w.Close(); err != nil {
		log.Fatal("writing %s: %v", outfile, err)
	}
}

var (
	samples = make(map[string]sample)
	mmap    = make(map[int][]*perffile.RecordMmap)
)

type sample struct {
	key   string
	count int64
}

var buf = make([]byte, 1024)

func filterStack(pid int, stack []uint64) []uint64 {
	mem := mmap[pid]
	stk := stack[:0]
	for _, pc := range stack {
		for _, m := range mem {
			if m.Addr <= pc && pc-m.Addr < m.Len && m.Filename == *targetBinary {
				stk = append(stk, pc)
				break
			}
		}
	}
	return stk
}

func addSample(pid int, stack []uint64) {
	stack = filterStack(pid, stack)
	if len(stack) == 0 {
		return
	}
	for cap(buf) < (1+len(stack))*10 {
		buf = make([]byte, cap(buf)*2)
	}
	buf = buf[:10*(1+len(stack))]
	n := 0
	n += binary.PutUvarint(buf[n:], uint64(pid))
	for _, x := range stack {
		n += binary.PutUvarint(buf[n:], x)
	}

	buf = buf[:n]
	s, ok := samples[string(buf)]
	if !ok {
		s.key = string(buf)
		if len(samples)&(len(samples)-1) == 0 {
			fmt.Printf("%d samples for %d records\n", len(samples)+1, numRecords)
		}
	}
	s.count++
	samples[s.key] = s
}

func decode(s string, stack []uint64) (pid int, outstack []uint64) {
	stack = stack[:0]
	v, n := uvarint(s)
	if n <= 0 {
		log.Fatal("malformed internal encoding")
	}
	pid = int(v)
	s = s[n:]
	for len(s) > 0 {
		v, n := uvarint(s)
		if n <= 0 {
			log.Fatal("malformed internal encoding")
		}
		stack = append(stack, v)
		s = s[n:]
	}
	return pid, stack
}

func uvarint(buf string) (uint64, int) {
	var x uint64
	var s uint
	for i := 0; i < len(buf); i++ {
		b := buf[i]
		if b < 0x80 {
			if i > 9 || i == 9 && b > 1 {
				return 0, -(i + 1) // overflow
			}
			return x | uint64(b)<<s, i + 1
		}
		x |= uint64(b&0x7f) << s
		s += 7
	}
	return 0, 0
}
