<|start_filename|>service/rpccommon/sameuser.go<|end_filename|>
//+build !linux

package rpccommon

import "net"

func canAccept(_, _ net.Addr) bool {
	return true
}


<|start_filename|>_fixtures/testvariablescgo/testvariablescgo.go<|end_filename|>
package main

// #cgo CFLAGS: -g -Wall -O0 -std=gnu99
/*
extern void testfn(void);
*/
import "C"

func main() {
	C.testfn()
}


<|start_filename|>_fixtures/issue1795.go<|end_filename|>
package main

import (
	"fmt"
	"regexp"
	"runtime"
)

func main() {
	r := regexp.MustCompile("ab")
	runtime.Breakpoint()
	out := r.MatchString("blah")
	fmt.Printf("%v\n", out)
}


<|start_filename|>vendor/github.com/cosiner/argv/argv.go<|end_filename|>
// Package argv parse command line string into arguments array using the bash syntax.
package argv

// Argv split cmdline string as array of argument array by the '|' character.
//
// The parsing rules is same as bash. The environment variable will be replaced
// and string surround by '`' will be passed to reverse quote parser.
func Argv(cmdline string, backquoteExpander, stringExpander Expander) ([][]string, error) {
	return NewParser(NewScanner(cmdline), backquoteExpander, stringExpander).Parse()
}


<|start_filename|>pkg/proc/linutil/auxv.go<|end_filename|>
package linutil

import (
	"bytes"
	"encoding/binary"
)

const (
	_AT_NULL  = 0
	_AT_ENTRY = 9
)

// EntryPointFromAuxv searches the elf auxiliary vector for the entry point
// address.
// For a description of the auxiliary vector (auxv) format see:
// System V Application Binary Interface, AMD64 Architecture Processor
// Supplement, section 3.4.3.
// System V Application Binary Interface, Intel386 Architecture Processor
// Supplement (fourth edition), section 3-28.
func EntryPointFromAuxv(auxv []byte, ptrSize int) uint64 {
	rd := bytes.NewBuffer(auxv)

	for {
		tag, err := readUintRaw(rd, binary.LittleEndian, ptrSize)
		if err != nil {
			return 0
		}
		val, err := readUintRaw(rd, binary.LittleEndian, ptrSize)
		if err != nil {
			return 0
		}

		switch tag {
		case _AT_NULL:
			return 0
		case _AT_ENTRY:
			return val
		}
	}
}


<|start_filename|>pkg/proc/amd64util/xsave_other.go<|end_filename|>
//+build !amd64

package amd64util

func AMD64XstateMaxSize() int {
	return _XSTATE_MAX_KNOWN_SIZE
}


<|start_filename|>_fixtures/redirect.go<|end_filename|>
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"time"
)

func main() {
	buf, _ := ioutil.ReadAll(os.Stdin)
	fmt.Fprintf(os.Stdout, "%s %v\n", buf, time.Now())
}


<|start_filename|>pkg/proc/pe.go<|end_filename|>
package proc

import (
	"fmt"
)

const (
	IMAGE_FILE_MACHINE_UNKNOWN   = 0x0
	IMAGE_FILE_MACHINE_AM33      = 0x1d3
	IMAGE_FILE_MACHINE_AMD64     = 0x8664
	IMAGE_FILE_MACHINE_ARM       = 0x1c0
	IMAGE_FILE_MACHINE_ARMNT     = 0x1c4
	IMAGE_FILE_MACHINE_ARM64     = 0xaa64
	IMAGE_FILE_MACHINE_EBC       = 0xebc
	IMAGE_FILE_MACHINE_I386      = 0x14c
	IMAGE_FILE_MACHINE_IA64      = 0x200
	IMAGE_FILE_MACHINE_M32R      = 0x9041
	IMAGE_FILE_MACHINE_MIPS16    = 0x266
	IMAGE_FILE_MACHINE_MIPSFPU   = 0x366
	IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466
	IMAGE_FILE_MACHINE_POWERPC   = 0x1f0
	IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1
	IMAGE_FILE_MACHINE_R4000     = 0x166
	IMAGE_FILE_MACHINE_SH3       = 0x1a2
	IMAGE_FILE_MACHINE_SH3DSP    = 0x1a3
	IMAGE_FILE_MACHINE_SH4       = 0x1a6
	IMAGE_FILE_MACHINE_SH5       = 0x1a8
	IMAGE_FILE_MACHINE_THUMB     = 0x1c2
	IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169
)

type PEMachine uint16

// PEMachineString map pe machine to name, See $GOROOT/src/debug/pe/pe.go for detail
var PEMachineString = map[uint16]string{
	IMAGE_FILE_MACHINE_UNKNOWN:   "unknown",
	IMAGE_FILE_MACHINE_AM33:      "am33",
	IMAGE_FILE_MACHINE_AMD64:     "amd64",
	IMAGE_FILE_MACHINE_ARM:       "arm",
	IMAGE_FILE_MACHINE_ARMNT:     "armnt",
	IMAGE_FILE_MACHINE_ARM64:     "arm64",
	IMAGE_FILE_MACHINE_EBC:       "ebc",
	IMAGE_FILE_MACHINE_I386:      "i386",
	IMAGE_FILE_MACHINE_IA64:      "ia64",
	IMAGE_FILE_MACHINE_M32R:      "m32r",
	IMAGE_FILE_MACHINE_MIPS16:    "mips16",
	IMAGE_FILE_MACHINE_MIPSFPU:   "mipsfpu",
	IMAGE_FILE_MACHINE_MIPSFPU16: "mipsfpu16",
	IMAGE_FILE_MACHINE_POWERPC:   "powerpc",
	IMAGE_FILE_MACHINE_POWERPCFP: "powerpcfp",
	IMAGE_FILE_MACHINE_R4000:     "r4000",
	IMAGE_FILE_MACHINE_SH3:       "sh3",
	IMAGE_FILE_MACHINE_SH3DSP:    "sh3dsp",
	IMAGE_FILE_MACHINE_SH4:       "sh4",
	IMAGE_FILE_MACHINE_SH5:       "sh5",
	IMAGE_FILE_MACHINE_THUMB:     "thumb",
	IMAGE_FILE_MACHINE_WCEMIPSV2: "wcemipsv2",
}

func (m PEMachine) String() string {
	str, ok := PEMachineString[uint16(m)]
	if ok {
		return str
	}
	return fmt.Sprintf("unkown image file machine code %d\n", uint16(m))
}


<|start_filename|>pkg/dwarf/loclist/dwarf5_loclist.go<|end_filename|>
package loclist

import (
	"bytes"
	"encoding/binary"
	"fmt"

	"github.com/go-delve/delve/pkg/dwarf/godwarf"
	"github.com/go-delve/delve/pkg/dwarf/util"
)

// Dwarf5Reader parses and presents DWARF loclist information for DWARF version 5 and later.
// See DWARFv5 section 7.29 page 243 and following.
type Dwarf5Reader struct {
	byteOrder binary.ByteOrder
	ptrSz     int
	data      []byte
}

func NewDwarf5Reader(data []byte) *Dwarf5Reader {
	if len(data) == 0 {
		return nil
	}
	r := &Dwarf5Reader{data: data}

	_, dwarf64, _, byteOrder := util.ReadDwarfLengthVersion(data)
	r.byteOrder = byteOrder

	data = data[6:]
	if dwarf64 {
		data = data[8:]
	}

	addrSz := data[0]
	segSelSz := data[1]
	r.ptrSz = int(addrSz + segSelSz)

	// Not read:
	// - offset_entry_count (4 bytes)
	// - offset table (offset_entry_count*4 or offset_entry_count*8 if dwarf64 is set)

	return r
}

func (rdr *Dwarf5Reader) Empty() bool {
	return rdr == nil
}

// Find returns the loclist entry for the specified PC address, inside the
// loclist stating at off. Base is the base address of the compile unit and
// staticBase is the static base at which the image is loaded.
func (rdr *Dwarf5Reader) Find(off int, staticBase, base, pc uint64, debugAddr *godwarf.DebugAddr) (*Entry, error) {
	it := &loclistsIterator{rdr: rdr, debugAddr: debugAddr, buf: bytes.NewBuffer(rdr.data), base: base, staticBase: staticBase}
	it.buf.Next(off)

	for it.next() {
		if !it.onRange {
			continue
		}
		if it.start <= pc && pc < it.end {
			return &Entry{it.start, it.end, it.instr}, nil
		}
	}

	if it.err != nil {
		return nil, it.err
	}

	if it.defaultInstr != nil {
		return &Entry{pc, pc + 1, it.defaultInstr}, nil
	}

	return nil, nil
}

type loclistsIterator struct {
	rdr        *Dwarf5Reader
	debugAddr  *godwarf.DebugAddr
	buf        *bytes.Buffer
	staticBase uint64
	base       uint64 // base for offsets in the list

	onRange      bool
	atEnd        bool
	start, end   uint64
	instr        []byte
	defaultInstr []byte
	err          error
}

const (
	_DW_LLE_end_of_list      uint8 = 0x0
	_DW_LLE_base_addressx    uint8 = 0x1
	_DW_LLE_startx_endx      uint8 = 0x2
	_DW_LLE_startx_length    uint8 = 0x3
	_DW_LLE_offset_pair      uint8 = 0x4
	_DW_LLE_default_location uint8 = 0x5
	_DW_LLE_base_address     uint8 = 0x6
	_DW_LLE_start_end        uint8 = 0x7
	_DW_LLE_start_length     uint8 = 0x8
)

func (it *loclistsIterator) next() bool {
	if it.err != nil || it.atEnd {
		return false
	}
	opcode, err := it.buf.ReadByte()
	if err != nil {
		it.err = err
		return false
	}
	switch opcode {
	case _DW_LLE_end_of_list:
		it.atEnd = true
		it.onRange = false
		return false

	case _DW_LLE_base_addressx:
		baseIdx, _ := util.DecodeULEB128(it.buf)
		if err != nil {
			it.err = err
			return false
		}
		it.base, it.err = it.debugAddr.Get(baseIdx)
		it.base += it.staticBase
		it.onRange = false

	case _DW_LLE_startx_endx:
		startIdx, _ := util.DecodeULEB128(it.buf)
		endIdx, _ := util.DecodeULEB128(it.buf)
		it.readInstr()

		it.start, it.err = it.debugAddr.Get(startIdx)
		if it.err == nil {
			it.end, it.err = it.debugAddr.Get(endIdx)
		}
		it.onRange = true

	case _DW_LLE_startx_length:
		startIdx, _ := util.DecodeULEB128(it.buf)
		length, _ := util.DecodeULEB128(it.buf)
		it.readInstr()

		it.start, it.err = it.debugAddr.Get(startIdx)
		it.end = it.start + length
		it.onRange = true

	case _DW_LLE_offset_pair:
		off1, _ := util.DecodeULEB128(it.buf)
		off2, _ := util.DecodeULEB128(it.buf)
		it.readInstr()

		it.start = it.base + off1
		it.end = it.base + off2
		it.onRange = true

	case _DW_LLE_default_location:
		it.readInstr()
		it.defaultInstr = it.instr
		it.onRange = false

	case _DW_LLE_base_address:
		it.base, it.err = util.ReadUintRaw(it.buf, it.rdr.byteOrder, it.rdr.ptrSz)
		it.base += it.staticBase
		it.onRange = false

	case _DW_LLE_start_end:
		it.start, it.err = util.ReadUintRaw(it.buf, it.rdr.byteOrder, it.rdr.ptrSz)
		it.end, it.err = util.ReadUintRaw(it.buf, it.rdr.byteOrder, it.rdr.ptrSz)
		it.readInstr()
		it.onRange = true

	case _DW_LLE_start_length:
		it.start, it.err = util.ReadUintRaw(it.buf, it.rdr.byteOrder, it.rdr.ptrSz)
		length, _ := util.DecodeULEB128(it.buf)
		it.readInstr()
		it.end = it.start + length
		it.onRange = true

	default:
		it.err = fmt.Errorf("unknown opcode %#x at %#x", opcode, len(it.rdr.data)-it.buf.Len())
		it.onRange = false
		it.atEnd = true
		return false
	}

	return true
}

func (it *loclistsIterator) readInstr() {
	length, _ := util.DecodeULEB128(it.buf)
	it.instr = it.buf.Next(int(length))
}


<|start_filename|>_fixtures/ifaceembcall.go<|end_filename|>
package main

import "fmt"

type A struct {
	a int
}

type B struct {
	*A
}

type Iface interface {
	PtrReceiver() string
	NonPtrReceiver() string
}

func (*A) PtrReceiver() string {
	return "blah"
}

func (A) NonPtrReceiver() string {
	return "blah"
}

func main() {
	var iface Iface = &B{&A{1}}
	s := iface.PtrReceiver()
	s = iface.NonPtrReceiver()
	fmt.Printf("%s\n", s)
}


<|start_filename|>_fixtures/issue2023.go<|end_filename|>
package main

import (
	"fmt"
	"time"
)

func A() {
	fmt.Printf("hello delve\n")
}

func main() {
	count := 0
	for {
		A()
		time.Sleep(time.Millisecond * time.Duration(100))
		if count >= 30 {
			break
		}
		count++
	}
}


<|start_filename|>pkg/proc/native/ptrace_linux_64bit.go<|end_filename|>
// +build linux,amd64 linux,arm64

package native

import (
	"syscall"
	"unsafe"

	sys "golang.org/x/sys/unix"
)

// processVmRead calls process_vm_readv
func processVmRead(tid int, addr uintptr, data []byte) (int, error) {
	len_iov := uint64(len(data))
	local_iov := sys.Iovec{Base: &data[0], Len: len_iov}
	remote_iov := sys.Iovec{Base: (*byte)(unsafe.Pointer(addr)), Len: len_iov}
	p_local := uintptr(unsafe.Pointer(&local_iov))
	p_remote := uintptr(unsafe.Pointer(&remote_iov))
	n, _, err := syscall.Syscall6(sys.SYS_PROCESS_VM_READV, uintptr(tid), p_local, 1, p_remote, 1, 0)
	if err != syscall.Errno(0) {
		return 0, err
	}
	return int(n), nil
}

// processVmWrite calls process_vm_writev
func processVmWrite(tid int, addr uintptr, data []byte) (int, error) {
	len_iov := uint64(len(data))
	local_iov := sys.Iovec{Base: &data[0], Len: len_iov}
	remote_iov := sys.Iovec{Base: (*byte)(unsafe.Pointer(addr)), Len: len_iov}
	p_local := uintptr(unsafe.Pointer(&local_iov))
	p_remote := uintptr(unsafe.Pointer(&remote_iov))
	n, _, err := syscall.Syscall6(sys.SYS_PROCESS_VM_WRITEV, uintptr(tid), p_local, 1, p_remote, 1, 0)
	if err != syscall.Errno(0) {
		return 0, err
	}
	return int(n), nil
}


<|start_filename|>pkg/dwarf/util/buf.go<|end_filename|>
// Copyright 2009 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.

// Buffered reading and decoding of DWARF data streams.

package util

import (
	"debug/dwarf"
	"fmt"
)

// Data buffer being decoded.
type buf struct {
	dwarf  *dwarf.Data
	format dataFormat
	name   string
	off    dwarf.Offset
	data   []byte
	Err    error
}

// Data format, other than byte order.  This affects the handling of
// certain field formats.
type dataFormat interface {
	// DWARF version number.  Zero means unknown.
	version() int

	// 64-bit DWARF format?
	dwarf64() (dwarf64 bool, isKnown bool)

	// Size of an address, in bytes.  Zero means unknown.
	addrsize() int
}

// Some parts of DWARF have no data format, e.g., abbrevs.
type UnknownFormat struct{}

func (u UnknownFormat) version() int {
	return 0
}

func (u UnknownFormat) dwarf64() (bool, bool) {
	return false, false
}

func (u UnknownFormat) addrsize() int {
	return 0
}

func MakeBuf(d *dwarf.Data, format dataFormat, name string, off dwarf.Offset, data []byte) buf {
	return buf{d, format, name, off, data, nil}
}

func (b *buf) slice(length int) buf {
	n := *b
	data := b.data
	b.skip(length) // Will validate length.
	n.data = data[:length]
	return n
}

func (b *buf) Uint8() uint8 {
	if len(b.data) < 1 {
		b.error("underflow")
		return 0
	}
	val := b.data[0]
	b.data = b.data[1:]
	b.off++
	return val
}

func (b *buf) bytes(n int) []byte {
	if len(b.data) < n {
		b.error("underflow")
		return nil
	}
	data := b.data[0:n]
	b.data = b.data[n:]
	b.off += dwarf.Offset(n)
	return data
}

func (b *buf) skip(n int) { b.bytes(n) }

// string returns the NUL-terminated (C-like) string at the start of the buffer.
// The terminal NUL is discarded.
func (b *buf) string() string {
	for i := 0; i < len(b.data); i++ {
		if b.data[i] == 0 {
			s := string(b.data[0:i])
			b.data = b.data[i+1:]
			b.off += dwarf.Offset(i + 1)
			return s
		}
	}
	b.error("underflow")
	return ""
}

// Read a varint, which is 7 bits per byte, little endian.
// the 0x80 bit means read another byte.
func (b *buf) Varint() (c uint64, bits uint) {
	for i := 0; i < len(b.data); i++ {
		byte := b.data[i]
		c |= uint64(byte&0x7F) << bits
		bits += 7
		if byte&0x80 == 0 {
			b.off += dwarf.Offset(i + 1)
			b.data = b.data[i+1:]
			return c, bits
		}
	}
	return 0, 0
}

// Unsigned int is just a varint.
func (b *buf) Uint() uint64 {
	x, _ := b.Varint()
	return x
}

// Signed int is a sign-extended varint.
func (b *buf) Int() int64 {
	ux, bits := b.Varint()
	x := int64(ux)
	if x&(1<<(bits-1)) != 0 {
		x |= -1 << bits
	}
	return x
}

// AssertEmpty checks that everything has been read from b.
func (b *buf) AssertEmpty() {
	if len(b.data) == 0 {
		return
	}
	if len(b.data) > 5 {
		b.error(fmt.Sprintf("unexpected extra data: %x...", b.data[0:5]))
	}
	b.error(fmt.Sprintf("unexpected extra data: %x", b.data))
}

func (b *buf) error(s string) {
	if b.Err == nil {
		b.data = nil
		b.Err = dwarf.DecodeError{Name: b.name, Offset: b.off, Err: s}
	}
}


<|start_filename|>service/api/prettyprint_test.go<|end_filename|>
package api

import (
	"fmt"
	"math"
	"strings"
	"testing"
)

func TestPrettyExamineMemory(t *testing.T) {
	// Test whether always use the last addr's len to format when the lens of two adjacent address are different
	addr := uintptr(0xffff)
	memArea := []byte("abcdefghijklmnopqrstuvwxyz")
	format := byte('o')

	display := []string{
		"0x0ffff:   0141   0142   0143   0144   0145   0146   0147   0150   ",
		"0x10007:   0151   0152   0153   0154   0155   0156   0157   0160   ",
		"0x1000f:   0161   0162   0163   0164   0165   0166   0167   0170   ",
		"0x10017:   0171   0172"}
	res := strings.Split(strings.TrimSpace(PrettyExamineMemory(addr, memArea, true, format, 1)), "\n")

	if len(display) != len(res) {
		t.Fatalf("wrong lines return, expected %d but got %d", len(display), len(res))
	}

	for i := 0; i < len(display); i++ {
		if display[i] != res[i] {
			errInfo := fmt.Sprintf("wrong display return at line %d\n", i+1)
			errInfo += fmt.Sprintf("expected:\n   %q\n", display[i])
			errInfo += fmt.Sprintf("but got:\n   %q\n", res[i])
			t.Fatal(errInfo)
		}
	}
}

func Test_byteArrayToUInt64(t *testing.T) {
	tests := []struct {
		name string
		args []byte
		want uint64
	}{
		{"case-nil", nil, 0},
		{"case-empty", []byte{}, 0},
		{"case-1", []byte{0x1}, 1},
		{"case-2", []byte{0x12}, 18},
		{"case-3", []byte{0x1, 0x2}, 513},
		{"case-4", []byte{0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x2}, 144397766876004609},
		{"case-5", []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, math.MaxUint64},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := byteArrayToUInt64(tt.args, true)
			if got != tt.want {
				t.Errorf("byteArrayToUInt64() got = %v, want %v", got, tt.want)
			}
		})
	}
}


<|start_filename|>pkg/proc/native/threads_linux_amd64.go<|end_filename|>
package native

import (
	"syscall"
	"unsafe"

	sys "golang.org/x/sys/unix"

	"github.com/go-delve/delve/pkg/proc"
	"github.com/go-delve/delve/pkg/proc/linutil"
)

func (t *nativeThread) restoreRegisters(savedRegs proc.Registers) error {
	sr := savedRegs.(*linutil.AMD64Registers)

	var restoreRegistersErr error
	t.dbp.execPtraceFunc(func() {
		oldRegs := (*sys.PtraceRegs)(sr.Regs)

		var currentRegs sys.PtraceRegs
		restoreRegistersErr = sys.PtraceGetRegs(t.ID, &currentRegs)
		if restoreRegistersErr != nil {
			return
		}
		// restoreRegisters is only supposed to restore CPU registers, not FS_BASE and GS_BASE
		oldRegs.Fs_base = currentRegs.Fs_base
		oldRegs.Gs_base = currentRegs.Gs_base

		restoreRegistersErr = sys.PtraceSetRegs(t.ID, oldRegs)

		if restoreRegistersErr != nil {
			return
		}
		if sr.Fpregset.Xsave != nil {
			iov := sys.Iovec{Base: &sr.Fpregset.Xsave[0], Len: uint64(len(sr.Fpregset.Xsave))}
			_, _, restoreRegistersErr = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_SETREGSET, uintptr(t.ID), _NT_X86_XSTATE, uintptr(unsafe.Pointer(&iov)), 0, 0)
			return
		}

		_, _, restoreRegistersErr = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_SETFPREGS, uintptr(t.ID), uintptr(0), uintptr(unsafe.Pointer(&sr.Fpregset.AMD64PtraceFpRegs)), 0, 0)
		return
	})
	if restoreRegistersErr == syscall.Errno(0) {
		restoreRegistersErr = nil
	}
	return restoreRegistersErr
}


<|start_filename|>pkg/dwarf/godwarf/addr.go<|end_filename|>
package godwarf

import (
	"bytes"
	"encoding/binary"
	"errors"

	"github.com/go-delve/delve/pkg/dwarf/util"
)

// DebugAddrSection represents the debug_addr section of DWARFv5.
// See DWARFv5 section 7.27 page 241 and following.
type DebugAddrSection struct {
	byteOrder binary.ByteOrder
	ptrSz     int
	data      []byte
}

// ParseAddr parses the header of a debug_addr section.
func ParseAddr(data []byte) *DebugAddrSection {
	if len(data) == 0 {
		return nil
	}
	r := &DebugAddrSection{data: data}
	_, dwarf64, _, byteOrder := util.ReadDwarfLengthVersion(data)
	r.byteOrder = byteOrder
	data = data[6:]
	if dwarf64 {
		data = data[8:]
	}

	addrSz := data[0]
	segSelSz := data[1]
	r.ptrSz = int(addrSz + segSelSz)

	return r
}

// GetSubsection returns the subsection of debug_addr starting at addrBase
func (addr *DebugAddrSection) GetSubsection(addrBase uint64) *DebugAddr {
	if addr == nil {
		return nil
	}
	return &DebugAddr{DebugAddrSection: addr, addrBase: addrBase}
}

// DebugAddr represents a subsection of the debug_addr section with a specific base address
type DebugAddr struct {
	*DebugAddrSection
	addrBase uint64
}

// Get returns the address at index idx starting from addrBase.
func (addr *DebugAddr) Get(idx uint64) (uint64, error) {
	if addr == nil || addr.DebugAddrSection == nil {
		return 0, errors.New("debug_addr section not present")
	}
	off := idx*uint64(addr.ptrSz) + addr.addrBase
	return util.ReadUintRaw(bytes.NewReader(addr.data[off:]), addr.byteOrder, addr.ptrSz)
}


<|start_filename|>pkg/locspec/doc.go<|end_filename|>
// Package locspec implements code to parse a string into a specific
// location specification.
//
// Location spec examples:
//
// locStr ::= <filename>:<line> | <function>[:<line>] | /<regex>/ | (+|-)<offset> | <line> | *<address>
// * <filename> can be the full path of a file or just a suffix
// * <function> ::= <package>.<receiver type>.<name> | <package>.(*<receiver type>).<name> | <receiver type>.<name> | <package>.<name> | (*<receiver type>).<name> | <name>
// * <function> must be unambiguous
// * /<regex>/ will return a location for each function matched by regex
// * +<offset> returns a location for the line that is <offset> lines after the current line
// * -<offset> returns a location for the line that is <offset> lines before the current line
// * <line> returns a location for a line in the current file
// * *<address> returns the location corresponding to the specified address
package locspec


<|start_filename|>cmd/dlv/cmds/cmds_test.go<|end_filename|>
package cmds

import (
	"testing"
)

func TestParseRedirects(t *testing.T) {
	testCases := []struct {
		in     []string
		tgt    [3]string
		tgterr string
	}{
		{
			[]string{"one.txt"},
			[3]string{"one.txt", "", ""},
			"",
		},
		{
			[]string{"one.txt", "two.txt"},
			[3]string{},
			"redirect error: stdin redirected twice",
		},
		{
			[]string{"stdout:one.txt"},
			[3]string{"", "one.txt", ""},
			"",
		},
		{
			[]string{"stdout:one.txt", "stderr:two.txt", "stdin:three.txt"},
			[3]string{"three.txt", "one.txt", "two.txt"},
			"",
		},
		{
			[]string{"stdout:one.txt", "stderr:two.txt", "three.txt"},
			[3]string{"three.txt", "one.txt", "two.txt"},
			"",
		},
	}

	for _, tc := range testCases {
		t.Logf("input: %q", tc.in)
		out, err := parseRedirects(tc.in)
		t.Logf("output: %q error %v", out, err)
		if tc.tgterr != "" {
			if err == nil {
				t.Errorf("Expected error %q, got output %q", tc.tgterr, out)
			} else if errstr := err.Error(); errstr != tc.tgterr {
				t.Errorf("Expected error %q, got error %q", tc.tgterr, errstr)
			}
		} else {
			for i := range tc.tgt {
				if tc.tgt[i] != out[i] {
					t.Errorf("Expected %q, got %q (mismatch at index %d)", tc.tgt, out, i)
					break
				}
			}
		}
	}
}


<|start_filename|>pkg/terminal/starlark_test.go<|end_filename|>
package terminal

import (
	"fmt"
	"runtime"
	"strings"
	"testing"
)

func TestStarlarkExamples(t *testing.T) {
	if runtime.GOARCH == "arm64" {
		t.Skip("test is not valid on ARM64")
	}
	withTestTerminal("testvariables2", t, func(term *FakeTerminal) {
		term.MustExec("continue")
		t.Run("goroutine_start_line", func(t *testing.T) { testStarlarkExampleGoroutineStartLine(t, term) })
		t.Run("create_breakpoint_main", func(t *testing.T) { testStarlarkExampleCreateBreakpointmain(t, term) })
		t.Run("switch_to_main_goroutine", func(t *testing.T) { testStarlarkExampleSwitchToMainGoroutine(t, term) })
		t.Run("linked_list", func(t *testing.T) { testStarlarkExampleLinkedList(t, term) })
		t.Run("echo_expr", func(t *testing.T) { testStarlarkEchoExpr(t, term) })
		t.Run("find_array", func(t *testing.T) { testStarlarkFindArray(t, term) })
		t.Run("map_iteration", func(t *testing.T) { testStarlarkMapIteration(t, term) })
	})
}

func testStarlarkExampleGoroutineStartLine(t *testing.T, term *FakeTerminal) {
	term.MustExec("source " + findStarFile("goroutine_start_line"))
	out1 := term.MustExec("gsl")
	t.Logf("gsl: %q", out1)
	if !strings.Contains(out1, "func main() {") {
		t.Fatalf("goroutine_start_line example failed")
	}
}

func testStarlarkExampleCreateBreakpointmain(t *testing.T, term *FakeTerminal) {
	out2p1 := term.MustExec("source " + findStarFile("create_breakpoint_main"))
	t.Logf("create_breakpoint_main: %s", out2p1)
	out2p2 := term.MustExec("breakpoints")
	t.Logf("breakpoints: %q", out2p2)
	if !strings.Contains(out2p2, "main.afunc1") {
		t.Fatalf("create_breakpoint_runtime_func example failed")
	}
}

func testStarlarkExampleSwitchToMainGoroutine(t *testing.T, term *FakeTerminal) {
	gs, _, err := term.client.ListGoroutines(0, 0)
	if err != nil {
		t.Fatal(err)
	}
	for _, g := range gs {
		if g.ID != 1 {
			t.Logf("switching to goroutine %d\n", g.ID)
			term.MustExec(fmt.Sprintf("goroutine %d", g.ID))
			break
		}
	}
	term.MustExec("source " + findStarFile("switch_to_main_goroutine"))
	out3p1 := term.MustExec("switch_to_main_goroutine")
	out3p2 := term.MustExec("goroutine")
	t.Logf("%q\n", out3p1)
	t.Logf("%q\n", out3p2)
	if !strings.Contains(out3p2, "Goroutine 1:\n") {
		t.Fatalf("switch_to_main_goroutine example failed")
	}
}

func testStarlarkExampleLinkedList(t *testing.T, term *FakeTerminal) {
	term.MustExec("source " + findStarFile("linked_list"))
	out := term.MustExec("linked_list ll Next 3")
	t.Logf("%q\n", out)
	if n := len(strings.Split(strings.TrimRight(out, "\n"), "\n")); n != 3 {
		t.Fatalf("wrong number of lines in output %d", n)
	}

	out = term.MustExec("linked_list ll Next 100")
	t.Logf("%q\n", out)
	lines := strings.Split(strings.TrimRight(out, "\n"), "\n")
	for i, line := range lines {
		if i == 5 {
			if line != "5: *main.List nil" {
				t.Errorf("mismatched line %d %q", i, line)
			}
		} else {
			if !strings.HasPrefix(line, fmt.Sprintf("%d: *main.List {N: %d, Next: ", i, i)) {
				t.Errorf("mismatched line %d %q", i, line)
			}
		}
	}
	if len(lines) != 6 {
		t.Fatalf("wrong number of output lines %d", len(lines))
	}
}

func testStarlarkEchoExpr(t *testing.T, term *FakeTerminal) {
	term.MustExec("source " + findStarFile("echo_expr"))
	out := term.MustExec("echo_expr 2+2, 1-1, 2*3")
	t.Logf("echo_expr %q", out)
	if out != "a 4 b 0 c 6\n" {
		t.Error("output mismatch")
	}
}

func testStarlarkFindArray(t *testing.T, term *FakeTerminal) {
	term.MustExec("source " + findStarFile("find_array"))
	out := term.MustExec(`find_array "s2", lambda x: x.A == 5`)
	t.Logf("find_array (1) %q", out)
	if out != "found 2\n" {
		t.Error("output mismatch")
	}
	out = term.MustExec(`find_array "s2", lambda x: x.A == 20`)
	t.Logf("find_array (2) %q", out)
	if out != "not found\n" {
		t.Error("output mismatch")
	}
}

func testStarlarkMapIteration(t *testing.T, term *FakeTerminal) {
	out := term.MustExec("source " + findStarFile("starlark_map_iteration"))
	if !strings.Contains(out, "values=66") {
		t.Fatalf("testStarlarkMapIteration example failed")
	}
	t.Logf("%s", out)
}

func TestStarlarkVariable(t *testing.T) {
	withTestTerminal("testvariables2", t, func(term *FakeTerminal) {
		term.MustExec("continue")
		for _, tc := range []struct{ expr, tgt string }{
			{`v = eval(None, "i1").Variable; print(v.Value)`, "1"},
			{`v = eval(None, "f1").Variable; print(v.Value)`, "3"},
			{`v = eval(None, "as1").Variable; print(v.Value.A)`, "1"},
			{`v = eval(None, "as1").Variable; print(v.Value.B)`, "1"},
			{`v = eval(None, "as1").Variable; print(v.Value["A"])`, "1"},
			{`v = eval(None, "s1").Variable; print(v.Value[0])`, "one"},
			{`v = eval(None, "nilstruct").Variable; print(v.Value)`, "*main.astruct nil"},
			{`v = eval(None, "nilstruct").Variable; print(v.Value[0])`, "None"},
			{`v = eval(None, 'm1["Malone"]').Variable; print(v.Value)`, "main.astruct {A: 2, B: 3}"},
			{`v = eval(None, "m1").Variable; print(v.Value["Malone"])`, "main.astruct {A: 2, B: 3}"},
			{`v = eval(None, "m2").Variable; print(v.Value[1])`, "*main.astruct {A: 10, B: 11}"},
			{`v = eval(None, "c1.pb").Variable; print(v.Value)`, "*main.bstruct {a: main.astruct {A: 1, B: 2}}"},
			{`v = eval(None, "c1.pb").Variable; print(v.Value[0])`, "main.bstruct {a: main.astruct {A: 1, B: 2}}"},
			{`v = eval(None, "c1.pb").Variable; print(v.Value.a.B)`, "2"},
			{`v = eval(None, "iface1").Variable; print(v.Value[0])`, "*main.astruct {A: 1, B: 2}"},
			{`v = eval(None, "iface1").Variable; print(v.Value[0][0])`, "main.astruct {A: 1, B: 2}"},
			{`v = eval(None, "iface1").Variable; print(v.Value.A)`, "1"},

			{`v = eval(None, "as1", {"MaxStructFields": -1}).Variable; print(v.Value.A)`, "1"},
			{`v = eval({"GoroutineID": -1}, "as1").Variable; print(v.Value.A)`, "1"},
			{`v = eval(cur_scope(), "as1").Variable; print(v.Value.A)`, "1"},
			{`v = eval(None, "as1", default_load_config()).Variable; print(v.Value.A)`, "1"},

			// From starlark.md's examples
			{`v = eval(None, "s2").Variable; print(v.Value[0])`, "main.astruct {A: 1, B: 2}"},
			{`v = eval(None, "s2").Variable; print(v.Value[1].A)`, "3"},
			{`v = eval(None, "s2").Variable; print(v.Value[1].A + 10)`, "13"},
			{`v = eval(None, "s2").Variable; print(v.Value[1]["B"])`, "4"},
		} {
			out := strings.TrimSpace(term.MustExecStarlark(tc.expr))
			if out != tc.tgt {
				t.Errorf("for %q\nexpected %q\ngot %q", tc.expr, tc.tgt, out)
			}
		}
	})
}


<|start_filename|>service/rpccommon/sameuser_linux_test.go<|end_filename|>
//+build linux

package rpccommon

import (
	"net"
	"testing"
)

func TestSameUserForRemoteAddr(t *testing.T) {
	uid = 149098
	var proc string
	readFile = func(string) ([]byte, error) {
		return []byte(proc), nil
	}
	for _, tt := range []struct {
		name string
		proc string
		addr *net.TCPAddr
		want bool
	}{
		{
			name: "ipv4-same",
			proc: `  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
  21: 0100007F:E682 0100007F:0FC8 01 00000000:00000000 00:00000000 00000000 149098        0 8420541 2 0000000000000000 20 0 0 10 -1                  `,
			addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 59010},
			want: true,
		},

		{
			name: "ipv4-not-found",
			proc: `  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
  21: 0100007F:E682 0100007F:0FC8 01 00000000:00000000 00:00000000 00000000 149098        0 8420541 2 0000000000000000 20 0 0 10 -1                  `,
			addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 2342},
			want: false,
		},

		{
			name: "ipv4-different-uid",
			proc: `  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
  21: 0100007F:E682 0100007F:0FC8 01 00000000:00000000 00:00000000 00000000 149097        0 8420541 2 0000000000000000 20 0 0 10 -1                  `,
			addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 59010},
			want: false,
		},

		{
			name: "ipv6-same",
			proc: `  sl  local_address                         remote_address                        st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
   5: 00000000000000000000000001000000:D3E4 00000000000000000000000001000000:0FC8 01 00000000:00000000 00:00000000 00000000 149098        0 8425526 2 0000000000000000 20 0 0 10 -1
   6: 00000000000000000000000001000000:0FC8 00000000000000000000000001000000:D3E4 01 00000000:00000000 00:00000000 00000000 149098        0 8424744 1 0000000000000000 20 0 0 10 -1`,
			addr: &net.TCPAddr{IP: net.ParseIP("::1"), Port: 54244},
			want: true,
		},
	} {
		t.Run(tt.name, func(t *testing.T) {
			proc = tt.proc
			// The returned error is for reporting only.
			same, _ := sameUserForRemoteAddr(tt.addr)
			if got, want := same, tt.want; got != want {
				t.Errorf("sameUserForRemoteAddr(%v) = %v, want %v", tt.addr, got, want)
			}
		})
	}
}


<|start_filename|>_fixtures/cat.go<|end_filename|>
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		fmt.Printf("read %q\n", s.Text())
	}
	os.Stdout.Close()
}
