diff --git a/go.mod b/go.mod index a8b88ccc..7ded24d4 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,8 @@ require ( github.com/cosiner/argv v0.0.0-20170225145430-13bacc38a0a5 github.com/cpuguy83/go-md2man v1.0.10 // indirect github.com/google/go-dap v0.2.0 + github.com/cpuguy83/go-md2man v1.0.8 // indirect + github.com/hashicorp/golang-lru v0.5.4 github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/mattn/go-colorable v0.0.0-20170327083344-ded68f7a9561 github.com/mattn/go-isatty v0.0.3 diff --git a/go.sum b/go.sum index 7fcdfe0a..7bcbbe16 100644 --- a/go.sum +++ b/go.sum @@ -10,6 +10,8 @@ github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/google/go-dap v0.2.0 h1:whjIGQRumwbR40qRU7CEKuFLmePUUc2s4Nt9DoXXxWk= github.com/google/go-dap v0.2.0/go.mod h1:5q8aYQFnHOAZEMP+6vmq25HKYAEwE+LF5yh7JKrrhSQ= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= diff --git a/pkg/dwarf/godwarf/tree.go b/pkg/dwarf/godwarf/tree.go new file mode 100644 index 00000000..2cb56a7a --- /dev/null +++ b/pkg/dwarf/godwarf/tree.go @@ -0,0 +1,255 @@ +package godwarf + +import ( + "debug/dwarf" + "fmt" + "sort" +) + +// Entry represents a debug_info entry. +// When calling Val, if the entry does not have the specified attribute, the +// entry specified by DW_AT_abstract_origin will be searched recursively. +type Entry interface { + Val(dwarf.Attr) interface{} +} + +type compositeEntry []*dwarf.Entry + +func (ce compositeEntry) Val(attr dwarf.Attr) interface{} { + for _, e := range ce { + if r := e.Val(attr); r != nil { + return r + } + } + return nil +} + +// LoadAbstractOrigin loads the entry corresponding to the +// DW_AT_abstract_origin of entry and returns a combination of entry and its +// abstract origin. +func LoadAbstractOrigin(entry *dwarf.Entry, aordr *dwarf.Reader) (Entry, dwarf.Offset) { + ao, ok := entry.Val(dwarf.AttrAbstractOrigin).(dwarf.Offset) + if !ok { + return entry, entry.Offset + } + + r := []*dwarf.Entry{entry} + + for { + aordr.Seek(ao) + e, _ := aordr.Next() + if e == nil { + break + } + r = append(r, e) + + ao, ok = e.Val(dwarf.AttrAbstractOrigin).(dwarf.Offset) + if !ok { + break + } + } + + return compositeEntry(r), entry.Offset +} + +// Tree represents a tree of dwarf objects. +type Tree struct { + Entry + typ Type + Tag dwarf.Tag + Offset dwarf.Offset + Ranges [][2]uint64 + Children []*Tree +} + +// LoadTree returns the tree of DIE rooted at offset 'off'. +// Abstract origins are automatically loaded, if present. +// DIE ranges are bubbled up automatically, if the child of a DIE covers a +// range of addresses that is not covered by its parent LoadTree will fix +// the parent entry. +func LoadTree(off dwarf.Offset, dw *dwarf.Data, staticBase uint64) (*Tree, error) { + rdr := dw.Reader() + rdr.Seek(off) + + e, err := rdr.Next() + if err != nil { + return nil, err + } + r := EntryToTree(e) + r.Children, err = loadTreeChildren(e, rdr) + if err != nil { + return nil, err + } + + err = r.resolveRanges(dw, staticBase) + if err != nil { + return nil, err + } + r.resolveAbstractEntries(rdr) + + return r, nil +} + +// EntryToTree converts a single entry, without children to a *Tree object +func EntryToTree(entry *dwarf.Entry) *Tree { + return &Tree{Entry: entry, Offset: entry.Offset, Tag: entry.Tag} +} + +func loadTreeChildren(e *dwarf.Entry, rdr *dwarf.Reader) ([]*Tree, error) { + if !e.Children { + return nil, nil + } + children := []*Tree{} + for { + e, err := rdr.Next() + if err != nil { + return nil, err + } + if e.Tag == 0 { + break + } + child := EntryToTree(e) + child.Children, err = loadTreeChildren(e, rdr) + if err != nil { + return nil, err + } + children = append(children, child) + } + return children, nil +} + +func (n *Tree) resolveRanges(dw *dwarf.Data, staticBase uint64) error { + var err error + n.Ranges, err = dw.Ranges(n.Entry.(*dwarf.Entry)) + if err != nil { + return err + } + for i := range n.Ranges { + n.Ranges[i][0] += staticBase + n.Ranges[i][1] += staticBase + } + n.Ranges = normalizeRanges(n.Ranges) + + for _, child := range n.Children { + err := child.resolveRanges(dw, staticBase) + if err != nil { + return err + } + n.Ranges = fuseRanges(n.Ranges, child.Ranges) + } + return nil +} + +// normalizeRanges sorts rngs by starting point and fuses overlapping entries. +func normalizeRanges(rngs [][2]uint64) [][2]uint64 { + const ( + start = 0 + end = 1 + ) + + if len(rngs) == 0 { + return rngs + } + + sort.Slice(rngs, func(i, j int) bool { + return rngs[i][start] <= rngs[j][start] + }) + + // eliminate invalid entries + out := rngs[:0] + for i := range rngs { + if rngs[i][start] < rngs[i][end] { + out = append(out, rngs[i]) + } + } + rngs = out + + // fuse overlapping entries + out = rngs[:1] + for i := 1; i < len(rngs); i++ { + cur := rngs[i] + if cur[start] <= out[len(out)-1][end] { + out[len(out)-1][end] = max(cur[end], out[len(out)-1][end]) + } else { + out = append(out, cur) + } + } + return out +} + +func max(a, b uint64) uint64 { + if a > b { + return a + } + return b +} + +// fuseRanges fuses rngs2 into rngs1, it's the equivalent of +// normalizeRanges(append(rngs1, rngs2)) +// but more efficent. +func fuseRanges(rngs1, rngs2 [][2]uint64) [][2]uint64 { + if rangesContains(rngs1, rngs2) { + return rngs1 + } + + return normalizeRanges(append(rngs1, rngs2...)) +} + +// rangesContains checks that rngs1 is a superset of rngs2. +func rangesContains(rngs1, rngs2 [][2]uint64) bool { + i, j := 0, 0 + for { + if i >= len(rngs1) { + return false + } + if j >= len(rngs2) { + return true + } + if rangeContains(rngs1[i], rngs2[j]) { + j++ + } else { + i++ + } + } +} + +// rangeContains checks that a contains b. +func rangeContains(a, b [2]uint64) bool { + return a[0] <= b[0] && a[1] >= b[1] +} + +func (n *Tree) resolveAbstractEntries(rdr *dwarf.Reader) { + n.Entry, n.Offset = LoadAbstractOrigin(n.Entry.(*dwarf.Entry), rdr) + for _, child := range n.Children { + child.resolveAbstractEntries(rdr) + } +} + +// ContainsPC returns true if the ranges of this DIE contains PC. +func (n *Tree) ContainsPC(pc uint64) bool { + for _, rng := range n.Ranges { + if rng[0] > pc { + return false + } + if rng[0] <= pc && pc < rng[1] { + return true + } + } + return false +} + +func (n *Tree) Type(dw *dwarf.Data, index int, typeCache map[dwarf.Offset]Type) (Type, error) { + if n.typ == nil { + offset, ok := n.Val(dwarf.AttrType).(dwarf.Offset) + if !ok { + return nil, fmt.Errorf("malformed variable DIE (offset)") + } + + var err error + n.typ, err = ReadType(dw, index, offset, typeCache) + if err != nil { + return nil, err + } + } + return n.typ, nil +} diff --git a/pkg/dwarf/godwarf/tree_test.go b/pkg/dwarf/godwarf/tree_test.go new file mode 100644 index 00000000..643308b3 --- /dev/null +++ b/pkg/dwarf/godwarf/tree_test.go @@ -0,0 +1,119 @@ +package godwarf + +import ( + "testing" +) + +func makeRanges(v ...uint64) [][2]uint64 { + r := make([][2]uint64, 0, len(v)/2) + for i := 0; i < len(v); i += 2 { + r = append(r, [2]uint64{v[i], v[i+1]}) + } + return r +} + +func assertRanges(t *testing.T, out, tgt [][2]uint64) { + if len(out) != len(tgt) { + t.Errorf("\nexpected:\t%v\ngot:\t\t%v", tgt, out) + } + for i := range out { + if out[i] != tgt[i] { + t.Errorf("\nexpected:\t%v\ngot:\t\t%v", tgt, out) + break + } + } +} + +func TestNormalizeRanges(t *testing.T) { + mr := makeRanges + //assertRanges(t, normalizeRanges(mr(105, 103, 90, 95, 25, 20, 20, 23)), mr(20, 23, 90, 95)) + assertRanges(t, normalizeRanges(mr(10, 12, 12, 15)), mr(10, 15)) + assertRanges(t, normalizeRanges(mr(12, 15, 10, 12)), mr(10, 15)) + assertRanges(t, normalizeRanges(mr(4910012, 4910013, 4910013, 4910098, 4910124, 4910127)), mr(4910012, 4910098, 4910124, 4910127)) +} + +func TestRangeContains(t *testing.T) { + mr := func(start, end uint64) [2]uint64 { + return [2]uint64{start, end} + } + tcs := []struct { + a, b [2]uint64 + tgt bool + }{ + {mr(1, 10), mr(1, 11), false}, + {mr(1, 10), mr(1, 1), true}, + {mr(1, 10), mr(10, 11), false}, + {mr(1, 10), mr(1, 10), true}, + {mr(1, 10), mr(2, 5), true}, + } + + for _, tc := range tcs { + if rangeContains(tc.a, tc.b) != tc.tgt { + if tc.tgt { + t.Errorf("range %v does not contan %v (but should)", tc.a, tc.b) + } else { + t.Errorf("range %v does contain %v (but shouldn't)", tc.a, tc.b) + } + } + } +} + +func TestRangesContains(t *testing.T) { + mr := makeRanges + tcs := []struct { + rngs1, rngs2 [][2]uint64 + tgt bool + }{ + {mr(1, 10), mr(1, 11), false}, + {mr(1, 10), mr(1, 1), true}, + {mr(1, 10), mr(10, 11), false}, + {mr(1, 10), mr(1, 10), true}, + {mr(1, 10), mr(2, 5), true}, + + {mr(1, 10, 20, 30), mr(1, 11), false}, + {mr(1, 10, 20, 30), mr(1, 1, 20, 22), true}, + {mr(1, 10, 20, 30), mr(30, 31), false}, + {mr(1, 10, 20, 30), mr(15, 17), false}, + {mr(1, 10, 20, 30), mr(1, 5, 6, 9, 21, 24), true}, + {mr(1, 10, 20, 30), mr(0, 1), false}, + } + + for _, tc := range tcs { + if rangesContains(tc.rngs1, tc.rngs2) != tc.tgt { + if tc.tgt { + t.Errorf("ranges %v does not contan %v (but should)", tc.rngs1, tc.rngs2) + } else { + t.Errorf("ranges %v does contain %v (but shouldn't)", tc.rngs1, tc.rngs2) + } + } + } +} + +func TestContainsPC(t *testing.T) { + mr := makeRanges + + tcs := []struct { + rngs [][2]uint64 + pc uint64 + tgt bool + }{ + {mr(1, 10), 1, true}, + {mr(1, 10), 5, true}, + {mr(1, 10), 10, false}, + {mr(1, 10, 20, 30), 15, false}, + {mr(1, 10, 20, 30), 20, true}, + {mr(1, 10, 20, 30), 30, false}, + {mr(1, 10, 20, 30), 31, false}, + } + + for _, tc := range tcs { + n := &Tree{Ranges: tc.rngs} + if n.ContainsPC(tc.pc) != tc.tgt { + if tc.tgt { + t.Errorf("ranges %v does not contain %d (but should)", tc.rngs, tc.pc) + } else { + t.Errorf("ranges %v does contain %d (but shouldn't)", tc.rngs, tc.pc) + } + } + } +} diff --git a/pkg/dwarf/reader/reader.go b/pkg/dwarf/reader/reader.go index f3118e9f..8fa99571 100644 --- a/pkg/dwarf/reader/reader.go +++ b/pkg/dwarf/reader/reader.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" + "github.com/go-delve/delve/pkg/dwarf/godwarf" "github.com/go-delve/delve/pkg/dwarf/op" ) @@ -32,37 +33,6 @@ func (reader *Reader) SeekToEntry(entry *dwarf.Entry) error { return err } -// SeekToFunctionEntry moves the reader to the function that includes the -// specified program counter. -func (reader *Reader) SeekToFunction(pc RelAddr) (*dwarf.Entry, error) { - reader.Seek(0) - for entry, err := reader.Next(); entry != nil; entry, err = reader.Next() { - if err != nil { - return nil, err - } - - if entry.Tag != dwarf.TagSubprogram { - continue - } - - lowpc, ok := entry.Val(dwarf.AttrLowpc).(uint64) - if !ok { - continue - } - - highpc, ok := entry.Val(dwarf.AttrHighpc).(uint64) - if !ok { - continue - } - - if lowpc <= uint64(pc) && highpc > uint64(pc) { - return entry, nil - } - } - - return nil, fmt.Errorf("unable to find function context") -} - // Returns the address for the named entry. func (reader *Reader) AddrFor(name string, staticBase uint64, ptrSize int) (uint64, error) { entry, err := reader.FindEntryNamed(name, false) @@ -320,79 +290,20 @@ func (reader *Reader) NextCompileUnit() (*dwarf.Entry, error) { return nil, nil } -// Entry represents a debug_info entry. -// When calling Val, if the entry does not have the specified attribute, the -// entry specified by DW_AT_abstract_origin will be searched recursively. -type Entry interface { - Val(dwarf.Attr) interface{} -} - -type compositeEntry []*dwarf.Entry - -func (ce compositeEntry) Val(attr dwarf.Attr) interface{} { - for _, e := range ce { - if r := e.Val(attr); r != nil { - return r - } - } - return nil -} - -// LoadAbstractOrigin loads the entry corresponding to the -// DW_AT_abstract_origin of entry and returns a combination of entry and its -// abstract origin. -func LoadAbstractOrigin(entry *dwarf.Entry, aordr *dwarf.Reader) (Entry, dwarf.Offset) { - ao, ok := entry.Val(dwarf.AttrAbstractOrigin).(dwarf.Offset) - if !ok { - return entry, entry.Offset - } - - r := []*dwarf.Entry{entry} - - for { - aordr.Seek(ao) - e, _ := aordr.Next() - if e == nil { - break - } - r = append(r, e) - - ao, ok = e.Val(dwarf.AttrAbstractOrigin).(dwarf.Offset) - if !ok { - break - } - } - - return compositeEntry(r), entry.Offset -} - -// InlineStackReader provides a way to read the stack of inlined calls at a -// specified PC address. -type InlineStackReader struct { - dwarf *dwarf.Data - reader *dwarf.Reader - pc uint64 - entry *dwarf.Entry - err error - - // stack contains the list of DIEs that will be returned by Next. - stack []*dwarf.Entry -} - -// InlineStack returns an InlineStackReader for the specified function and -// PC address. +// InlineStack returns the stack of inlined calls for the specified function +// and PC address. // If pc is 0 then all inlined calls will be returned. -func InlineStack(dw *dwarf.Data, fnoff dwarf.Offset, pc RelAddr) *InlineStackReader { - reader := dw.Reader() - reader.Seek(fnoff) - r := &InlineStackReader{dwarf: dw, reader: reader, pc: uint64(pc)} - r.precalcStack(nil) - return r +func InlineStack(root *godwarf.Tree, pc uint64) []*godwarf.Tree { + v := []*godwarf.Tree{} + for _, child := range root.Children { + v = inlineStackInternal(v, child, pc) + } + return v } -// precalcStack precalculates the inlined call stack for irdr.pc. -// If irdr.pc == 0 then all inlined calls will be saved in irdr.stack. -// Otherwise an inlined call will be saved in irdr.stack if its range, or +// inlineStackInternal precalculates the inlined call stack for pc +// If pc == 0 then all inlined calls will be returned +// Otherwise an inlined call will be returned if its range, or // the range of one of its child entries contains irdr.pc. // The recursive calculation of range inclusion is necessary because // sometimes when doing midstack inlining the Go compiler emits the toplevel @@ -403,77 +314,17 @@ func InlineStack(dw *dwarf.Data, fnoff dwarf.Offset, pc RelAddr) *InlineStackRea // ranges that do not cover the ranges of the inlined call to C. // This is probably a violation of the DWARF standard (it's unclear) but we // might as well support it as best as possible anyway. -func (irdr *InlineStackReader) precalcStack(rentry *dwarf.Entry) bool { - var contains bool - -childLoop: - for { - if irdr.err != nil { - return contains - } - e2, err := irdr.reader.Next() - if e2 == nil || err != nil { - break - } - - switch e2.Tag { - case 0: - break childLoop - case dwarf.TagLexDwarfBlock, dwarf.TagSubprogram, dwarf.TagInlinedSubroutine: - if irdr.precalcStack(e2) { - contains = true +func inlineStackInternal(stack []*godwarf.Tree, n *godwarf.Tree, pc uint64) []*godwarf.Tree { + switch n.Tag { + case dwarf.TagSubprogram, dwarf.TagInlinedSubroutine, dwarf.TagLexDwarfBlock: + if pc == 0 || n.ContainsPC(pc) { + for _, child := range n.Children { + stack = inlineStackInternal(stack, child, pc) } - default: - irdr.reader.SkipChildren() - } - if rentry == nil { - break - } - } - - if rentry != nil && rentry.Tag == dwarf.TagInlinedSubroutine { - if !contains { - if irdr.pc != 0 { - contains, irdr.err = entryRangesContains(irdr.dwarf, rentry, irdr.pc) - } else { - contains = true + if n.Tag == dwarf.TagInlinedSubroutine { + stack = append(stack, n) } } - if contains { - irdr.stack = append(irdr.stack, rentry) - } } - return contains -} - -// Next reads next inlined call in the stack, returns false if there aren't any. -// Next reads the inlined stack of calls backwards, starting with the -// deepest inlined call and moving back out, like a normal stacktrace works. -func (irdr *InlineStackReader) Next() bool { - if irdr.err != nil { - return false - } - - if len(irdr.stack) == 0 { - return false - } - - irdr.entry = irdr.stack[0] - irdr.stack = irdr.stack[1:] - return true -} - -// Entry returns the DIE for the current inlined call. -func (irdr *InlineStackReader) Entry() *dwarf.Entry { - return irdr.entry -} - -// Err returns an error, if any was encountered. -func (irdr *InlineStackReader) Err() error { - return irdr.err -} - -// SkipChildren skips all children of the current inlined call. -func (irdr *InlineStackReader) SkipChildren() { - irdr.reader.SkipChildren() + return stack } diff --git a/pkg/dwarf/reader/variables.go b/pkg/dwarf/reader/variables.go index d2c64a44..1035a332 100644 --- a/pkg/dwarf/reader/variables.go +++ b/pkg/dwarf/reader/variables.go @@ -1,123 +1,41 @@ package reader import ( - "errors" - "debug/dwarf" + + "github.com/go-delve/delve/pkg/dwarf/godwarf" ) -// RelAddr is an address relative to the static base. For normal executables -// this is just a normal memory address, for PIE it's a relative address. -type RelAddr uint64 - -func ToRelAddr(addr uint64, staticBase uint64) RelAddr { - return RelAddr(addr - staticBase) +type Variable struct { + *godwarf.Tree + Depth int } -// VariableReader provides a way of reading the local variables and formal -// parameters of a function that are visible at the specified PC address. -type VariableReader struct { - dwarf *dwarf.Data - reader *dwarf.Reader - entry *dwarf.Entry - depth int - pc uint64 - line int - err error - - onlyVisible bool - skipInlinedSubroutines bool +// Variables returns a list of variables contained inside 'root'. +// If onlyVisible is true only variables visible at pc will be returned. +// If skipInlinedSubroutines is true inlined subroutines will be skipped +func Variables(root *godwarf.Tree, pc uint64, line int, onlyVisible, skipInlinedSubroutines bool) []Variable { + return variablesInternal(nil, root, 0, pc, line, onlyVisible, skipInlinedSubroutines) } -// Variables returns a VariableReader for the function or lexical block at off. -// If onlyVisible is true only variables visible at pc will be returned by -// the VariableReader. -func Variables(dwarf *dwarf.Data, off dwarf.Offset, pc RelAddr, line int, onlyVisible, skipInlinedSubroutines bool) *VariableReader { - reader := dwarf.Reader() - reader.Seek(off) - return &VariableReader{dwarf: dwarf, reader: reader, entry: nil, depth: 0, onlyVisible: onlyVisible, skipInlinedSubroutines: skipInlinedSubroutines, pc: uint64(pc), line: line, err: nil} -} - -// Next reads the next variable entry, returns false if there aren't any. -func (vrdr *VariableReader) Next() bool { - if vrdr.err != nil { - return false - } - - for { - vrdr.entry, vrdr.err = vrdr.reader.Next() - if vrdr.entry == nil || vrdr.err != nil { - return false +func variablesInternal(v []Variable, root *godwarf.Tree, depth int, pc uint64, line int, onlyVisible, skipInlinedSubroutines bool) []Variable { + switch root.Tag { + case dwarf.TagInlinedSubroutine: + if skipInlinedSubroutines { + return v } - - switch vrdr.entry.Tag { - case 0: - vrdr.depth-- - if vrdr.depth == 0 { - return false - } - - case dwarf.TagInlinedSubroutine: - if vrdr.skipInlinedSubroutines { - vrdr.reader.SkipChildren() - continue - } - fallthrough - case dwarf.TagLexDwarfBlock, dwarf.TagSubprogram: - - recur := true - if vrdr.onlyVisible { - recur, vrdr.err = entryRangesContains(vrdr.dwarf, vrdr.entry, vrdr.pc) - if vrdr.err != nil { - return false - } - } - - if recur && vrdr.entry.Children { - vrdr.depth++ - } else { - if vrdr.depth == 0 { - return false - } - vrdr.reader.SkipChildren() - } - - default: - if vrdr.depth == 0 { - vrdr.err = errors.New("offset was not lexical block or subprogram") - return false - } - if declLine, ok := vrdr.entry.Val(dwarf.AttrDeclLine).(int64); !ok || vrdr.line >= int(declLine) { - return true + fallthrough + case dwarf.TagLexDwarfBlock, dwarf.TagSubprogram: + if !onlyVisible || root.ContainsPC(pc) { + for _, child := range root.Children { + v = variablesInternal(v, child, depth+1, pc, line, onlyVisible, skipInlinedSubroutines) } } - } -} - -func entryRangesContains(dwarf *dwarf.Data, entry *dwarf.Entry, pc uint64) (bool, error) { - rngs, err := dwarf.Ranges(entry) - if err != nil { - return false, err - } - for _, rng := range rngs { - if pc >= rng[0] && pc < rng[1] { - return true, nil + return v + default: + if declLine, ok := root.Val(dwarf.AttrDeclLine).(int64); !ok || line >= int(declLine) { + return append(v, Variable{root, depth}) } + return v } - return false, nil -} - -// Entry returns the current variable entry. -func (vrdr *VariableReader) Entry() *dwarf.Entry { - return vrdr.entry -} - -// Depth returns the depth of the current scope -func (vrdr *VariableReader) Depth() int { - return vrdr.depth -} - -// Err returns the error if there was one. -func (vrdr *VariableReader) Err() error { - return vrdr.err } diff --git a/pkg/proc/bininfo.go b/pkg/proc/bininfo.go index ae3da942..244820b0 100644 --- a/pkg/proc/bininfo.go +++ b/pkg/proc/bininfo.go @@ -30,6 +30,7 @@ import ( "github.com/go-delve/delve/pkg/dwarf/util" "github.com/go-delve/delve/pkg/goversion" "github.com/go-delve/delve/pkg/logflags" + "github.com/hashicorp/golang-lru/simplelru" "github.com/sirupsen/logrus" ) @@ -166,6 +167,8 @@ var supportedDarwinArch = map[macho.Cpu]bool{ const dwarfGoLanguage = 22 // DW_LANG_Go (from DWARF v5, section 7.12, page 231) +const dwarfTreeCacheSize = 512 // size of the dwarfTree cache of each image + type compileUnit struct { name string // univocal name for non-go compile units lowPC uint64 @@ -489,18 +492,16 @@ func (bi *BinaryInfo) PCToFunc(pc uint64) *Function { // If the PC address belongs to an inlined call it will return the inlined function. func (bi *BinaryInfo) PCToInlineFunc(pc uint64) *Function { fn := bi.PCToFunc(pc) - irdr := reader.InlineStack(fn.cu.image.dwarf, fn.offset, reader.ToRelAddr(pc, fn.cu.image.StaticBase)) - var inlineFnEntry *dwarf.Entry - if irdr.Next() { - inlineFnEntry = irdr.Entry() + dwarfTree, err := fn.cu.image.getDwarfTree(fn.offset) + if err != nil { + return fn } - - if inlineFnEntry == nil { + entries := reader.InlineStack(dwarfTree, pc) + if len(entries) == 0 { return fn } - e, _ := reader.LoadAbstractOrigin(inlineFnEntry, fn.cu.image.dwarfReader) - fnname, okname := e.Val(dwarf.AttrName).(string) + fnname, okname := entries[0].Val(dwarf.AttrName).(string) if !okname { return fn } @@ -531,6 +532,8 @@ type Image struct { typeCache map[dwarf.Offset]godwarf.Type + dwarfTreeCache *simplelru.LRU + // runtimeTypeToDIE maps between the offset of a runtime._type in // runtime.moduledata.types and the offset of the DIE in debug_info. This // map is filled by using the extended attribute godwarf.AttrGoRuntimeType @@ -566,6 +569,8 @@ func (bi *BinaryInfo) AddImage(path string, addr uint64) error { // Actually add the image. image := &Image{Path: path, addr: addr, typeCache: make(map[dwarf.Offset]godwarf.Type)} + image.dwarfTreeCache, _ = simplelru.NewLRU(dwarfTreeCacheSize, nil) + // add Image regardless of error so that we don't attempt to re-add it every time we stop image.index = len(bi.Images) bi.Images = append(bi.Images, image) @@ -651,6 +656,18 @@ func (image *Image) LoadError() error { return image.loadErr } +func (image *Image) getDwarfTree(off dwarf.Offset) (*godwarf.Tree, error) { + if r, ok := image.dwarfTreeCache.Get(off); ok { + return r.(*godwarf.Tree), nil + } + r, err := godwarf.LoadTree(off, image.dwarf, image.StaticBase) + if err != nil { + return nil, err + } + image.dwarfTreeCache.Add(off, r) + return r, nil +} + type nilCloser struct{} func (c *nilCloser) Close() error { return nil } @@ -663,6 +680,7 @@ func (bi *BinaryInfo) LoadImageFromData(dwdata *dwarf.Data, debugFrameBytes, deb image.sepDebugCloser = (*nilCloser)(nil) image.dwarf = dwdata image.typeCache = make(map[dwarf.Offset]godwarf.Type) + image.dwarfTreeCache, _ = simplelru.NewLRU(dwarfTreeCacheSize, nil) if debugFrameBytes != nil { bi.frameEntries = frame.Parse(debugFrameBytes, frame.DwarfEndian(debugFrameBytes), 0, bi.Arch.PtrSize()) @@ -675,7 +693,7 @@ func (bi *BinaryInfo) LoadImageFromData(dwdata *dwarf.Data, debugFrameBytes, deb bi.Images = append(bi.Images, image) } -func (bi *BinaryInfo) locationExpr(entry reader.Entry, attr dwarf.Attr, pc uint64) ([]byte, string, error) { +func (bi *BinaryInfo) locationExpr(entry godwarf.Entry, attr dwarf.Attr, pc uint64) ([]byte, string, error) { a := entry.Val(attr) if a == nil { return nil, "", fmt.Errorf("no location attribute %s", attr) @@ -743,7 +761,7 @@ func (bi *BinaryInfo) LocationCovers(entry *dwarf.Entry, attr dwarf.Attr) ([][2] // This will either be an int64 address or a slice of Pieces for locations // that don't correspond to a single memory address (registers, composite // locations). -func (bi *BinaryInfo) Location(entry reader.Entry, attr dwarf.Attr, pc uint64, regs op.DwarfRegisters) (int64, []op.Piece, string, error) { +func (bi *BinaryInfo) Location(entry godwarf.Entry, attr dwarf.Attr, pc uint64, regs op.DwarfRegisters) (int64, []op.Piece, string, error) { instr, descr, err := bi.locationExpr(entry, attr, pc) if err != nil { return 0, nil, "", err diff --git a/pkg/proc/eval.go b/pkg/proc/eval.go index 296905f7..cc23524d 100644 --- a/pkg/proc/eval.go +++ b/pkg/proc/eval.go @@ -104,12 +104,16 @@ func (scope *EvalScope) Locals() ([]*Variable, error) { trustArgOrder := scope.BinInfo.Producer() != "" && goversion.ProducerAfterOrEqual(scope.BinInfo.Producer(), 1, 12) - var vars []*Variable - var depths []int - varReader := reader.Variables(scope.image().dwarf, scope.Fn.offset, reader.ToRelAddr(scope.PC, scope.image().StaticBase), scope.Line, true, false) - for varReader.Next() { - entry := varReader.Entry() - val, err := extractVarInfoFromEntry(scope.BinInfo, scope.image(), scope.Regs, scope.Mem, entry) + dwarfTree, err := scope.image().getDwarfTree(scope.Fn.offset) + if err != nil { + return nil, err + } + + varEntries := reader.Variables(dwarfTree, scope.PC, scope.Line, true, false) + vars := make([]*Variable, 0, len(varEntries)) + depths := make([]int, 0, len(varEntries)) + for _, entry := range varEntries { + val, err := extractVarInfoFromEntry(scope.BinInfo, scope.image(), scope.Regs, scope.Mem, entry.Tree) if err != nil { // skip variables that we can't parse yet continue @@ -123,7 +127,7 @@ func (scope *EvalScope) Locals() ([]*Variable, error) { val = newVariable(val.Name, addr, val.DwarfType, scope.BinInfo, scope.Mem) } vars = append(vars, val) - depth := varReader.Depth() + depth := entry.Depth if entry.Tag == dwarf.TagFormalParameter { if depth <= 1 { depth = 0 @@ -138,10 +142,6 @@ func (scope *EvalScope) Locals() ([]*Variable, error) { depths = append(depths, depth) } - if err := varReader.Err(); err != nil { - return nil, err - } - if len(vars) <= 0 { return vars, nil } @@ -367,7 +367,7 @@ func (scope *EvalScope) PackageVariables(cfg LoadConfig) ([]*Variable, error) { } // Ignore errors trying to extract values - val, err := extractVarInfoFromEntry(scope.BinInfo, image, regsReplaceStaticBase(scope.Regs, image), scope.Mem, entry) + val, err := extractVarInfoFromEntry(scope.BinInfo, image, regsReplaceStaticBase(scope.Regs, image), scope.Mem, godwarf.EntryToTree(entry)) if err != nil { continue } @@ -402,7 +402,7 @@ func (scope *EvalScope) findGlobalInternal(name string) (*Variable, error) { if err != nil { return nil, err } - return extractVarInfoFromEntry(scope.BinInfo, pkgvar.cu.image, regsReplaceStaticBase(scope.Regs, pkgvar.cu.image), scope.Mem, entry) + return extractVarInfoFromEntry(scope.BinInfo, pkgvar.cu.image, regsReplaceStaticBase(scope.Regs, pkgvar.cu.image), scope.Mem, godwarf.EntryToTree(entry)) } } for _, fn := range scope.BinInfo.Functions { diff --git a/pkg/proc/fncall.go b/pkg/proc/fncall.go index 9ec3a8f4..e2005aa3 100644 --- a/pkg/proc/fncall.go +++ b/pkg/proc/fncall.go @@ -520,17 +520,22 @@ func funcCallCopyOneArg(scope *EvalScope, fncall *functionCallState, actualArg * func funcCallArgs(fn *Function, bi *BinaryInfo, includeRet bool) (argFrameSize int64, formalArgs []funcCallArg, err error) { const CFA = 0x1000 - vrdr := reader.Variables(fn.cu.image.dwarf, fn.offset, reader.ToRelAddr(fn.Entry, fn.cu.image.StaticBase), int(^uint(0)>>1), false, true) + + dwarfTree, err := fn.cu.image.getDwarfTree(fn.offset) + if err != nil { + return 0, nil, fmt.Errorf("DWARF read error: %v", err) + } + + varEntries := reader.Variables(dwarfTree, fn.Entry, int(^uint(0)>>1), false, true) trustArgOrder := bi.Producer() != "" && goversion.ProducerAfterOrEqual(bi.Producer(), 1, 12) // typechecks arguments, calculates argument frame size - for vrdr.Next() { - e := vrdr.Entry() - if e.Tag != dwarf.TagFormalParameter { + for _, entry := range varEntries { + if entry.Tag != dwarf.TagFormalParameter { continue } - entry, argname, typ, err := readVarEntry(e, fn.cu.image) + argname, typ, err := readVarEntry(entry.Tree, fn.cu.image) if err != nil { return 0, nil, err } @@ -574,9 +579,6 @@ func funcCallArgs(fn *Function, bi *BinaryInfo, includeRet bool) (argFrameSize i formalArgs = append(formalArgs, funcCallArg{name: argname, typ: typ, off: off, isret: isret}) } } - if err := vrdr.Err(); err != nil { - return 0, nil, fmt.Errorf("DWARF read error: %v", err) - } sort.Slice(formalArgs, func(i, j int) bool { return formalArgs[i].off < formalArgs[j].off diff --git a/pkg/proc/stack.go b/pkg/proc/stack.go index 0efb92f7..e3182d4e 100644 --- a/pkg/proc/stack.go +++ b/pkg/proc/stack.go @@ -287,13 +287,11 @@ func (it *stackIterator) Err() error { // frameBase calculates the frame base pseudo-register for DWARF for fn and // the current frame. func (it *stackIterator) frameBase(fn *Function) int64 { - rdr := fn.cu.image.dwarfReader - rdr.Seek(fn.offset) - e, err := rdr.Next() + dwarfTree, err := fn.cu.image.getDwarfTree(fn.offset) if err != nil { return 0 } - fb, _, _, _ := it.bi.Location(e, dwarf.AttrFrameBase, it.pc, it.regs) + fb, _, _, _ := it.bi.Location(dwarfTree.Entry, dwarf.AttrFrameBase, it.pc, it.regs) return fb } @@ -366,12 +364,12 @@ func (it *stackIterator) appendInlineCalls(frames []Stackframe, frame Stackframe callpc-- } - image := frame.Call.Fn.cu.image - - irdr := reader.InlineStack(image.dwarf, frame.Call.Fn.offset, reader.ToRelAddr(callpc, image.StaticBase)) - for irdr.Next() { - entry, offset := reader.LoadAbstractOrigin(irdr.Entry(), image.dwarfReader) + dwarfTree, err := frame.Call.Fn.cu.image.getDwarfTree(frame.Call.Fn.offset) + if err != nil { + return append(frames, frame) + } + for _, entry := range reader.InlineStack(dwarfTree, callpc) { fnname, okname := entry.Val(dwarf.AttrName).(string) fileidx, okfileidx := entry.Val(dwarf.AttrCallFile).(int64) line, okline := entry.Val(dwarf.AttrCallLine).(int64) @@ -383,7 +381,7 @@ func (it *stackIterator) appendInlineCalls(frames []Stackframe, frame Stackframe break } - inlfn := &Function{Name: fnname, Entry: frame.Call.Fn.Entry, End: frame.Call.Fn.End, offset: offset, cu: frame.Call.Fn.cu} + inlfn := &Function{Name: fnname, Entry: frame.Call.Fn.Entry, End: frame.Call.Fn.End, offset: entry.Offset, cu: frame.Call.Fn.cu} frames = append(frames, Stackframe{ Current: frame.Current, Call: Location{ diff --git a/pkg/proc/threads.go b/pkg/proc/threads.go index 613e6b59..cfa9a157 100644 --- a/pkg/proc/threads.go +++ b/pkg/proc/threads.go @@ -398,30 +398,25 @@ func FindDeferReturnCalls(text []AsmInstruction) []uint64 { // If includeCurrentFn is true it will also remove all instructions // belonging to the current function. func removeInlinedCalls(dbp Process, pcs []uint64, topframe Stackframe) ([]uint64, error) { - image := topframe.Call.Fn.cu.image - dwarf := image.dwarf - irdr := reader.InlineStack(dwarf, topframe.Call.Fn.offset, 0) - for irdr.Next() { - e := irdr.Entry() + dwarfTree, err := topframe.Call.Fn.cu.image.getDwarfTree(topframe.Call.Fn.offset) + if err != nil { + return pcs, err + } + for _, e := range reader.InlineStack(dwarfTree, 0) { if e.Offset == topframe.Call.Fn.offset { continue } - ranges, err := dwarf.Ranges(e) - if err != nil { - return pcs, err + for _, rng := range e.Ranges { + pcs = removePCsBetween(pcs, rng[0], rng[1]) } - for _, rng := range ranges { - pcs = removePCsBetween(pcs, rng[0], rng[1], image.StaticBase) - } - irdr.SkipChildren() } - return pcs, irdr.Err() + return pcs, nil } -func removePCsBetween(pcs []uint64, start, end, staticBase uint64) []uint64 { +func removePCsBetween(pcs []uint64, start, end uint64) []uint64 { out := pcs[:0] for _, pc := range pcs { - if pc < start+staticBase || pc >= end+staticBase { + if pc < start || pc >= end { out = append(out, pc) } } diff --git a/pkg/proc/variables.go b/pkg/proc/variables.go index 17052e96..9b800f1c 100644 --- a/pkg/proc/variables.go +++ b/pkg/proc/variables.go @@ -16,7 +16,6 @@ import ( "github.com/go-delve/delve/pkg/dwarf/godwarf" "github.com/go-delve/delve/pkg/dwarf/op" - "github.com/go-delve/delve/pkg/dwarf/reader" "github.com/go-delve/delve/pkg/goversion" ) @@ -841,39 +840,28 @@ func (v *Variable) structMember(memberName string) (*Variable, error) { } } -func readVarEntry(varEntry *dwarf.Entry, image *Image) (entry reader.Entry, name string, typ godwarf.Type, err error) { - entry, _ = reader.LoadAbstractOrigin(varEntry, image.dwarfReader) - +func readVarEntry(entry *godwarf.Tree, image *Image) (name string, typ godwarf.Type, err error) { name, ok := entry.Val(dwarf.AttrName).(string) if !ok { - return nil, "", nil, fmt.Errorf("malformed variable DIE (name)") + return "", nil, fmt.Errorf("malformed variable DIE (name)") } - offset, ok := entry.Val(dwarf.AttrType).(dwarf.Offset) - if !ok { - return nil, "", nil, fmt.Errorf("malformed variable DIE (offset)") - } - - typ, err = image.Type(offset) + typ, err = entry.Type(image.dwarf, image.index, image.typeCache) if err != nil { - return nil, "", nil, err + return "", nil, err } - return entry, name, typ, nil + return name, typ, nil } // Extracts the name and type of a variable from a dwarf entry // then executes the instructions given in the DW_AT_location attribute to grab the variable's address -func extractVarInfoFromEntry(bi *BinaryInfo, image *Image, regs op.DwarfRegisters, mem MemoryReadWriter, varEntry *dwarf.Entry) (*Variable, error) { - if varEntry == nil { - return nil, fmt.Errorf("invalid entry") +func extractVarInfoFromEntry(bi *BinaryInfo, image *Image, regs op.DwarfRegisters, mem MemoryReadWriter, entry *godwarf.Tree) (*Variable, error) { + if entry.Tag != dwarf.TagFormalParameter && entry.Tag != dwarf.TagVariable { + return nil, fmt.Errorf("invalid entry tag, only supports FormalParameter and Variable, got %s", entry.Tag.String()) } - if varEntry.Tag != dwarf.TagFormalParameter && varEntry.Tag != dwarf.TagVariable { - return nil, fmt.Errorf("invalid entry tag, only supports FormalParameter and Variable, got %s", varEntry.Tag.String()) - } - - entry, n, t, err := readVarEntry(varEntry, image) + n, t, err := readVarEntry(entry, image) if err != nil { return nil, err } diff --git a/vendor/github.com/hashicorp/golang-lru/LICENSE b/vendor/github.com/hashicorp/golang-lru/LICENSE new file mode 100644 index 00000000..be2cc4df --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/LICENSE @@ -0,0 +1,362 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. + +1.8. "License" + + means this document. + +1.9. "Licensable" + + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. + +1.10. "Modifications" + + means any of the following: + + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. + +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, "control" means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. + + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by + the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go new file mode 100644 index 00000000..a86c8539 --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go @@ -0,0 +1,177 @@ +package simplelru + +import ( + "container/list" + "errors" +) + +// EvictCallback is used to get a callback when a cache entry is evicted +type EvictCallback func(key interface{}, value interface{}) + +// LRU implements a non-thread safe fixed size LRU cache +type LRU struct { + size int + evictList *list.List + items map[interface{}]*list.Element + onEvict EvictCallback +} + +// entry is used to hold a value in the evictList +type entry struct { + key interface{} + value interface{} +} + +// NewLRU constructs an LRU of the given size +func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { + if size <= 0 { + return nil, errors.New("Must provide a positive size") + } + c := &LRU{ + size: size, + evictList: list.New(), + items: make(map[interface{}]*list.Element), + onEvict: onEvict, + } + return c, nil +} + +// Purge is used to completely clear the cache. +func (c *LRU) Purge() { + for k, v := range c.items { + if c.onEvict != nil { + c.onEvict(k, v.Value.(*entry).value) + } + delete(c.items, k) + } + c.evictList.Init() +} + +// Add adds a value to the cache. Returns true if an eviction occurred. +func (c *LRU) Add(key, value interface{}) (evicted bool) { + // Check for existing item + if ent, ok := c.items[key]; ok { + c.evictList.MoveToFront(ent) + ent.Value.(*entry).value = value + return false + } + + // Add new item + ent := &entry{key, value} + entry := c.evictList.PushFront(ent) + c.items[key] = entry + + evict := c.evictList.Len() > c.size + // Verify size not exceeded + if evict { + c.removeOldest() + } + return evict +} + +// Get looks up a key's value from the cache. +func (c *LRU) Get(key interface{}) (value interface{}, ok bool) { + if ent, ok := c.items[key]; ok { + c.evictList.MoveToFront(ent) + if ent.Value.(*entry) == nil { + return nil, false + } + return ent.Value.(*entry).value, true + } + return +} + +// Contains checks if a key is in the cache, without updating the recent-ness +// or deleting it for being stale. +func (c *LRU) Contains(key interface{}) (ok bool) { + _, ok = c.items[key] + return ok +} + +// Peek returns the key value (or undefined if not found) without updating +// the "recently used"-ness of the key. +func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { + var ent *list.Element + if ent, ok = c.items[key]; ok { + return ent.Value.(*entry).value, true + } + return nil, ok +} + +// Remove removes the provided key from the cache, returning if the +// key was contained. +func (c *LRU) Remove(key interface{}) (present bool) { + if ent, ok := c.items[key]; ok { + c.removeElement(ent) + return true + } + return false +} + +// RemoveOldest removes the oldest item from the cache. +func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) { + ent := c.evictList.Back() + if ent != nil { + c.removeElement(ent) + kv := ent.Value.(*entry) + return kv.key, kv.value, true + } + return nil, nil, false +} + +// GetOldest returns the oldest entry +func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) { + ent := c.evictList.Back() + if ent != nil { + kv := ent.Value.(*entry) + return kv.key, kv.value, true + } + return nil, nil, false +} + +// Keys returns a slice of the keys in the cache, from oldest to newest. +func (c *LRU) Keys() []interface{} { + keys := make([]interface{}, len(c.items)) + i := 0 + for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() { + keys[i] = ent.Value.(*entry).key + i++ + } + return keys +} + +// Len returns the number of items in the cache. +func (c *LRU) Len() int { + return c.evictList.Len() +} + +// Resize changes the cache size. +func (c *LRU) Resize(size int) (evicted int) { + diff := c.Len() - size + if diff < 0 { + diff = 0 + } + for i := 0; i < diff; i++ { + c.removeOldest() + } + c.size = size + return diff +} + +// removeOldest removes the oldest item from the cache. +func (c *LRU) removeOldest() { + ent := c.evictList.Back() + if ent != nil { + c.removeElement(ent) + } +} + +// removeElement is used to remove a given list element from the cache +func (c *LRU) removeElement(e *list.Element) { + c.evictList.Remove(e) + kv := e.Value.(*entry) + delete(c.items, kv.key) + if c.onEvict != nil { + c.onEvict(kv.key, kv.value) + } +} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go new file mode 100644 index 00000000..a0b97e3f --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go @@ -0,0 +1,39 @@ +package simplelru + +// LRUCache is the interface for simple LRU cache. +type LRUCache interface { + // Adds a value to the cache, returns true if an eviction occurred and + // updates the "recently used"-ness of the key. + Add(key, value interface{}) bool + + // Returns key's value from the cache and + // updates the "recently used"-ness of the key. #value, isFound + Get(key interface{}) (value interface{}, ok bool) + + // Checks if a key exists in cache without updating the recent-ness. + Contains(key interface{}) (ok bool) + + // Returns key's value without updating the "recently used"-ness of the key. + Peek(key interface{}) (value interface{}, ok bool) + + // Removes a key from the cache. + Remove(key interface{}) bool + + // Removes the oldest entry from cache. + RemoveOldest() (interface{}, interface{}, bool) + + // Returns the oldest entry from the cache. #key, value, isFound + GetOldest() (interface{}, interface{}, bool) + + // Returns a slice of the keys in the cache, from oldest to newest. + Keys() []interface{} + + // Returns the number of items in the cache. + Len() int + + // Clears all cache entries. + Purge() + + // Resizes cache, returning number evicted + Resize(int) int +}