package symbol

import (
	"debug/elf"
	"flag"
	"os"
	"testing"
)

var (
	vmlinux = flag.String("vmlinux", "", "Path to linux kernel with debug symbols")

	// Address of do_numa_page in the "3.13.0-79-generic #123~precise1-Ubuntu"
	// kernel
	dnpAddr uint64 = 0xffffffff81184f60
)

func TestKernelSymbol(t *testing.T) {
	t.Skip("weird test")

	if *vmlinux == "" {
		t.Fatalf("vmlinux flag not set")
	}
	f, err := os.Open(*vmlinux)
	if err != nil {
		t.Fatalf("could not open vmlinux %q: %v", *vmlinux, err)
	}
	defer f.Close()

	ef, err := elf.NewFile(f)
	if err != nil {
		t.Fatalf("elf: %v", err)
	}

	dw, err := ef.DWARF()
	if err != nil {
		t.Fatalf("dwarf: %v", err)
	}

	_ = dw

	syms, err := ef.Symbols()
	if err != nil {
		t.Fatalf("elf symbols: %v", err)
	}

	t.Logf("symbols=%d", len(syms))

	var i = -1
	for _, sym := range syms {
		if sym.Name == "" {
			continue
		}
		switch sym.Section {
		case 1, 19, 20, 65521:
			continue
		}
		i++
		if i >= 10 && sym.Name != "do_numa_page" {
			continue
		}
		t.Logf("symbol name=%q section=%d size=%d value=%x", sym.Name, sym.Section, sym.Size, sym.Value)
	}

	t.Logf("sections=%d", len(ef.Sections))
	for i, s := range ef.Sections {
		if bits := elf.SHF_ALLOC | elf.SHF_EXECINSTR; s.Flags&bits != bits {
			continue
		}
		t.Logf("addr=%x size=%x i=%d name=%q type=%q flags=%q", s.Addr, s.Size, i, s.Name, s.Type, s.Flags)
	}

	obj, err := newObject(f)
	if err != nil {
		t.Fatalf("newObject: %v", err)
	}

	l, err := obj.Resolve(dnpAddr)
	if err != nil {
		t.Fatalf("Resolve: %v", err)
	}

	t.Logf("location: %#v", l)
}
