proc_test.go 131.8 KB
Newer Older
1
package proc_test
D
Derek Parker 已提交
2 3

import (
4
	"bytes"
5
	"flag"
6
	"fmt"
7
	"go/ast"
8
	"go/constant"
9
	"go/token"
10
	"io/ioutil"
D
Derek Parker 已提交
11 12
	"net"
	"net/http"
D
Derek Parker 已提交
13
	"os"
14
	"os/exec"
15
	"path/filepath"
16
	"reflect"
17
	"runtime"
18
	"strconv"
19
	"strings"
D
Derek Parker 已提交
20
	"testing"
D
Derek Parker 已提交
21
	"time"
D
Dan Mace 已提交
22

23 24 25 26 27 28 29
	"github.com/go-delve/delve/pkg/dwarf/frame"
	"github.com/go-delve/delve/pkg/goversion"
	"github.com/go-delve/delve/pkg/logflags"
	"github.com/go-delve/delve/pkg/proc"
	"github.com/go-delve/delve/pkg/proc/gdbserial"
	"github.com/go-delve/delve/pkg/proc/native"
	protest "github.com/go-delve/delve/pkg/proc/test"
D
Derek Parker 已提交
30
)
31

32
var normalLoadConfig = proc.LoadConfig{true, 1, 64, 64, -1, 0}
33
var testBackend, buildMode string
34

35
func init() {
36 37
	runtime.GOMAXPROCS(4)
	os.Setenv("GOMAXPROCS", "4")
38 39
}

D
Dan Mace 已提交
40
func TestMain(m *testing.M) {
41
	flag.StringVar(&testBackend, "backend", "", "selects backend")
42 43 44
	flag.StringVar(&buildMode, "test-buildmode", "", "selects build mode")
	var logConf string
	flag.StringVar(&logConf, "log", "", "configures logging")
45
	flag.Parse()
46
	protest.DefaultTestBackend(&testBackend)
47 48 49 50
	if buildMode != "" && buildMode != "pie" {
		fmt.Fprintf(os.Stderr, "unknown build mode %q", buildMode)
		os.Exit(1)
	}
51
	logflags.Setup(logConf != "", logConf, "")
D
Derek Parker 已提交
52
	os.Exit(protest.RunTestsWithFixtures(m))
D
Dan Mace 已提交
53 54
}

55
func withTestProcess(name string, t testing.TB, fn func(p proc.Process, fixture protest.Fixture)) {
56
	withTestProcessArgs(name, t, ".", []string{}, 0, fn)
57 58
}

59
func withTestProcessArgs(name string, t testing.TB, wd string, args []string, buildFlags protest.BuildFlags, fn func(p proc.Process, fixture protest.Fixture)) {
60 61 62
	if buildMode == "pie" {
		buildFlags |= protest.BuildModePIE
	}
63
	fixture := protest.BuildFixture(name, buildFlags)
64
	var p proc.Process
65
	var err error
66
	var tracedir string
67 68 69

	switch testBackend {
	case "native":
70
		p, err = native.Launch(append([]string{fixture.Path}, args...), wd, false, []string{})
71
	case "lldb":
72
		p, err = gdbserial.LLDBLaunch(append([]string{fixture.Path}, args...), wd, false, []string{})
73 74 75
	case "rr":
		protest.MustHaveRecordingAllowed(t)
		t.Log("recording")
76
		p, tracedir, err = gdbserial.RecordAndReplay(append([]string{fixture.Path}, args...), wd, true, []string{})
77
		t.Logf("replaying %q", tracedir)
78 79 80
	default:
		t.Fatal("unknown backend")
	}
81 82 83 84 85
	if err != nil {
		t.Fatal("Launch():", err)
	}

	defer func() {
86
		p.Detach(true)
87 88 89
		if tracedir != "" {
			protest.SafeRemoveAll(tracedir)
		}
90 91 92 93 94
	}()

	fn(p, fixture)
}

95
func getRegisters(p proc.Process, t *testing.T) proc.Registers {
96
	regs, err := p.CurrentThread().Registers(false)
97 98 99 100 101 102 103
	if err != nil {
		t.Fatal("Registers():", err)
	}

	return regs
}

104
func dataAtAddr(thread proc.MemoryReadWriter, addr uint64) ([]byte, error) {
105 106 107
	data := make([]byte, 1)
	_, err := thread.ReadMemory(data, uintptr(addr))
	return data, err
108 109
}

110
func assertNoError(err error, t testing.TB, s string) {
111
	if err != nil {
112 113
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
114
		t.Fatalf("failed assertion at %s:%d: %s - %s\n", fname, line, s, err)
115 116 117
	}
}

118
func currentPC(p proc.Process, t *testing.T) uint64 {
119
	regs, err := p.CurrentThread().Registers(false)
120 121 122 123
	if err != nil {
		t.Fatal(err)
	}

124
	return regs.PC()
125 126
}

127
func currentLineNumber(p proc.Process, t *testing.T) (string, int) {
128
	pc := currentPC(p, t)
129
	f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
130
	return f, l
131 132
}

133 134 135 136 137 138 139 140 141
func assertLineNumber(p proc.Process, t *testing.T, lineno int, descr string) (string, int) {
	f, l := currentLineNumber(p, t)
	if l != lineno {
		_, callerFile, callerLine, _ := runtime.Caller(1)
		t.Fatalf("%s expected line :%d got %s:%d\n\tat %s:%d", descr, lineno, f, l, callerFile, callerLine)
	}
	return f, l
}

142
func TestExit(t *testing.T) {
143
	protest.AllowRecording(t)
144
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
145
		err := proc.Continue(p)
146
		pe, ok := err.(proc.ErrProcessExited)
147
		if !ok {
148
			t.Fatalf("Continue() returned unexpected error type %s", err)
149 150 151 152
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
153
		if pe.Pid != p.Pid() {
154 155 156 157 158
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

159
func TestExitAfterContinue(t *testing.T) {
160
	protest.AllowRecording(t)
161
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
162
		setFunctionBreakpoint(p, t, "main.sayhi")
163
		assertNoError(proc.Continue(p), t, "First Continue()")
164
		err := proc.Continue(p)
165
		pe, ok := err.(proc.ErrProcessExited)
166
		if !ok {
L
Luke Hoban 已提交
167
			t.Fatalf("Continue() returned unexpected error type %s", pe)
168 169 170 171
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
172
		if pe.Pid != p.Pid() {
173 174 175 176 177
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

178 179 180 181
func setFunctionBreakpoint(p proc.Process, t testing.TB, fname string) *proc.Breakpoint {
	_, f, l, _ := runtime.Caller(1)
	f = filepath.Base(f)

182
	addr, err := proc.FindFunctionLocation(p, fname, 0)
183
	if err != nil {
184
		t.Fatalf("%s:%d: FindFunctionLocation(%s): %v", f, l, fname, err)
185
	}
186 187 188 189 190
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
	if err != nil {
		t.Fatalf("%s:%d: FindFunctionLocation(%s): %v", f, l, fname, err)
	}
	return bp
191 192
}

193 194 195
func setFileBreakpoint(p proc.Process, t *testing.T, path string, lineno int) *proc.Breakpoint {
	_, f, l, _ := runtime.Caller(1)
	f = filepath.Base(f)
196 197

	addr, err := proc.FindFileLocation(p, path, lineno)
A
aarzilli 已提交
198
	if err != nil {
199
		t.Fatalf("%s:%d: FindFileLocation(%s, %d): %v", f, l, path, lineno, err)
A
aarzilli 已提交
200
	}
201
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
A
aarzilli 已提交
202
	if err != nil {
203
		t.Fatalf("%s:%d: SetBreakpoint: %v", f, l, err)
A
aarzilli 已提交
204 205 206 207
	}
	return bp
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
func findFunctionLocation(p proc.Process, t *testing.T, fnname string) uint64 {
	addr, err := proc.FindFunctionLocation(p, fnname, 0)
	if err != nil {
		_, f, l, _ := runtime.Caller(1)
		f = filepath.Base(f)
		t.Fatalf("%s:%d: FindFunctionLocation(%s): %v", f, l, fnname, err)
	}
	return addr
}

func findFileLocation(p proc.Process, t *testing.T, file string, lineno int) uint64 {
	addr, err := proc.FindFileLocation(p, file, lineno)
	if err != nil {
		_, f, l, _ := runtime.Caller(1)
		f = filepath.Base(f)
		t.Fatalf("%s:%d: FindFileLocation(%s, %d): %v", f, l, file, lineno, err)
	}
	return addr
}

D
Derek Parker 已提交
228
func TestHalt(t *testing.T) {
229
	stopChan := make(chan interface{}, 1)
230
	withTestProcess("loopprog", t, func(p proc.Process, fixture protest.Fixture) {
231
		setFunctionBreakpoint(p, t, "main.loop")
232 233 234
		assertNoError(proc.Continue(p), t, "Continue")
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
235 236
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
237 238
			}
		}
239
		resumeChan := make(chan struct{}, 1)
D
Derek Parker 已提交
240
		go func() {
A
aarzilli 已提交
241 242
			<-resumeChan
			time.Sleep(100 * time.Millisecond)
243
			stopChan <- p.RequestManualStop()
D
Derek Parker 已提交
244
		}()
A
aarzilli 已提交
245
		p.ResumeNotify(resumeChan)
246
		assertNoError(proc.Continue(p), t, "Continue")
247 248 249 250 251 252
		retVal := <-stopChan

		if err, ok := retVal.(error); ok && err != nil {
			t.Fatal()
		}

D
Derek Parker 已提交
253 254 255
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
256 257 258 259 260 261
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
				if th, ok := th.(*native.Thread); ok {
					if !th.Stopped() {
						t.Fatal("expected thread to be stopped, but was not")
					}
262 263 264
				}
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
D
Derek Parker 已提交
265 266 267 268 269
			}
		}
	})
}

270
func TestStep(t *testing.T) {
271
	protest.AllowRecording(t)
272
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
273
		setFunctionBreakpoint(p, t, "main.helloworld")
274
		assertNoError(proc.Continue(p), t, "Continue()")
275

276
		regs := getRegisters(p, t)
277
		rip := regs.PC()
278

279
		err := p.CurrentThread().StepInstruction()
D
Derek Parker 已提交
280
		assertNoError(err, t, "Step()")
281

282
		regs = getRegisters(p, t)
283 284 285 286 287
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
288

D
Derek Parker 已提交
289
func TestBreakpoint(t *testing.T) {
290
	protest.AllowRecording(t)
291
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
292
		bp := setFunctionBreakpoint(p, t, "main.helloworld")
293
		assertNoError(proc.Continue(p), t, "Continue()")
294

295 296 297
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
298

299 300 301 302
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
303
		if pc-1 != bp.Addr && pc != bp.Addr {
304
			f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
305
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
306 307
		}
	})
308
}
309

J
Josh Soref 已提交
310
func TestBreakpointInSeparateGoRoutine(t *testing.T) {
311
	protest.AllowRecording(t)
312
	withTestProcess("testthreads", t, func(p proc.Process, fixture protest.Fixture) {
313
		setFunctionBreakpoint(p, t, "main.anotherthread")
314

315
		assertNoError(proc.Continue(p), t, "Continue")
316

317 318 319
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
320

321
		f, l, _ := p.BinInfo().PCToLine(pc)
322 323 324 325 326 327
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
328
func TestBreakpointWithNonExistantFunction(t *testing.T) {
329
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
330
		_, err := p.SetBreakpoint(0, proc.UserBreakpoint, nil)
331 332 333 334
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
335
}
336

337
func TestClearBreakpointBreakpoint(t *testing.T) {
338
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
339
		bp := setFunctionBreakpoint(p, t, "main.sleepytime")
340

341
		_, err := p.ClearBreakpoint(bp.Addr)
342
		assertNoError(err, t, "ClearBreakpoint()")
343

344 345
		data, err := dataAtAddr(p.CurrentThread(), bp.Addr)
		assertNoError(err, t, "dataAtAddr")
346

347
		int3 := []byte{0xcc}
348 349 350 351
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

352
		if countBreakpoints(p) != 0 {
353 354 355
			t.Fatal("Breakpoint not removed internally")
		}
	})
356
}
357

358 359 360
type nextTest struct {
	begin, end int
}
361

362
func countBreakpoints(p proc.Process) int {
363
	bpcount := 0
A
aarzilli 已提交
364
	for _, bp := range p.Breakpoints().M {
365 366 367 368 369 370 371
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

A
aarzilli 已提交
372 373 374
type contFunc int

const (
375 376
	contContinue contFunc = iota
	contNext
A
aarzilli 已提交
377
	contStep
378
	contStepout
A
aarzilli 已提交
379 380
)

381 382
type seqTest struct {
	cf  contFunc
383
	pos interface{}
384 385
}

A
aarzilli 已提交
386
func testseq(program string, contFunc contFunc, testcases []nextTest, initialLocation string, t *testing.T) {
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
	seqTestcases := make([]seqTest, len(testcases)+1)
	seqTestcases[0] = seqTest{contContinue, testcases[0].begin}
	for i := range testcases {
		if i > 0 {
			if testcases[i-1].end != testcases[i].begin {
				panic(fmt.Errorf("begin/end mismatch at index %d", i))
			}
		}
		seqTestcases[i+1] = seqTest{contFunc, testcases[i].end}
	}
	testseq2(t, program, initialLocation, seqTestcases)
}

const traceTestseq2 = false

func testseq2(t *testing.T, program string, initialLocation string, testcases []seqTest) {
	testseq2Args(".", []string{}, 0, t, program, initialLocation, testcases)
}

func testseq2Args(wd string, args []string, buildFlags protest.BuildFlags, t *testing.T, program string, initialLocation string, testcases []seqTest) {
407
	protest.AllowRecording(t)
408
	withTestProcessArgs(program, t, wd, args, buildFlags, func(p proc.Process, fixture protest.Fixture) {
409
		var bp *proc.Breakpoint
A
aarzilli 已提交
410
		if initialLocation != "" {
411
			bp = setFunctionBreakpoint(p, t, initialLocation)
412
		} else if testcases[0].cf == contContinue {
413
			bp = setFileBreakpoint(p, t, fixture.Source, testcases[0].pos.(int))
414 415 416 417 418
		} else {
			panic("testseq2 can not set initial breakpoint")
		}
		if traceTestseq2 {
			t.Logf("initial breakpoint %v", bp)
A
aarzilli 已提交
419
		}
420 421
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
422

D
Derek Parker 已提交
423
		f, ln := currentLineNumber(p, t)
424 425
		for i, tc := range testcases {
			switch tc.cf {
A
aarzilli 已提交
426
			case contNext:
427 428 429
				if traceTestseq2 {
					t.Log("next")
				}
430
				assertNoError(proc.Next(p), t, "Next() returned an error")
A
aarzilli 已提交
431
			case contStep:
432 433 434
				if traceTestseq2 {
					t.Log("step")
				}
435
				assertNoError(proc.Step(p), t, "Step() returned an error")
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
			case contStepout:
				if traceTestseq2 {
					t.Log("stepout")
				}
				assertNoError(proc.StepOut(p), t, "StepOut() returned an error")
			case contContinue:
				if traceTestseq2 {
					t.Log("continue")
				}
				assertNoError(proc.Continue(p), t, "Continue() returned an error")
				if i == 0 {
					if traceTestseq2 {
						t.Log("clearing initial breakpoint")
					}
					_, err := p.ClearBreakpoint(bp.Addr)
					assertNoError(err, t, "ClearBreakpoint() returned an error")
				}
A
aarzilli 已提交
453
			}
454

D
Derek Parker 已提交
455
			f, ln = currentLineNumber(p, t)
456
			regs, _ = p.CurrentThread().Registers(false)
457 458 459 460
			pc := regs.PC()

			if traceTestseq2 {
				t.Logf("at %#x %s:%d", pc, f, ln)
461
				fmt.Printf("at %#x %s:%d", pc, f, ln)
462
			}
463 464 465 466 467 468 469 470 471 472 473
			switch pos := tc.pos.(type) {
			case int:
				if ln != pos {
					t.Fatalf("Program did not continue to correct next location expected %d was %s:%d (%#x) (testcase %d)", pos, filepath.Base(f), ln, pc, i)
				}
			case string:
				v := strings.Split(pos, ":")
				tgtln, _ := strconv.Atoi(v[1])
				if !strings.HasSuffix(f, v[0]) || (ln != tgtln) {
					t.Fatalf("Program did not continue to correct next location, expected %s was %s:%d (%#x) (testcase %d)", pos, filepath.Base(f), ln, pc, i)
				}
474 475
			}
		}
476

477
		if countBreakpoints(p) != 0 {
A
aarzilli 已提交
478
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints().M))
479
		}
480 481
	})
}
482

483
func TestNextGeneral(t *testing.T) {
484 485
	var testcases []nextTest

486
	ver, _ := goversion.Parse(runtime.Version())
487

488
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
		testcases = []nextTest{
			{17, 19},
			{19, 20},
			{20, 23},
			{23, 24},
			{24, 26},
			{26, 31},
			{31, 23},
			{23, 24},
			{24, 26},
			{26, 31},
			{31, 23},
			{23, 24},
			{24, 26},
			{26, 27},
			{27, 28},
			{28, 34},
		}
	} else {
		testcases = []nextTest{
			{17, 19},
			{19, 20},
			{20, 23},
			{23, 24},
			{24, 26},
			{26, 31},
			{31, 23},
			{23, 24},
			{24, 26},
			{26, 31},
			{31, 23},
			{23, 24},
			{24, 26},
			{26, 27},
			{27, 34},
		}
525
	}
526

A
aarzilli 已提交
527
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
528 529
}

530
func TestNextConcurrent(t *testing.T) {
531 532 533
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
534
	testcases := []nextTest{
535
		{8, 9},
536 537 538
		{9, 10},
		{10, 11},
	}
539
	protest.AllowRecording(t)
540
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
541
		bp := setFunctionBreakpoint(p, t, "main.sayhi")
542
		assertNoError(proc.Continue(p), t, "Continue")
543
		f, ln := currentLineNumber(p, t)
544
		initV := evalVariable(p, t, "n")
545
		initVval, _ := constant.Int64Val(initV.Value)
546
		_, err := p.ClearBreakpoint(bp.Addr)
547
		assertNoError(err, t, "ClearBreakpoint()")
548
		for _, tc := range testcases {
549
			g, err := proc.GetG(p.CurrentThread())
550
			assertNoError(err, t, "GetG()")
551 552
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
553
			}
554 555 556
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
557
			assertNoError(proc.Next(p), t, "Next() returned an error")
558 559
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to the expected location")
			v := evalVariable(p, t, "n")
560 561
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
562 563 564 565 566 567
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

568
func TestNextConcurrentVariant2(t *testing.T) {
569 570 571
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
572 573
	// Just like TestNextConcurrent but instead of removing the initial breakpoint we check that when it happens is for other goroutines
	testcases := []nextTest{
574
		{8, 9},
575 576 577
		{9, 10},
		{10, 11},
	}
578
	protest.AllowRecording(t)
579
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
580
		setFunctionBreakpoint(p, t, "main.sayhi")
581
		assertNoError(proc.Continue(p), t, "Continue")
582
		f, ln := currentLineNumber(p, t)
583
		initV := evalVariable(p, t, "n")
584 585
		initVval, _ := constant.Int64Val(initV.Value)
		for _, tc := range testcases {
586
			t.Logf("test case %v", tc)
587
			g, err := proc.GetG(p.CurrentThread())
588
			assertNoError(err, t, "GetG()")
589 590
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
591 592 593 594
			}
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
595
			assertNoError(proc.Next(p), t, "Next() returned an error")
596 597
			var vval int64
			for {
598
				v := evalVariable(p, t, "n")
599 600 601
				for _, thread := range p.ThreadList() {
					proc.GetG(thread)
				}
602
				vval, _ = constant.Int64Val(v.Value)
603
				if bpstate := p.CurrentThread().Breakpoint(); bpstate.Breakpoint == nil {
604 605 606 607 608 609 610 611
					if vval != initVval {
						t.Fatal("Did not end up on same goroutine")
					}
					break
				} else {
					if vval == initVval {
						t.Fatal("Initial breakpoint triggered twice for the same goroutine")
					}
612
					assertNoError(proc.Continue(p), t, "Continue 2")
613 614
				}
			}
615
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to the expected location")
616 617 618 619
		}
	})
}

620 621
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
622
		{13, 14},
D
Derek Parker 已提交
623 624
		{14, 15},
		{15, 35},
625
	}
626
	protest.AllowRecording(t)
A
aarzilli 已提交
627
	testseq("testnextprog", contNext, testcases, "main.helloworld", t)
628 629 630
}

func TestNextFunctionReturnDefer(t *testing.T) {
A
aarzilli 已提交
631 632
	var testcases []nextTest

633
	ver, _ := goversion.Parse(runtime.Version())
A
aarzilli 已提交
634

635
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
636 637 638 639 640 641 642 643 644 645 646
		testcases = []nextTest{
			{5, 6},
			{6, 9},
			{9, 10},
		}
	} else {
		testcases = []nextTest{
			{5, 8},
			{8, 9},
			{9, 10},
		}
647
	}
648
	protest.AllowRecording(t)
A
aarzilli 已提交
649
	testseq("testnextdefer", contNext, testcases, "main.main", t)
650 651
}

D
Derek Parker 已提交
652 653 654 655 656
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
657
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
658 659 660
		go func() {
			// Wait for program to start listening.
			for {
661
				conn, err := net.Dial("tcp", "127.0.0.1:9191")
D
Derek Parker 已提交
662 663 664 665 666 667
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
668
			http.Get("http://127.0.0.1:9191")
D
Derek Parker 已提交
669
		}()
670
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
671 672 673 674 675 676 677 678
			t.Fatal(err)
		}
		f, ln := currentLineNumber(p, t)
		for _, tc := range testcases {
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}

679
			assertNoError(proc.Next(p), t, "Next() returned an error")
D
Derek Parker 已提交
680

681
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to correct next location")
D
Derek Parker 已提交
682 683 684 685
		}
	})
}

D
Derek Parker 已提交
686
func TestRuntimeBreakpoint(t *testing.T) {
687
	withTestProcess("testruntimebreakpoint", t, func(p proc.Process, fixture protest.Fixture) {
688
		err := proc.Continue(p)
D
Derek Parker 已提交
689 690 691
		if err != nil {
			t.Fatal(err)
		}
692 693 694
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
695
		f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
696
		if l != 10 {
697
			t.Fatalf("did not respect breakpoint %s:%d", f, l)
D
Derek Parker 已提交
698 699 700 701
		}
	})
}

702
func returnAddress(thread proc.Thread) (uint64, error) {
703
	locations, err := proc.ThreadStacktrace(thread, 2)
704 705 706 707
	if err != nil {
		return 0, err
	}
	if len(locations) < 2 {
A
aarzilli 已提交
708
		return 0, fmt.Errorf("no return address for function: %s", locations[0].Current.Fn.BaseName())
709 710 711 712
	}
	return locations[1].Current.PC, nil
}

713
func TestFindReturnAddress(t *testing.T) {
714
	protest.AllowRecording(t)
715
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
716 717
		setFileBreakpoint(p, t, fixture.Source, 24)
		err := proc.Continue(p)
718 719 720
		if err != nil {
			t.Fatal(err)
		}
721
		addr, err := returnAddress(p.CurrentThread())
722 723 724
		if err != nil {
			t.Fatal(err)
		}
725
		_, l, _ := p.BinInfo().PCToLine(addr)
726 727
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
728
		}
729 730
	})
}
731

732
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
733
	protest.AllowRecording(t)
734
	withTestProcess("testreturnaddress", t, func(p proc.Process, fixture protest.Fixture) {
735
		fnName := "runtime.rt0_go"
736
		setFunctionBreakpoint(p, t, fnName)
737
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
738 739
			t.Fatal(err)
		}
740
		if _, err := returnAddress(p.CurrentThread()); err == nil {
741
			t.Fatal("expected error to be returned")
742 743 744
		}
	})
}
D
Derek Parker 已提交
745 746

func TestSwitchThread(t *testing.T) {
747
	protest.AllowRecording(t)
748
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
749 750 751 752 753
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
754
		setFunctionBreakpoint(p, t, "main.main")
755
		err = proc.Continue(p)
D
Derek Parker 已提交
756 757 758 759
		if err != nil {
			t.Fatal(err)
		}
		var nt int
760 761 762 763
		ct := p.CurrentThread().ThreadID()
		for _, thread := range p.ThreadList() {
			if thread.ThreadID() != ct {
				nt = thread.ThreadID()
D
Derek Parker 已提交
764 765 766 767 768 769 770 771 772 773 774
				break
			}
		}
		if nt == 0 {
			t.Fatal("could not find thread to switch to")
		}
		// With valid thread id
		err = p.SwitchThread(nt)
		if err != nil {
			t.Fatal(err)
		}
775
		if p.CurrentThread().ThreadID() != nt {
D
Derek Parker 已提交
776 777 778 779
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
780

781 782 783 784 785 786
func TestCGONext(t *testing.T) {
	// Test if one can do 'next' in a cgo binary
	// On OSX with Go < 1.5 CGO is not supported due to: https://github.com/golang/go/issues/8973
	if runtime.GOOS == "darwin" && strings.Contains(runtime.Version(), "1.4") {
		return
	}
A
aarzilli 已提交
787 788 789
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
790

791
	protest.AllowRecording(t)
792
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
793 794 795
		setFunctionBreakpoint(p, t, "main.main")
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
796 797 798
	})
}

A
aarzilli 已提交
799 800 801 802 803
type loc struct {
	line int
	fn   string
}

804
func (l1 *loc) match(l2 proc.Stackframe) bool {
A
aarzilli 已提交
805
	if l1.line >= 0 {
806
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
807 808 809
			return false
		}
	}
810
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
811 812 813 814
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
815 816
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
817
	}
818
	protest.AllowRecording(t)
819
	withTestProcess("stacktraceprog", t, func(p proc.Process, fixture protest.Fixture) {
820
		bp := setFunctionBreakpoint(p, t, "main.stacktraceme")
A
aarzilli 已提交
821 822

		for i := range stacks {
823 824
			assertNoError(proc.Continue(p), t, "Continue()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
A
aarzilli 已提交
825 826 827 828 829 830
			assertNoError(err, t, "Stacktrace()")

			if len(locations) != len(stacks[i])+2 {
				t.Fatalf("Wrong stack trace size %d %d\n", len(locations), len(stacks[i])+2)
			}

831 832 833 834
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
835

A
aarzilli 已提交
836 837 838 839 840 841 842
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

843
		p.ClearBreakpoint(bp.Addr)
844
		proc.Continue(p)
A
aarzilli 已提交
845 846 847
	})
}

848
func TestStacktrace2(t *testing.T) {
849
	withTestProcess("retstack", t, func(p proc.Process, fixture protest.Fixture) {
850
		assertNoError(proc.Continue(p), t, "Continue()")
851

852
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
853
		assertNoError(err, t, "Stacktrace()")
854
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
855 856 857
			for i := range locations {
				t.Logf("\t%s:%d [%s]\n", locations[i].Call.File, locations[i].Call.Line, locations[i].Call.Fn.Name)
			}
D
Derek Parker 已提交
858
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
859 860
		}

861 862
		assertNoError(proc.Continue(p), t, "Continue()")
		locations, err = proc.ThreadStacktrace(p.CurrentThread(), 40)
863
		assertNoError(err, t, "Stacktrace()")
864
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
865 866 867
			for i := range locations {
				t.Logf("\t%s:%d [%s]\n", locations[i].Call.File, locations[i].Call.Line, locations[i].Call.Fn.Name)
			}
D
Derek Parker 已提交
868
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
869 870 871 872 873
		}
	})

}

874
func stackMatch(stack []loc, locations []proc.Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
875 876 877
	if len(stack) > len(locations) {
		return false
	}
878 879 880 881 882 883 884 885 886 887 888
	i := 0
	for j := range locations {
		if i >= len(stack) {
			break
		}
		if skipRuntime {
			if locations[j].Call.Fn == nil || strings.HasPrefix(locations[j].Call.Fn.Name, "runtime.") {
				continue
			}
		}
		if !stack[i].match(locations[j]) {
A
aarzilli 已提交
889 890
			return false
		}
891
		i++
A
aarzilli 已提交
892
	}
893
	return i >= len(stack)
A
aarzilli 已提交
894 895 896
}

func TestStacktraceGoroutine(t *testing.T) {
897
	mainStack := []loc{{14, "main.stacktraceme"}, {29, "main.main"}}
898 899 900
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		mainStack[0].line = 15
	}
901 902 903 904 905
	agoroutineStacks := [][]loc{
		{{8, "main.agoroutine"}},
		{{9, "main.agoroutine"}},
		{{10, "main.agoroutine"}},
	}
A
aarzilli 已提交
906

907
	protest.AllowRecording(t)
908
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
909
		bp := setFunctionBreakpoint(p, t, "main.stacktraceme")
A
aarzilli 已提交
910

911
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
912

913
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
aarzilli 已提交
914 915 916 917 918
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
919
		for i, g := range gs {
920
			locations, err := g.Stacktrace(40, false)
921 922
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
923
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
924 925
				continue
			}
A
aarzilli 已提交
926

927
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
928 929 930
				mainCount++
			}

931 932 933 934 935 936 937 938
			found := false
			for _, agoroutineStack := range agoroutineStacks {
				if stackMatch(agoroutineStack, locations, true) {
					found = true
				}
			}

			if found {
A
aarzilli 已提交
939 940
				agoroutineCount++
			} else {
D
Derek Parker 已提交
941
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
942 943
				for i := range locations {
					name := ""
944 945
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
946
					}
947
					t.Logf("\t%s:%d %s (%#x)\n", locations[i].Call.File, locations[i].Call.Line, name, locations[i].Current.PC)
A
aarzilli 已提交
948 949 950 951 952
				}
			}
		}

		if mainCount != 1 {
953
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
954 955 956 957 958 959
		}

		if agoroutineCount != 10 {
			t.Fatalf("Goroutine stacks not found (%d)", agoroutineCount)
		}

960
		p.ClearBreakpoint(bp.Addr)
961
		proc.Continue(p)
A
aarzilli 已提交
962 963
	})
}
964 965

func TestKill(t *testing.T) {
966 967 968 969
	if testBackend == "lldb" {
		// k command presumably works but leaves the process around?
		return
	}
970 971 972 973
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
		if err := p.Detach(true); err != nil {
			t.Fatal(err)
		}
974
		if valid, _ := p.Valid(); valid {
975 976 977 978 979 980 981 982 983
			t.Fatal("expected process to have exited")
		}
		if runtime.GOOS == "linux" {
			_, err := os.Open(fmt.Sprintf("/proc/%d/", p.Pid()))
			if err == nil {
				t.Fatal("process has not exited", p.Pid())
			}
		}
	})
984
}
985

986
func testGSupportFunc(name string, t *testing.T, p proc.Process, fixture protest.Fixture) {
987
	bp := setFunctionBreakpoint(p, t, "main.main")
988

989
	assertNoError(proc.Continue(p), t, name+": Continue()")
990

991
	g, err := proc.GetG(p.CurrentThread())
992 993 994 995 996 997 998 999 1000 1001 1002 1003
	assertNoError(err, t, name+": GetG()")

	if g == nil {
		t.Fatal(name + ": g was nil")
	}

	t.Logf(name+": g is: %v", g)

	p.ClearBreakpoint(bp.Addr)
}

func TestGetG(t *testing.T) {
1004
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
1005 1006 1007
		testGSupportFunc("nocgo", t, p, fixture)
	})

1008 1009 1010 1011
	// On OSX with Go < 1.5 CGO is not supported due to: https://github.com/golang/go/issues/8973
	if runtime.GOOS == "darwin" && strings.Contains(runtime.Version(), "1.4") {
		return
	}
A
aarzilli 已提交
1012 1013 1014
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
1015

1016
	protest.AllowRecording(t)
1017
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
1018 1019 1020
		testGSupportFunc("cgo", t, p, fixture)
	})
}
1021 1022

func TestContinueMulti(t *testing.T) {
1023
	protest.AllowRecording(t)
1024
	withTestProcess("integrationprog", t, func(p proc.Process, fixture protest.Fixture) {
1025 1026
		bp1 := setFunctionBreakpoint(p, t, "main.main")
		bp2 := setFunctionBreakpoint(p, t, "main.sayhi")
1027 1028 1029 1030

		mainCount := 0
		sayhiCount := 0
		for {
1031
			err := proc.Continue(p)
1032
			if valid, _ := p.Valid(); !valid {
1033 1034 1035 1036
				break
			}
			assertNoError(err, t, "Continue()")

1037
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp1.ID {
1038 1039 1040
				mainCount++
			}

1041
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp2.ID {
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
				sayhiCount++
			}
		}

		if mainCount != 1 {
			t.Fatalf("Main breakpoint hit wrong number of times: %d\n", mainCount)
		}

		if sayhiCount != 3 {
			t.Fatalf("Sayhi breakpoint hit wrong number of times: %d\n", sayhiCount)
		}
	})
}
1055

1056
func TestBreakpointOnFunctionEntry(t *testing.T) {
1057
	testseq2(t, "testprog", "main.main", []seqTest{{contContinue, 17}})
1058
}
1059 1060

func TestProcessReceivesSIGCHLD(t *testing.T) {
1061
	protest.AllowRecording(t)
1062
	withTestProcess("sigchldprog", t, func(p proc.Process, fixture protest.Fixture) {
1063
		err := proc.Continue(p)
1064
		_, ok := err.(proc.ErrProcessExited)
1065
		if !ok {
1066
			t.Fatalf("Continue() returned unexpected error type %v", err)
1067 1068 1069
		}
	})
}
1070 1071

func TestIssue239(t *testing.T) {
1072
	withTestProcess("is sue239", t, func(p proc.Process, fixture protest.Fixture) {
1073
		setFileBreakpoint(p, t, fixture.Source, 17)
1074
		assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue()"))
1075 1076
	})
}
1077

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
func findFirstNonRuntimeFrame(p proc.Process) (proc.Stackframe, error) {
	frames, err := proc.ThreadStacktrace(p.CurrentThread(), 10)
	if err != nil {
		return proc.Stackframe{}, err
	}

	for _, frame := range frames {
		if frame.Current.Fn != nil && !strings.HasPrefix(frame.Current.Fn.Name, "runtime.") {
			return frame, nil
		}
	}
	return proc.Stackframe{}, fmt.Errorf("non-runtime frame not found")
}

1092
func evalVariableOrError(p proc.Process, symbol string) (*proc.Variable, error) {
1093 1094 1095 1096 1097 1098 1099
	var scope *proc.EvalScope
	var err error

	if testBackend == "rr" {
		var frame proc.Stackframe
		frame, err = findFirstNonRuntimeFrame(p)
		if err == nil {
1100
			scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)
1101 1102 1103 1104
		}
	} else {
		scope, err = proc.GoroutineScope(p.CurrentThread())
	}
1105

1106 1107 1108
	if err != nil {
		return nil, err
	}
1109
	return scope.EvalVariable(symbol, normalLoadConfig)
1110 1111
}

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
func evalVariable(p proc.Process, t testing.TB, symbol string) *proc.Variable {
	v, err := evalVariableOrError(p, symbol)
	if err != nil {
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
		t.Fatalf("%s:%d: EvalVariable(%q): %v", fname, line, symbol, err)
	}
	return v
}

1122
func setVariable(p proc.Process, symbol, value string) error {
1123
	scope, err := proc.GoroutineScope(p.CurrentThread())
1124 1125 1126 1127 1128 1129 1130
	if err != nil {
		return err
	}
	return scope.SetVariable(symbol, value)
}

func TestVariableEvaluation(t *testing.T) {
1131
	protest.AllowRecording(t)
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	testcases := []struct {
		name        string
		st          reflect.Kind
		value       interface{}
		length, cap int64
		childrenlen int
	}{
		{"a1", reflect.String, "foofoofoofoofoofoo", 18, 0, 0},
		{"a11", reflect.Array, nil, 3, -1, 3},
		{"a12", reflect.Slice, nil, 2, 2, 2},
		{"a13", reflect.Slice, nil, 3, 3, 3},
		{"a2", reflect.Int, int64(6), 0, 0, 0},
		{"a3", reflect.Float64, float64(7.23), 0, 0, 0},
		{"a4", reflect.Array, nil, 2, -1, 2},
		{"a5", reflect.Slice, nil, 5, 5, 5},
		{"a6", reflect.Struct, nil, 2, 0, 2},
		{"a7", reflect.Ptr, nil, 1, 0, 1},
		{"a8", reflect.Struct, nil, 2, 0, 2},
		{"a9", reflect.Ptr, nil, 1, 0, 1},
		{"baz", reflect.String, "bazburzum", 9, 0, 0},
		{"neg", reflect.Int, int64(-1), 0, 0, 0},
		{"f32", reflect.Float32, float64(float32(1.2)), 0, 0, 0},
A
aarzilli 已提交
1154 1155
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
		{"a6.Baz", reflect.Int, int64(8), 0, 0, 0},
		{"a7.Baz", reflect.Int, int64(5), 0, 0, 0},
		{"a8.Baz", reflect.String, "feh", 3, 0, 0},
		{"a8", reflect.Struct, nil, 2, 0, 2},
		{"i32", reflect.Array, nil, 2, -1, 2},
		{"b1", reflect.Bool, true, 0, 0, 0},
		{"b2", reflect.Bool, false, 0, 0, 0},
		{"f", reflect.Func, "main.barfoo", 0, 0, 0},
		{"ba", reflect.Slice, nil, 200, 200, 64},
	}

1167
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1168
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1169 1170

		for _, tc := range testcases {
1171
			v := evalVariable(p, t, tc.name)
1172 1173 1174 1175 1176 1177 1178

			if v.Kind != tc.st {
				t.Fatalf("%s simple type: expected: %s got: %s", tc.name, tc.st, v.Kind.String())
			}
			if v.Value == nil && tc.value != nil {
				t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
			} else {
1179 1180 1181
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1182 1183 1184
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1185 1186
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1187 1188 1189
					if y, ok := tc.value.(float64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
A
aarzilli 已提交
1190 1191 1192 1193 1194 1195
				case reflect.Complex64, reflect.Complex128:
					xr, _ := constant.Float64Val(constant.Real(v.Value))
					xi, _ := constant.Float64Val(constant.Imag(v.Value))
					if y, ok := tc.value.(complex128); !ok || complex(xr, xi) != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1196 1197
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
				}
			}
			if v.Len != tc.length {
				t.Fatalf("%s len: expected: %d got: %d", tc.name, tc.length, v.Len)
			}
			if v.Cap != tc.cap {
				t.Fatalf("%s cap: expected: %d got: %d", tc.name, tc.cap, v.Cap)
			}
			if len(v.Children) != tc.childrenlen {
				t.Fatalf("%s children len: expected %d got: %d", tc.name, tc.childrenlen, len(v.Children))
			}
		}
	})
}

func TestFrameEvaluation(t *testing.T) {
1216
	protest.AllowRecording(t)
1217
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
1218
		setFunctionBreakpoint(p, t, "main.stacktraceme")
1219
		assertNoError(proc.Continue(p), t, "Continue()")
1220

1221 1222
		t.Logf("stopped on thread %d, goroutine: %#v", p.CurrentThread().ThreadID(), p.SelectedGoroutine())

1223
		// Testing evaluation on goroutines
1224
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1225 1226 1227 1228
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
1229
			frames, err := g.Stacktrace(10, false)
1230 1231 1232 1233
			if err != nil {
				t.Logf("could not stacktrace goroutine %d: %v\n", g.ID, err)
				continue
			}
1234
			t.Logf("Goroutine %d", g.ID)
1235
			logStacktrace(t, p.BinInfo(), frames)
1236 1237 1238 1239 1240 1241 1242 1243
			for i := range frames {
				if frames[i].Call.Fn != nil && frames[i].Call.Fn.Name == "main.agoroutine" {
					frame = i
					break
				}
			}

			if frame < 0 {
D
Derek Parker 已提交
1244
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1245 1246 1247
				continue
			}

1248
			scope, err := proc.ConvertEvalScope(p, g.ID, frame, 0)
1249 1250
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
1251
			v, err := scope.EvalVariable("i", normalLoadConfig)
1252 1253
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1254
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1255 1256
				continue
			}
1257 1258
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1259 1260 1261 1262 1263 1264 1265 1266
		}

		for i := range found {
			if !found[i] {
				t.Fatalf("Goroutine %d not found\n", i)
			}
		}

1267
		// Testing evaluation on frames
1268 1269
		assertNoError(proc.Continue(p), t, "Continue() 2")
		g, err := proc.GetG(p.CurrentThread())
1270 1271 1272
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
1273
			scope, err := proc.ConvertEvalScope(p, g.ID, i+1, 0)
1274
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
1275
			v, err := scope.EvalVariable("n", normalLoadConfig)
1276
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1277
			n, _ := constant.Int64Val(v.Value)
1278 1279 1280 1281 1282 1283 1284 1285 1286
			t.Logf("frame %d n %d\n", i+1, n)
			if n != int64(3-i) {
				t.Fatalf("On frame %d value of n is %d (not %d)", i+1, n, 3-i)
			}
		}
	})
}

func TestPointerSetting(t *testing.T) {
1287
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1288
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1289 1290

		pval := func(n int64) {
1291
			variable := evalVariable(p, t, "p1")
1292 1293 1294
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1295 1296 1297 1298 1299 1300
			}
		}

		pval(1)

		// change p1 to point to i2
1301
		scope, err := proc.GoroutineScope(p.CurrentThread())
1302
		assertNoError(err, t, "Scope()")
1303
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1304 1305
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1306 1307 1308 1309 1310 1311 1312 1313 1314
		pval(2)

		// change the value of i2 check that p1 also changes
		assertNoError(setVariable(p, "i2", "5"), t, "SetVariable()")
		pval(5)
	})
}

func TestVariableFunctionScoping(t *testing.T) {
1315
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1316
		err := proc.Continue(p)
1317 1318
		assertNoError(err, t, "Continue() returned an error")

1319 1320
		evalVariable(p, t, "a1")
		evalVariable(p, t, "a2")
1321 1322

		// Move scopes, a1 exists here by a2 does not
1323
		err = proc.Continue(p)
1324 1325
		assertNoError(err, t, "Continue() returned an error")

1326
		evalVariable(p, t, "a1")
1327

1328
		_, err = evalVariableOrError(p, "a2")
1329 1330 1331 1332 1333 1334 1335
		if err == nil {
			t.Fatalf("Can eval out of scope variable a2")
		}
	})
}

func TestRecursiveStructure(t *testing.T) {
1336
	protest.AllowRecording(t)
1337
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1338
		assertNoError(proc.Continue(p), t, "Continue()")
1339
		v := evalVariable(p, t, "aas")
1340 1341 1342
		t.Logf("v: %v\n", v)
	})
}
1343 1344 1345

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1346
	protest.AllowRecording(t)
1347
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1348
		assertNoError(proc.Continue(p), t, "Continue()")
1349
		evalVariable(p, t, "iface5")
1350 1351
	})
}
1352 1353 1354

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1355
	protest.AllowRecording(t)
1356
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1357
		assertNoError(proc.Continue(p), t, "Continue()")
1358
		iface2fn1v := evalVariable(p, t, "iface2fn1")
1359 1360
		t.Logf("iface2fn1: %v\n", iface2fn1v)

1361
		iface2fn2v := evalVariable(p, t, "iface2fn2")
1362 1363 1364
		t.Logf("iface2fn2: %v\n", iface2fn2v)
	})
}
1365 1366

func TestBreakpointCounts(t *testing.T) {
1367 1368 1369
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1370
	protest.AllowRecording(t)
1371
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1372
		bp := setFileBreakpoint(p, t, fixture.Source, 12)
1373 1374

		for {
1375
			if err := proc.Continue(p); err != nil {
1376
				if _, exited := err.(proc.ErrProcessExited); exited {
1377 1378 1379 1380 1381 1382 1383
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
		if bp.TotalHitCount != 200 {
			t.Fatalf("Wrong TotalHitCount for the breakpoint (%d)", bp.TotalHitCount)
		}

		if len(bp.HitCount) != 2 {
			t.Fatalf("Wrong number of goroutines for breakpoint (%d)", len(bp.HitCount))
		}

		for _, v := range bp.HitCount {
			if v != 100 {
				t.Fatalf("Wrong HitCount for breakpoint (%v)", bp.HitCount)
			}
		}
	})
}

1400 1401
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
1402
	protest.AllowRecording(b)
1403
	b.SetBytes(int64(64 * 128))
1404
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1405
		assertNoError(proc.Continue(p), b, "Continue()")
1406
		for i := 0; i < b.N; i++ {
1407
			evalVariable(p, b, "bencharr")
1408 1409 1410 1411
		}
	})
}

1412 1413 1414 1415 1416 1417 1418
const doTestBreakpointCountsWithDetection = false

func TestBreakpointCountsWithDetection(t *testing.T) {
	if !doTestBreakpointCountsWithDetection {
		return
	}
	m := map[int64]int64{}
1419
	protest.AllowRecording(t)
1420
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1421
		bp := setFileBreakpoint(p, t, fixture.Source, 12)
1422 1423

		for {
1424
			if err := proc.Continue(p); err != nil {
1425
				if _, exited := err.(proc.ErrProcessExited); exited {
1426 1427 1428 1429
					break
				}
				assertNoError(err, t, "Continue()")
			}
1430
			for _, th := range p.ThreadList() {
1431
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
1432 1433
					continue
				}
1434
				scope, err := proc.GoroutineScope(th)
1435
				assertNoError(err, t, "Scope()")
1436
				v, err := scope.EvalVariable("i", normalLoadConfig)
1437 1438
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
1439
				v, err = scope.EvalVariable("id", normalLoadConfig)
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
				assertNoError(err, t, "evalVariable")
				id, _ := constant.Int64Val(v.Value)
				m[id] = i
			}

			total := int64(0)
			for i := range m {
				total += m[i] + 1
			}

			if uint64(total) != bp.TotalHitCount {
				t.Fatalf("Mismatched total count %d %d\n", total, bp.TotalHitCount)
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
		if bp.TotalHitCount != 200 {
			t.Fatalf("Wrong TotalHitCount for the breakpoint (%d)", bp.TotalHitCount)
		}

		if len(bp.HitCount) != 2 {
			t.Fatalf("Wrong number of goroutines for breakpoint (%d)", len(bp.HitCount))
		}

		for _, v := range bp.HitCount {
			if v != 100 {
				t.Fatalf("Wrong HitCount for breakpoint (%v)", bp.HitCount)
			}
		}
	})
}
1471

1472 1473 1474
func BenchmarkArrayPointer(b *testing.B) {
	// each bencharr struct is 128 bytes, benchparr is an array of 64 pointers to bencharr
	// each read will read 64 bencharr structs plus the 64 pointers of benchparr
1475
	protest.AllowRecording(b)
1476
	b.SetBytes(int64(64*128 + 64*8))
1477
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1478
		assertNoError(proc.Continue(p), b, "Continue()")
1479
		for i := 0; i < b.N; i++ {
1480
			evalVariable(p, b, "bencharr")
1481 1482 1483 1484 1485 1486 1487 1488
		}
	})
}

func BenchmarkMap(b *testing.B) {
	// m1 contains 41 entries, each one has a value that's 2 int values (2* 8 bytes) and a string key
	// each string key has an average of 9 character
	// reading strings and the map structure imposes a overhead that we ignore here
1489
	protest.AllowRecording(b)
1490
	b.SetBytes(int64(41 * (2*8 + 9)))
1491
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1492
		assertNoError(proc.Continue(p), b, "Continue()")
1493
		for i := 0; i < b.N; i++ {
1494
			evalVariable(p, b, "m1")
1495 1496 1497 1498 1499
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1500
	protest.AllowRecording(b)
1501
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1502
		assertNoError(proc.Continue(p), b, "Continue()")
1503
		for i := 0; i < b.N; i++ {
1504
			p.Common().ClearAllGCache()
1505
			_, _, err := proc.GoroutinesInfo(p, 0, 0)
1506 1507 1508 1509 1510
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1511 1512
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
1513
	protest.AllowRecording(t)
1514
	withTestProcess("issue262", t, func(p proc.Process, fixture protest.Fixture) {
1515
		setFileBreakpoint(p, t, fixture.Source, 11)
1516

1517
		assertNoError(proc.Continue(p), t, "Continue()")
1518
		err := proc.Continue(p)
1519 1520 1521
		if err == nil {
			t.Fatalf("No error on second continue")
		}
1522
		_, exited := err.(proc.ErrProcessExited)
1523 1524 1525 1526 1527
		if !exited {
			t.Fatalf("Process did not exit after second continue: %v", err)
		}
	})
}
1528

1529
func TestIssue305(t *testing.T) {
1530 1531 1532
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1533
	protest.AllowRecording(t)
1534
	withTestProcess("issue305", t, func(p proc.Process, fixture protest.Fixture) {
1535
		setFileBreakpoint(p, t, fixture.Source, 5)
1536

1537
		assertNoError(proc.Continue(p), t, "Continue()")
1538

1539 1540 1541 1542 1543
		assertNoError(proc.Next(p), t, "Next() 1")
		assertNoError(proc.Next(p), t, "Next() 2")
		assertNoError(proc.Next(p), t, "Next() 3")
		assertNoError(proc.Next(p), t, "Next() 4")
		assertNoError(proc.Next(p), t, "Next() 5")
1544 1545 1546
	})
}

1547 1548 1549
func TestPointerLoops(t *testing.T) {
	// Pointer loops through map entries, pointers and slices
	// Regression test for issue #341
1550
	protest.AllowRecording(t)
1551
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1552
		assertNoError(proc.Continue(p), t, "Continue()")
1553 1554
		for _, expr := range []string{"mapinf", "ptrinf", "sliceinf"} {
			t.Logf("requesting %s", expr)
1555
			v := evalVariable(p, t, expr)
1556 1557
			t.Logf("%s: %v\n", expr, v)
		}
1558 1559
	})
}
1560 1561

func BenchmarkLocalVariables(b *testing.B) {
1562
	protest.AllowRecording(b)
1563
	withTestProcess("testvariables", b, func(p proc.Process, fixture protest.Fixture) {
1564 1565
		assertNoError(proc.Continue(p), b, "Continue() returned an error")
		scope, err := proc.GoroutineScope(p.CurrentThread())
1566 1567
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
1568
			_, err := scope.LocalVariables(normalLoadConfig)
1569 1570 1571 1572
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1573 1574

func TestCondBreakpoint(t *testing.T) {
1575 1576 1577
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1578
	protest.AllowRecording(t)
1579
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1580
		bp := setFileBreakpoint(p, t, fixture.Source, 9)
1581 1582 1583 1584 1585 1586
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1587
		assertNoError(proc.Continue(p), t, "Continue()")
1588

1589
		nvar := evalVariable(p, t, "n")
1590 1591 1592 1593 1594 1595 1596 1597 1598

		n, _ := constant.Int64Val(nvar.Value)
		if n != 7 {
			t.Fatalf("Stoppend on wrong goroutine %d\n", n)
		}
	})
}

func TestCondBreakpointError(t *testing.T) {
1599 1600 1601
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1602
	protest.AllowRecording(t)
1603
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1604
		bp := setFileBreakpoint(p, t, fixture.Source, 9)
1605 1606 1607 1608 1609 1610
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1611
		err := proc.Continue(p)
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
		if err == nil {
			t.Fatalf("No error on first Continue()")
		}

		if err.Error() != "error evaluating expression: could not find symbol value for nonexistentvariable" && err.Error() != "multiple errors evaluating conditions" {
			t.Fatalf("Unexpected error on first Continue(): %v", err)
		}

		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1626
		err = proc.Continue(p)
1627
		if err != nil {
1628
			if _, exited := err.(proc.ErrProcessExited); !exited {
1629 1630 1631
				t.Fatalf("Unexpected error on second Continue(): %v", err)
			}
		} else {
1632
			nvar := evalVariable(p, t, "n")
1633 1634 1635 1636 1637 1638 1639 1640

			n, _ := constant.Int64Val(nvar.Value)
			if n != 7 {
				t.Fatalf("Stoppend on wrong goroutine %d\n", n)
			}
		}
	})
}
1641 1642 1643

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1644
	protest.AllowRecording(t)
1645
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1646
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1647
		mmvar := evalVariable(p, t, "mainMenu")
1648 1649 1650 1651 1652
		if mmvar.Kind != reflect.Slice {
			t.Fatalf("Wrong kind for mainMenu: %v\n", mmvar.Kind)
		}
	})
}
1653 1654

func TestStepIntoFunction(t *testing.T) {
1655
	withTestProcess("teststep", t, func(p proc.Process, fixture protest.Fixture) {
1656
		// Continue until breakpoint
1657
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1658
		// Step into function
1659
		assertNoError(proc.Step(p), t, "Step() returned an error")
1660
		// We should now be inside the function.
1661
		loc, err := p.CurrentThread().Location()
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
		if err != nil {
			t.Fatal(err)
		}
		if loc.Fn.Name != "main.callme" {
			t.Fatalf("expected to be within the 'callme' function, was in %s instead", loc.Fn.Name)
		}
		if !strings.Contains(loc.File, "teststep") {
			t.Fatalf("debugger stopped at incorrect location: %s:%d", loc.File, loc.Line)
		}
		if loc.Line != 8 {
			t.Fatalf("debugger stopped at incorrect line: %d", loc.Line)
		}
	})
}
1676 1677 1678

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
1679 1680 1681 1682 1683

	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// go 1.10 emits DW_AT_decl_line and we won't be able to evaluate 'st'
		// which is declared after line 13.
1684
		t.Skip("can not evaluate not-yet-declared variables with go 1.10")
1685 1686
	}

1687
	protest.AllowRecording(t)
1688
	withTestProcess("issue384", t, func(p proc.Process, fixture protest.Fixture) {
1689
		setFileBreakpoint(p, t, fixture.Source, 13)
1690
		assertNoError(proc.Continue(p), t, "Continue()")
1691
		evalVariable(p, t, "st")
1692 1693
	})
}
A
aarzilli 已提交
1694 1695 1696

func TestIssue332_Part1(t *testing.T) {
	// Next shouldn't step inside a function call
1697
	protest.AllowRecording(t)
1698
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1699
		setFileBreakpoint(p, t, fixture.Source, 8)
1700 1701 1702
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "first Next()")
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
		assertNoError(err, t, "Stacktrace()")
		if locations[0].Call.Fn == nil {
			t.Fatalf("Not on a function")
		}
		if locations[0].Call.Fn.Name != "main.main" {
			t.Fatalf("Not on main.main after Next: %s (%s:%d)", locations[0].Call.Fn.Name, locations[0].Call.File, locations[0].Call.Line)
		}
		if locations[0].Call.Line != 9 {
			t.Fatalf("Not on line 9 after Next: %s (%s:%d)", locations[0].Call.Fn.Name, locations[0].Call.File, locations[0].Call.Line)
		}
	})
}

func TestIssue332_Part2(t *testing.T) {
	// Step should skip a function's prologue
	// In some parts of the prologue, for some functions, the FDE data is incorrect
	// which leads to 'next' and 'stack' failing with error "could not find FDE for PC: <garbage>"
	// because the incorrect FDE data leads to reading the wrong stack address as the return address
1721
	protest.AllowRecording(t)
1722
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1723
		setFileBreakpoint(p, t, fixture.Source, 8)
1724
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
1725 1726 1727

		// step until we enter changeMe
		for {
1728 1729
			assertNoError(proc.Step(p), t, "Step()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738
			assertNoError(err, t, "Stacktrace()")
			if locations[0].Call.Fn == nil {
				t.Fatalf("Not on a function")
			}
			if locations[0].Call.Fn.Name == "main.changeMe" {
				break
			}
		}

1739 1740 1741
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers()")
		pc := regs.PC()
1742
		pcAfterPrologue := findFunctionLocation(p, t, "main.changeMe")
1743
		if pcAfterPrologue == p.BinInfo().LookupFunc["main.changeMe"].Entry {
1744 1745 1746 1747 1748 1749
			t.Fatalf("main.changeMe and main.changeMe:0 are the same (%x)", pcAfterPrologue)
		}
		if pc != pcAfterPrologue {
			t.Fatalf("Step did not skip the prologue: current pc: %x, first instruction after prologue: %x", pc, pcAfterPrologue)
		}

1750 1751 1752 1753
		assertNoError(proc.Next(p), t, "first Next()")
		assertNoError(proc.Next(p), t, "second Next()")
		assertNoError(proc.Next(p), t, "third Next()")
		err = proc.Continue(p)
1754
		if _, exited := err.(proc.ErrProcessExited); !exited {
A
aarzilli 已提交
1755 1756 1757 1758
			assertNoError(err, t, "final Continue()")
		}
	})
}
1759 1760

func TestIssue396(t *testing.T) {
A
Alessandro Arzilli 已提交
1761 1762 1763 1764 1765
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 13) {
		// CL 161337 in Go 1.13 and later removes the autogenerated init function
		// https://go-review.googlesource.com/c/go/+/161337
		t.Skip("no autogenerated init function in Go 1.13 or later")
	}
1766
	withTestProcess("callme", t, func(p proc.Process, fixture protest.Fixture) {
1767
		findFunctionLocation(p, t, "main.init")
1768 1769
	})
}
1770 1771 1772

func TestIssue414(t *testing.T) {
	// Stepping until the program exits
1773
	protest.AllowRecording(t)
1774
	withTestProcess("math", t, func(p proc.Process, fixture protest.Fixture) {
1775
		setFileBreakpoint(p, t, fixture.Source, 9)
1776
		assertNoError(proc.Continue(p), t, "Continue()")
1777
		for {
1778
			err := proc.Step(p)
1779
			if err != nil {
1780
				if _, exited := err.(proc.ErrProcessExited); exited {
1781 1782 1783 1784 1785 1786 1787
					break
				}
			}
			assertNoError(err, t, "Step()")
		}
	})
}
1788 1789

func TestPackageVariables(t *testing.T) {
1790
	protest.AllowRecording(t)
1791
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1792
		err := proc.Continue(p)
1793
		assertNoError(err, t, "Continue()")
1794
		scope, err := proc.GoroutineScope(p.CurrentThread())
1795
		assertNoError(err, t, "Scope()")
1796
		vars, err := scope.PackageVariables(normalLoadConfig)
1797 1798 1799
		assertNoError(err, t, "PackageVariables()")
		failed := false
		for _, v := range vars {
1800
			if v.Unreadable != nil && v.Unreadable.Error() != "no location attribute Location" {
1801 1802 1803 1804 1805 1806 1807 1808 1809
				failed = true
				t.Logf("Unreadable variable %s: %v", v.Name, v.Unreadable)
			}
		}
		if failed {
			t.Fatalf("previous errors")
		}
	})
}
1810 1811

func TestIssue149(t *testing.T) {
1812 1813
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
1814 1815 1816
		return
	}
	// setting breakpoint on break statement
1817
	withTestProcess("break", t, func(p proc.Process, fixture protest.Fixture) {
1818
		findFileLocation(p, t, fixture.Source, 8)
1819 1820
	})
}
1821 1822

func TestPanicBreakpoint(t *testing.T) {
1823
	protest.AllowRecording(t)
1824
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
1825
		assertNoError(proc.Continue(p), t, "Continue()")
1826 1827
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1828
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1829 1830 1831
		}
	})
}
1832

1833
func TestCmdLineArgs(t *testing.T) {
1834
	expectSuccess := func(p proc.Process, fixture protest.Fixture) {
1835
		err := proc.Continue(p)
1836 1837
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint != nil && bp.Name == proc.UnrecoveredPanic {
1838
			t.Fatalf("testing args failed on unrecovered-panic breakpoint: %v", bp)
1839
		}
1840
		exit, exited := err.(proc.ErrProcessExited)
1841
		if !exited {
1842
			t.Fatalf("Process did not exit: %v", err)
1843 1844
		} else {
			if exit.Status != 0 {
1845
				t.Fatalf("process exited with invalid status %d", exit.Status)
1846 1847 1848 1849
			}
		}
	}

1850
	expectPanic := func(p proc.Process, fixture protest.Fixture) {
1851
		proc.Continue(p)
1852 1853
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1854
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1855 1856 1857 1858
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
1859 1860 1861
	withTestProcessArgs("testargs", t, ".", []string{"test"}, 0, expectSuccess)
	withTestProcessArgs("testargs", t, ".", []string{"-test"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass flag"}, 0, expectSuccess)
1862
	// check that arguments with spaces are *only* passed correctly when correctly called
1863 1864 1865
	withTestProcessArgs("testargs", t, ".", []string{"test pass", "flag"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass", "flag"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test pass flag"}, 0, expectPanic)
1866 1867
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
1868 1869 1870
	withTestProcessArgs("testargs", t, ".", []string{"invalid"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "invalid"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"invalid", "pass flag"}, 0, expectPanic)
1871 1872
}

1873 1874 1875 1876 1877
func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
1878
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
1879 1880 1881
		go func() {
			// Wait for program to start listening.
			for {
1882
				conn, err := net.Dial("tcp", "127.0.0.1:9191")
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}

			p.RequestManualStop()
		}()

1893 1894
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
1895 1896 1897
		assertNoError(err, t, "Stacktrace()")
	})
}
1898

1899
func TestNextParked(t *testing.T) {
1900 1901 1902
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1903
	protest.AllowRecording(t)
1904
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1905
		bp := setFunctionBreakpoint(p, t, "main.sayhi")
1906 1907

		// continue until a parked goroutine exists
1908
		var parkedg *proc.G
1909
		for parkedg == nil {
1910
			err := proc.Continue(p)
1911
			if _, exited := err.(proc.ErrProcessExited); exited {
1912 1913 1914 1915 1916
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1917
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1918 1919
			assertNoError(err, t, "GoroutinesInfo()")

1920 1921 1922 1923
			// Search for a parked goroutine that we know for sure will have to be
			// resumed before the program can exit. This is a parked goroutine that:
			// 1. is executing main.sayhi
			// 2. hasn't called wg.Done yet
1924
			for _, g := range gs {
1925 1926 1927
				if g.Thread != nil {
					continue
				}
1928
				frames, _ := g.Stacktrace(5, false)
1929 1930 1931 1932 1933 1934 1935 1936 1937
				for _, frame := range frames {
					// line 11 is the line where wg.Done is called
					if frame.Current.Fn != nil && frame.Current.Fn.Name == "main.sayhi" && frame.Current.Line < 11 {
						parkedg = g
						break
					}
				}
				if parkedg != nil {
					break
1938 1939 1940 1941 1942 1943
				}
			}
		}

		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
1944
		assertNoError(proc.Next(p), t, "Next()")
1945

1946 1947
		if p.SelectedGoroutine().ID != parkedg.ID {
			t.Fatalf("Next did not continue on the selected goroutine, expected %d got %d", parkedg.ID, p.SelectedGoroutine().ID)
1948 1949 1950
		}
	})
}
1951 1952

func TestStepParked(t *testing.T) {
1953 1954 1955
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1956
	protest.AllowRecording(t)
1957
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1958
		bp := setFunctionBreakpoint(p, t, "main.sayhi")
1959 1960

		// continue until a parked goroutine exists
1961
		var parkedg *proc.G
1962 1963
	LookForParkedG:
		for {
1964
			err := proc.Continue(p)
1965
			if _, exited := err.(proc.ErrProcessExited); exited {
1966 1967 1968 1969 1970
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1971
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1972 1973 1974
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
1975
				if g.Thread == nil && g.CurrentLoc.Fn != nil && g.CurrentLoc.Fn.Name == "main.sayhi" {
1976 1977 1978 1979 1980 1981
					parkedg = g
					break LookForParkedG
				}
			}
		}

A
aarzilli 已提交
1982
		t.Logf("Parked g is: %v\n", parkedg)
1983
		frames, _ := parkedg.Stacktrace(20, false)
A
aarzilli 已提交
1984 1985 1986 1987 1988 1989 1990 1991
		for _, frame := range frames {
			name := ""
			if frame.Call.Fn != nil {
				name = frame.Call.Fn.Name
			}
			t.Logf("\t%s:%d in %s (%#x)", frame.Call.File, frame.Call.Line, name, frame.Current.PC)
		}

1992 1993
		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
1994
		assertNoError(proc.Step(p), t, "Step()")
1995

1996 1997
		if p.SelectedGoroutine().ID != parkedg.ID {
			t.Fatalf("Step did not continue on the selected goroutine, expected %d got %d", parkedg.ID, p.SelectedGoroutine().ID)
1998 1999 2000
		}
	})
}
2001 2002 2003 2004 2005 2006 2007 2008

func TestIssue509(t *testing.T) {
	fixturesDir := protest.FindFixturesDir()
	nomaindir := filepath.Join(fixturesDir, "nomaindir")
	cmd := exec.Command("go", "build", "-gcflags=-N -l", "-o", "debug")
	cmd.Dir = nomaindir
	assertNoError(cmd.Run(), t, "go build")
	exepath := filepath.Join(nomaindir, "debug")
2009 2010 2011 2012 2013
	defer os.Remove(exepath)
	var err error

	switch testBackend {
	case "native":
2014
		_, err = native.Launch([]string{exepath}, ".", false, []string{})
2015
	case "lldb":
2016
		_, err = gdbserial.LLDBLaunch([]string{exepath}, ".", false, []string{})
2017 2018 2019
	default:
		t.Skip("test not valid for this backend")
	}
2020 2021 2022
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
2023 2024
	if err != proc.ErrNotExecutable {
		t.Fatalf("expected error \"%v\" got \"%v\"", proc.ErrNotExecutable, err)
2025 2026 2027 2028
	}
}

func TestUnsupportedArch(t *testing.T) {
2029 2030
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major < 0 || !ver.AfterOrEqual(goversion.GoVersion{1, 6, -1, 0, 0, ""}) || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
2031 2032 2033
		// cross compile (with -N?) works only on select versions of go
		return
	}
2034

2035 2036 2037
	fixturesDir := protest.FindFixturesDir()
	infile := filepath.Join(fixturesDir, "math.go")
	outfile := filepath.Join(fixturesDir, "_math_debug_386")
2038

2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
	cmd := exec.Command("go", "build", "-gcflags=-N -l", "-o", outfile, infile)
	for _, v := range os.Environ() {
		if !strings.HasPrefix(v, "GOARCH=") {
			cmd.Env = append(cmd.Env, v)
		}
	}
	cmd.Env = append(cmd.Env, "GOARCH=386")
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("go build failed: %v: %v", err, string(out))
	}
	defer os.Remove(outfile)
2051

2052 2053 2054 2055
	var p proc.Process

	switch testBackend {
	case "native":
2056
		p, err = native.Launch([]string{outfile}, ".", false, []string{})
2057
	case "lldb":
2058
		p, err = gdbserial.LLDBLaunch([]string{outfile}, ".", false, []string{})
2059 2060 2061 2062
	default:
		t.Skip("test not valid for this backend")
	}

2063
	switch err {
2064
	case proc.ErrUnsupportedLinuxArch, proc.ErrUnsupportedWindowsArch, proc.ErrUnsupportedDarwinArch:
2065 2066
		// all good
	case nil:
A
aarzilli 已提交
2067
		p.Detach(true)
2068 2069 2070 2071 2072
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
2073

2074
func TestIssue573(t *testing.T) {
2075
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
2076
	// of the function and the internal breakpoint set by StepInto may be missed.
2077
	protest.AllowRecording(t)
2078
	withTestProcess("issue573", t, func(p proc.Process, fixture protest.Fixture) {
2079
		setFunctionBreakpoint(p, t, "main.foo")
2080 2081 2082 2083
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step() #1")
		assertNoError(proc.Step(p), t, "Step() #2") // Bug exits here.
		assertNoError(proc.Step(p), t, "Step() #3") // Third step ought to be possible; program ought not have exited.
2084 2085
	})
}
2086 2087

func TestTestvariables2Prologue(t *testing.T) {
2088
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2089
		addrEntry := p.BinInfo().LookupFunc["main.main"].Entry
2090
		addrPrologue := findFunctionLocation(p, t, "main.main")
2091 2092 2093 2094 2095
		if addrEntry == addrPrologue {
			t.Fatalf("Prologue detection failed on testvariables2.go/main.main")
		}
	})
}
2096 2097 2098 2099 2100

func TestNextDeferReturnAndDirectCall(t *testing.T) {
	// Next should not step into a deferred function if it is called
	// directly, only if it is called through a panic or a deferreturn.
	// Here we test the case where the function is called by a deferreturn
A
aarzilli 已提交
2101
	testseq("defercall", contNext, []nextTest{
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
		{9, 10},
		{10, 11},
		{11, 12},
		{12, 13},
		{13, 28}}, "main.callAndDeferReturn", t)
}

func TestNextPanicAndDirectCall(t *testing.T) {
	// Next should not step into a deferred function if it is called
	// directly, only if it is called through a panic or a deferreturn.
	// Here we test the case where the function is called by a panic
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq("defercall", contNext, []nextTest{
			{15, 16},
			{16, 17},
			{17, 18},
			{18, 6}}, "main.callAndPanic2", t)
	} else {
		testseq("defercall", contNext, []nextTest{
			{15, 16},
			{16, 17},
			{17, 18},
			{18, 5}}, "main.callAndPanic2", t)
	}
2126
}
A
aarzilli 已提交
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136

func TestStepCall(t *testing.T) {
	testseq("testnextprog", contStep, []nextTest{
		{34, 13},
		{13, 14}}, "", t)
}

func TestStepCallPtr(t *testing.T) {
	// Tests that Step works correctly when calling functions with a
	// function pointer.
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq("teststepprog", contStep, []nextTest{
			{9, 10},
			{10, 6},
			{6, 7},
			{7, 11}}, "", t)
	} else {
		testseq("teststepprog", contStep, []nextTest{
			{9, 10},
			{10, 5},
			{5, 6},
			{6, 7},
			{7, 11}}, "", t)
	}
A
aarzilli 已提交
2151 2152 2153 2154 2155
}

func TestStepReturnAndPanic(t *testing.T) {
	// Tests that Step works correctly when returning from functions
	// and when a deferred function is called when panic'ing.
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
	switch {
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 11):
		testseq("defercall", contStep, []nextTest{
			{17, 6},
			{6, 7},
			{7, 18},
			{18, 6},
			{6, 7}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 10):
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 9):
A
aarzilli 已提交
2174 2175 2176 2177 2178 2179 2180 2181 2182
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 17},
			{17, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
2183
	default:
A
aarzilli 已提交
2184 2185 2186 2187 2188 2189 2190 2191 2192
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
	}
A
aarzilli 已提交
2193 2194 2195 2196 2197
}

func TestStepDeferReturn(t *testing.T) {
	// Tests that Step works correctly when a deferred function is
	// called during a return.
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq("defercall", contStep, []nextTest{
			{11, 6},
			{6, 7},
			{7, 12},
			{12, 13},
			{13, 6},
			{6, 7},
			{7, 13},
			{13, 28}}, "", t)
	} else {
		testseq("defercall", contStep, []nextTest{
			{11, 5},
			{5, 6},
			{6, 7},
			{7, 12},
			{12, 13},
			{13, 5},
			{5, 6},
			{6, 7},
			{7, 13},
			{13, 28}}, "", t)
	}
A
aarzilli 已提交
2221 2222 2223 2224 2225
}

func TestStepIgnorePrivateRuntime(t *testing.T) {
	// Tests that Step will ignore calls to private runtime functions
	// (such as runtime.convT2E in this case)
2226 2227 2228 2229 2230 2231 2232
	switch {
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 11):
		testseq("teststepprog", contStep, []nextTest{
			{21, 14},
			{14, 15},
			{15, 22}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 10):
A
aarzilli 已提交
2233 2234 2235 2236
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
2237 2238
			{15, 22}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 7):
2239 2240 2241 2242
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
2243 2244 2245 2246
			{15, 14},
			{14, 17},
			{17, 22}}, "", t)
	default:
A
aarzilli 已提交
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
			{15, 17},
			{17, 22}}, "", t)
	}
}

func TestIssue561(t *testing.T) {
	// Step fails to make progress when PC is at a CALL instruction
	// where a breakpoint is also set.
2259
	protest.AllowRecording(t)
2260
	withTestProcess("issue561", t, func(p proc.Process, fixture protest.Fixture) {
2261
		setFileBreakpoint(p, t, fixture.Source, 10)
2262 2263
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step()")
2264
		assertLineNumber(p, t, 5, "wrong line number after Step,")
A
aarzilli 已提交
2265 2266 2267
	})
}

A
aarzilli 已提交
2268
func TestStepOut(t *testing.T) {
2269
	testseq2(t, "testnextprog", "main.helloworld", []seqTest{{contContinue, 13}, {contStepout, 35}})
A
aarzilli 已提交
2270 2271
}

A
aarzilli 已提交
2272
func TestStepConcurrentDirect(t *testing.T) {
2273 2274 2275
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
2276
	protest.AllowRecording(t)
2277
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2278
		bp := setFileBreakpoint(p, t, fixture.Source, 37)
A
aarzilli 已提交
2279

2280
		assertNoError(proc.Continue(p), t, "Continue()")
2281
		_, err := p.ClearBreakpoint(bp.Addr)
A
aarzilli 已提交
2282 2283
		assertNoError(err, t, "ClearBreakpoint()")

A
aarzilli 已提交
2284
		for _, b := range p.Breakpoints().M {
2285
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2286 2287 2288 2289 2290 2291
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

2292
		gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2293 2294 2295 2296 2297 2298

		seq := []int{37, 38, 13, 15, 16, 38}

		i := 0
		count := 0
		for {
A
aarzilli 已提交
2299
			anyerr := false
2300 2301
			if p.SelectedGoroutine().ID != gid {
				t.Errorf("Step switched to different goroutine %d %d\n", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2302 2303
				anyerr = true
			}
A
aarzilli 已提交
2304 2305 2306 2307 2308 2309
			f, ln := currentLineNumber(p, t)
			if ln != seq[i] {
				if i == 1 && ln == 40 {
					// loop exited
					break
				}
2310
				frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
A
aarzilli 已提交
2311
				if err != nil {
2312
					t.Errorf("Could not get stacktrace of goroutine %d\n", p.SelectedGoroutine().ID)
A
aarzilli 已提交
2313
				} else {
2314
					t.Logf("Goroutine %d (thread: %d):", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
A
aarzilli 已提交
2315 2316 2317 2318 2319 2320
					for _, frame := range frames {
						t.Logf("\t%s:%d (%#x)", frame.Call.File, frame.Call.Line, frame.Current.PC)
					}
				}
				t.Errorf("Program did not continue at expected location (%d) %s:%d [i %d count %d]", seq[i], f, ln, i, count)
				anyerr = true
A
aarzilli 已提交
2321
			}
A
aarzilli 已提交
2322 2323
			if anyerr {
				t.FailNow()
A
aarzilli 已提交
2324 2325 2326 2327 2328
			}
			i = (i + 1) % len(seq)
			if i == 0 {
				count++
			}
2329
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2330 2331 2332 2333 2334 2335 2336 2337 2338
		}

		if count != 100 {
			t.Fatalf("Program did not loop expected number of times: %d", count)
		}
	})
}

func TestStepConcurrentPtr(t *testing.T) {
2339 2340 2341
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
2342
	protest.AllowRecording(t)
2343
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2344
		setFileBreakpoint(p, t, fixture.Source, 24)
A
aarzilli 已提交
2345

A
aarzilli 已提交
2346
		for _, b := range p.Breakpoints().M {
2347
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2348 2349 2350 2351 2352 2353
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2354 2355 2356
		kvals := map[int]int64{}
		count := 0
		for {
2357
			err := proc.Continue(p)
2358
			_, exited := err.(proc.ErrProcessExited)
A
aarzilli 已提交
2359 2360 2361 2362 2363 2364 2365
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
2366
				for _, th := range p.ThreadList() {
2367
					t.Logf("thread %d stopped on breakpoint %v", th.ThreadID(), th.Breakpoint())
A
aarzilli 已提交
2368
				}
2369
				curbp := p.CurrentThread().Breakpoint()
2370
				t.Fatalf("Program did not continue at expected location (24): %s:%d %#x [%v] (gid %d count %d)", f, ln, currentPC(p, t), curbp, p.SelectedGoroutine().ID, count)
A
aarzilli 已提交
2371 2372
			}

2373
			gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2374

2375
			kvar := evalVariable(p, t, "k")
A
aarzilli 已提交
2376 2377 2378 2379
			k, _ := constant.Int64Val(kvar.Value)

			if oldk, ok := kvals[gid]; ok {
				if oldk >= k {
2380
					t.Fatalf("Goroutine %d did not make progress?", gid)
A
aarzilli 已提交
2381 2382 2383 2384
				}
			}
			kvals[gid] = k

2385
			assertNoError(proc.Step(p), t, "Step()")
2386
			for p.Breakpoints().HasInternalBreakpoints() {
2387 2388
				if p.SelectedGoroutine().ID == gid {
					t.Fatalf("step did not step into function call (but internal breakpoints still active?) (%d %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2389
				}
2390
				assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2391 2392
			}

2393 2394
			if p.SelectedGoroutine().ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2395 2396
			}

2397
			f, ln = assertLineNumber(p, t, 13, "Step did not step into function call")
A
aarzilli 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412

			count++
			if count > 50 {
				// this test could potentially go on for 10000 cycles, since that's
				// too slow we cut the execution after 50 cycles
				break
			}
		}

		if count == 0 {
			t.Fatalf("Breakpoint never hit")
		}
	})
}

A
aarzilli 已提交
2413
func TestStepOutDefer(t *testing.T) {
2414
	protest.AllowRecording(t)
2415
	withTestProcess("testnextdefer", t, func(p proc.Process, fixture protest.Fixture) {
2416
		bp := setFileBreakpoint(p, t, fixture.Source, 9)
2417
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2418 2419
		p.ClearBreakpoint(bp.Addr)

2420
		assertLineNumber(p, t, 9, "wrong line number")
A
aarzilli 已提交
2421

2422
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2423

2424
		f, l, _ := p.BinInfo().PCToLine(currentPC(p, t))
A
aarzilli 已提交
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
		if f == fixture.Source || l == 6 {
			t.Fatalf("wrong location %s:%d, expected to end somewhere in runtime", f, l)
		}
	})
}

func TestStepOutDeferReturnAndDirectCall(t *testing.T) {
	// StepOut should not step into a deferred function if it is called
	// directly, only if it is called through a panic.
	// Here we test the case where the function is called by a deferreturn
2435 2436 2437
	testseq2(t, "defercall", "", []seqTest{
		{contContinue, 11},
		{contStepout, 28}})
A
aarzilli 已提交
2438 2439
}

2440 2441
const maxInstructionLength uint64 = 15

A
aarzilli 已提交
2442
func TestStepOnCallPtrInstr(t *testing.T) {
2443
	protest.AllowRecording(t)
2444
	withTestProcess("teststepprog", t, func(p proc.Process, fixture protest.Fixture) {
2445
		setFileBreakpoint(p, t, fixture.Source, 10)
A
aarzilli 已提交
2446

2447
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2448 2449 2450 2451 2452 2453 2454 2455

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
2456
			regs, err := p.CurrentThread().Registers(false)
2457
			assertNoError(err, t, "Registers()")
2458
			pc := regs.PC()
D
Derek Parker 已提交
2459
			text, err := proc.Disassemble(p.CurrentThread(), regs, p.Breakpoints(), p.BinInfo(), pc, pc+maxInstructionLength)
A
aarzilli 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
			assertNoError(err, t, "Disassemble()")
			if text[0].IsCall() {
				found = true
				break
			}
			assertNoError(p.StepInstruction(), t, "StepInstruction()")
		}

		if !found {
			t.Fatal("Could not find CALL instruction")
		}

2472
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2473

2474 2475 2476 2477 2478
		if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
			assertLineNumber(p, t, 6, "Step continued to wrong line,")
		} else {
			assertLineNumber(p, t, 5, "Step continued to wrong line,")
		}
A
aarzilli 已提交
2479 2480
	})
}
2481 2482

func TestIssue594(t *testing.T) {
2483 2484 2485 2486 2487 2488 2489 2490
	if runtime.GOOS == "darwin" && testBackend == "lldb" {
		// debugserver will receive an EXC_BAD_ACCESS for this, at that point
		// there is no way to reconvert this exception into a unix signal and send
		// it to the process.
		// This is a bug in debugserver/lldb:
		//  https://bugs.llvm.org//show_bug.cgi?id=22868
		return
	}
2491 2492 2493 2494
	// Exceptions that aren't caused by breakpoints should be propagated
	// back to the target.
	// In particular the target should be able to cause a nil pointer
	// dereference panic and recover from it.
2495
	protest.AllowRecording(t)
2496
	withTestProcess("issue594", t, func(p proc.Process, fixture protest.Fixture) {
2497
		assertNoError(proc.Continue(p), t, "Continue()")
2498 2499 2500 2501 2502 2503 2504 2505 2506
		var f string
		var ln int
		if testBackend == "rr" {
			frame, err := findFirstNonRuntimeFrame(p)
			assertNoError(err, t, "findFirstNonRuntimeFrame")
			f, ln = frame.Current.File, frame.Current.Line
		} else {
			f, ln = currentLineNumber(p, t)
		}
2507 2508 2509 2510 2511
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2512 2513 2514 2515 2516

func TestStepOutPanicAndDirectCall(t *testing.T) {
	// StepOut should not step into a deferred function if it is called
	// directly, only if it is called through a panic.
	// Here we test the case where the function is called by a panic
2517 2518 2519 2520 2521 2522 2523 2524 2525
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq2(t, "defercall", "", []seqTest{
			{contContinue, 17},
			{contStepout, 6}})
	} else {
		testseq2(t, "defercall", "", []seqTest{
			{contContinue, 17},
			{contStepout, 5}})
	}
A
aarzilli 已提交
2526
}
E
Evgeny L 已提交
2527 2528 2529 2530 2531 2532 2533

func TestWorkDir(t *testing.T) {
	wd := os.TempDir()
	// For Darwin `os.TempDir()` returns `/tmp` which is symlink to `/private/tmp`.
	if runtime.GOOS == "darwin" {
		wd = "/private/tmp"
	}
2534
	protest.AllowRecording(t)
2535
	withTestProcessArgs("workdir", t, wd, []string{}, 0, func(p proc.Process, fixture protest.Fixture) {
2536
		setFileBreakpoint(p, t, fixture.Source, 14)
2537
		proc.Continue(p)
2538
		v := evalVariable(p, t, "pwd")
E
Evgeny L 已提交
2539 2540 2541 2542
		str := constant.StringVal(v.Value)
		if wd != str {
			t.Fatalf("Expected %s got %s\n", wd, str)
		}
2543
	})
E
Evgeny L 已提交
2544
}
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555

func TestNegativeIntEvaluation(t *testing.T) {
	testcases := []struct {
		name  string
		typ   string
		value interface{}
	}{
		{"ni8", "int8", int64(-5)},
		{"ni16", "int16", int64(-5)},
		{"ni32", "int32", int64(-5)},
	}
2556
	protest.AllowRecording(t)
2557
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2558
		assertNoError(proc.Continue(p), t, "Continue()")
2559
		for _, tc := range testcases {
2560
			v := evalVariable(p, t, tc.name)
2561 2562 2563 2564 2565 2566 2567 2568 2569
			if typ := v.RealType.String(); typ != tc.typ {
				t.Fatalf("Wrong type for variable %q: %q (expected: %q)", tc.name, typ, tc.typ)
			}
			if val, _ := constant.Int64Val(v.Value); val != tc.value {
				t.Fatalf("Wrong value for variable %q: %v (expected: %v)", tc.name, val, tc.value)
			}
		}
	})
}
2570 2571 2572

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
2573
	protest.AllowRecording(t)
2574
	withTestProcess("issue683", t, func(p proc.Process, fixture protest.Fixture) {
2575
		setFunctionBreakpoint(p, t, "main.main")
2576
		assertNoError(proc.Continue(p), t, "First Continue()")
2577 2578 2579
		for i := 0; i < 20; i++ {
			// eventually an error about the source file not being found will be
			// returned, the important thing is that we shouldn't panic
2580
			err := proc.Step(p)
2581 2582 2583 2584
			if err != nil {
				break
			}
		}
2585 2586 2587 2588
	})
}

func TestIssue664(t *testing.T) {
2589
	protest.AllowRecording(t)
2590
	withTestProcess("issue664", t, func(p proc.Process, fixture protest.Fixture) {
2591
		setFileBreakpoint(p, t, fixture.Source, 4)
2592 2593
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
2594
		assertLineNumber(p, t, 5, "Did not continue to correct location,")
2595 2596
	})
}
A
Alessandro Arzilli 已提交
2597 2598 2599

// Benchmarks (*Processs).Continue + (*Scope).FunctionArguments
func BenchmarkTrace(b *testing.B) {
2600
	protest.AllowRecording(b)
2601
	withTestProcess("traceperf", b, func(p proc.Process, fixture protest.Fixture) {
2602
		setFunctionBreakpoint(p, b, "main.PerfCheck")
A
Alessandro Arzilli 已提交
2603 2604
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
2605 2606
			assertNoError(proc.Continue(p), b, "Continue()")
			s, err := proc.GoroutineScope(p.CurrentThread())
A
Alessandro Arzilli 已提交
2607
			assertNoError(err, b, "Scope()")
2608
			_, err = s.FunctionArguments(proc.LoadConfig{false, 0, 64, 0, 3, 0})
A
Alessandro Arzilli 已提交
2609 2610 2611 2612 2613
			assertNoError(err, b, "FunctionArguments()")
		}
		b.StopTimer()
	})
}
A
Alessandro Arzilli 已提交
2614 2615 2616 2617 2618 2619

func TestNextInDeferReturn(t *testing.T) {
	// runtime.deferreturn updates the G struct in a way that for one
	// instruction leaves the curg._defer field non-nil but with curg._defer.fn
	// field being nil.
	// We need to deal with this without panicing.
2620
	protest.AllowRecording(t)
2621
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
2622
		setFunctionBreakpoint(p, t, "runtime.deferreturn")
2623
		assertNoError(proc.Continue(p), t, "First Continue()")
2624 2625 2626 2627

		// Set a breakpoint on the deferred function so that the following loop
		// can not step out of the runtime.deferreturn and all the way to the
		// point where the target program panics.
2628
		setFunctionBreakpoint(p, t, "main.sampleFunction")
A
Alessandro Arzilli 已提交
2629
		for i := 0; i < 20; i++ {
2630 2631 2632 2633 2634 2635
			loc, err := p.CurrentThread().Location()
			assertNoError(err, t, "CurrentThread().Location()")
			t.Logf("at %#x %s:%d", loc.PC, loc.File, loc.Line)
			if loc.Fn != nil && loc.Fn.Name == "main.sampleFunction" {
				break
			}
2636
			assertNoError(proc.Next(p), t, fmt.Sprintf("Next() %d", i))
A
Alessandro Arzilli 已提交
2637 2638 2639 2640
		}
	})
}

2641
func getg(goid int, gs []*proc.G) *proc.G {
A
Alessandro Arzilli 已提交
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
	for _, g := range gs {
		if g.ID == goid {
			return g
		}
	}
	return nil
}

func TestStacktraceWithBarriers(t *testing.T) {
	// Go's Garbage Collector will insert stack barriers into stacks.
	// This stack barrier is inserted by overwriting the return address for the
	// stack frame with the address of runtime.stackBarrier.
	// The original return address is saved into the stkbar slice inside the G
	// struct.
2656

2657
	// In Go 1.9 stack barriers have been removed and this test must be disabled.
2658
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
2659 2660 2661
		return
	}

2662 2663 2664 2665 2666
	// In Go 1.8 stack barriers are not inserted by default, this enables them.
	godebugOld := os.Getenv("GODEBUG")
	defer os.Setenv("GODEBUG", godebugOld)
	os.Setenv("GODEBUG", "gcrescanstacks=1")

2667
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2668
		// We want to get a user goroutine with a stack barrier, to get that we execute the program until runtime.gcInstallStackBarrier is executed AND the goroutine it was executed onto contains a call to main.bottomUpTree
2669
		setFunctionBreakpoint(p, t, "runtime.gcInstallStackBarrier")
A
Alessandro Arzilli 已提交
2670 2671
		stackBarrierGoids := []int{}
		for len(stackBarrierGoids) == 0 {
2672
			err := proc.Continue(p)
2673
			if _, exited := err.(proc.ErrProcessExited); exited {
2674 2675 2676 2677
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
2678
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
Alessandro Arzilli 已提交
2679
			assertNoError(err, t, "GoroutinesInfo()")
2680
			for _, th := range p.ThreadList() {
2681
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
A
Alessandro Arzilli 已提交
2682 2683 2684
					continue
				}

2685
				goidVar := evalVariable(p, t, "gp.goid")
A
Alessandro Arzilli 已提交
2686 2687 2688
				goid, _ := constant.Int64Val(goidVar.Value)

				if g := getg(int(goid), gs); g != nil {
2689
					stack, err := g.Stacktrace(50, false)
A
Alessandro Arzilli 已提交
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
					assertNoError(err, t, fmt.Sprintf("Stacktrace(goroutine = %d)", goid))
					for _, frame := range stack {
						if frame.Current.Fn != nil && frame.Current.Fn.Name == "main.bottomUpTree" {
							stackBarrierGoids = append(stackBarrierGoids, int(goid))
							break
						}
					}
				}
			}
		}

		if len(stackBarrierGoids) == 0 {
			t.Fatalf("Could not find a goroutine with stack barriers")
		}

		t.Logf("stack barrier goids: %v\n", stackBarrierGoids)

2707
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
Alessandro Arzilli 已提交
2708

2709
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
Alessandro Arzilli 已提交
2710 2711 2712 2713 2714
		assertNoError(err, t, "GoroutinesInfo()")

		for _, goid := range stackBarrierGoids {
			g := getg(goid, gs)

2715
			stack, err := g.Stacktrace(200, false)
A
Alessandro Arzilli 已提交
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
			assertNoError(err, t, "Stacktrace()")

			// Check that either main.main or main.main.func1 appear in the
			// stacktrace of this goroutine, if we failed at resolving stack barriers
			// correctly the stacktrace will be truncated and neither main.main or
			// main.main.func1 will appear
			found := false
			for _, frame := range stack {
				if frame.Current.Fn == nil {
					continue
				}
				if name := frame.Current.Fn.Name; name == "main.main" || name == "main.main.func1" {
					found = true
				}
			}

			t.Logf("Stacktrace for %d:\n", goid)
			for _, frame := range stack {
				name := "<>"
				if frame.Current.Fn != nil {
					name = frame.Current.Fn.Name
				}
2738
				t.Logf("\t%s [CFA: %x Ret: %x] at %s:%d", name, frame.Regs.CFA, frame.Ret, frame.Current.File, frame.Current.Line)
A
Alessandro Arzilli 已提交
2739 2740 2741
			}

			if !found {
2742
				t.Logf("Truncated stacktrace for %d\n", goid)
A
Alessandro Arzilli 已提交
2743 2744 2745 2746
			}
		}
	})
}
2747 2748

func TestAttachDetach(t *testing.T) {
2749 2750 2751 2752 2753 2754
	if testBackend == "lldb" && runtime.GOOS == "linux" {
		bs, _ := ioutil.ReadFile("/proc/sys/kernel/yama/ptrace_scope")
		if bs == nil || strings.TrimSpace(string(bs)) != "0" {
			t.Logf("can not run TestAttachDetach: %v\n", bs)
			return
		}
2755
	}
2756 2757 2758
	if testBackend == "rr" {
		return
	}
2759 2760 2761 2762 2763
	var buildFlags protest.BuildFlags
	if buildMode == "pie" {
		buildFlags |= protest.BuildModePIE
	}
	fixture := protest.BuildFixture("testnextnethttp", buildFlags)
2764 2765 2766 2767 2768 2769 2770 2771
	cmd := exec.Command(fixture.Path)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	assertNoError(cmd.Start(), t, "starting fixture")

	// wait for testnextnethttp to start listening
	t0 := time.Now()
	for {
2772
		conn, err := net.Dial("tcp", "127.0.0.1:9191")
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(50 * time.Millisecond)
		if time.Since(t0) > 10*time.Second {
			t.Fatal("fixture did not start")
		}
	}

2783
	var p proc.Process
2784 2785 2786 2787
	var err error

	switch testBackend {
	case "native":
2788
		p, err = native.Attach(cmd.Process.Pid, []string{})
2789 2790 2791 2792 2793
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
2794
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path, []string{})
2795 2796 2797 2798
	default:
		err = fmt.Errorf("unknown backend %q", testBackend)
	}

2799 2800 2801
	assertNoError(err, t, "Attach")
	go func() {
		time.Sleep(1 * time.Second)
2802
		http.Get("http://127.0.0.1:9191")
2803 2804
	}()

2805
	assertNoError(proc.Continue(p), t, "Continue")
2806
	assertLineNumber(p, t, 11, "Did not continue to correct location,")
2807 2808 2809

	assertNoError(p.Detach(false), t, "Detach")

2810
	resp, err := http.Get("http://127.0.0.1:9191/nobp")
2811 2812 2813
	assertNoError(err, t, "Page request after detach")
	bs, err := ioutil.ReadAll(resp.Body)
	assertNoError(err, t, "Reading /nobp page")
2814
	if out := string(bs); !strings.Contains(out, "hello, world!") {
2815 2816 2817 2818 2819
		t.Fatalf("/nobp page does not contain \"hello, world!\": %q", out)
	}

	cmd.Process.Kill()
}
2820 2821

func TestVarSum(t *testing.T) {
2822
	protest.AllowRecording(t)
2823 2824
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2825
		sumvar := evalVariable(p, t, "s1[0] + s1[1]")
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
		sumvarstr := constant.StringVal(sumvar.Value)
		if sumvarstr != "onetwo" {
			t.Fatalf("s1[0] + s1[1] == %q (expected \"onetwo\")", sumvarstr)
		}
		if sumvar.Len != int64(len(sumvarstr)) {
			t.Fatalf("sumvar.Len == %d (expected %d)", sumvar.Len, len(sumvarstr))
		}
	})
}

func TestPackageWithPathVar(t *testing.T) {
2837
	protest.AllowRecording(t)
2838 2839
	withTestProcess("pkgrenames", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2840 2841
		evalVariable(p, t, "pkg.SomeVar")
		evalVariable(p, t, "pkg.SomeVar.X")
2842 2843
	})
}
2844 2845

func TestEnvironment(t *testing.T) {
2846
	protest.AllowRecording(t)
2847 2848 2849
	os.Setenv("SOMEVAR", "bah")
	withTestProcess("testenv", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2850
		v := evalVariable(p, t, "x")
2851 2852 2853 2854 2855 2856 2857
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != "bah" {
			t.Fatalf("value of v is %q (expected \"bah\")", vv)
		}
	})
}
2858 2859

func getFrameOff(p proc.Process, t *testing.T) int64 {
2860
	frameoffvar := evalVariable(p, t, "runtime.frameoff")
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
	frameoff, _ := constant.Int64Val(frameoffvar.Value)
	return frameoff
}

func TestRecursiveNext(t *testing.T) {
	protest.AllowRecording(t)
	testcases := []nextTest{
		{6, 7},
		{7, 10},
		{10, 11},
		{11, 17},
	}
	testseq("increment", contNext, testcases, "main.Increment", t)

	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
2876
		bp := setFunctionBreakpoint(p, t, "main.Increment")
2877
		assertNoError(proc.Continue(p), t, "Continue")
2878
		_, err := p.ClearBreakpoint(bp.Addr)
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
		assertNoError(err, t, "ClearBreakpoint")
		assertNoError(proc.Next(p), t, "Next 1")
		assertNoError(proc.Next(p), t, "Next 2")
		assertNoError(proc.Next(p), t, "Next 3")
		frameoff0 := getFrameOff(p, t)
		assertNoError(proc.Step(p), t, "Step")
		frameoff1 := getFrameOff(p, t)
		if frameoff0 == frameoff1 {
			t.Fatalf("did not step into function?")
		}
2889
		assertLineNumber(p, t, 6, "program did not continue to expected location,")
2890
		assertNoError(proc.Next(p), t, "Next 4")
2891
		assertLineNumber(p, t, 7, "program did not continue to expected location,")
2892
		assertNoError(proc.StepOut(p), t, "StepOut")
2893
		assertLineNumber(p, t, 11, "program did not continue to expected location,")
2894 2895 2896 2897 2898 2899
		frameoff2 := getFrameOff(p, t)
		if frameoff0 != frameoff2 {
			t.Fatalf("frame offset mismatch %x != %x", frameoff0, frameoff2)
		}
	})
}
2900 2901 2902 2903 2904 2905 2906

// TestIssue877 ensures that the environment variables starting with DYLD_ and LD_
// are passed when executing the binary on OSX via debugserver
func TestIssue877(t *testing.T) {
	if runtime.GOOS != "darwin" && testBackend == "lldb" {
		return
	}
A
aarzilli 已提交
2907 2908 2909 2910 2911
	if os.Getenv("TRAVIS") == "true" && runtime.GOOS == "darwin" {
		// Something changed on Travis side that makes the Go compiler fail if
		// DYLD_LIBRARY_PATH is set.
		t.Skip("broken")
	}
2912 2913 2914 2915
	const envval = "/usr/local/lib"
	os.Setenv("DYLD_LIBRARY_PATH", envval)
	withTestProcess("issue877", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2916
		v := evalVariable(p, t, "dyldenv")
2917 2918 2919 2920 2921 2922 2923
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != envval {
			t.Fatalf("value of v is %q (expected %q)", vv, envval)
		}
	})
}
2924 2925 2926 2927

func TestIssue893(t *testing.T) {
	// Test what happens when next is called immediately after launching the
	// executable, acceptable behaviors are: (a) no error, (b) no source at PC
2928
	// error, (c) program runs to completion
2929 2930 2931 2932 2933 2934
	protest.AllowRecording(t)
	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		err := proc.Next(p)
		if err == nil {
			return
		}
2935
		if _, ok := err.(*frame.ErrNoFDEForPC); ok {
2936 2937
			return
		}
2938
		if _, ok := err.(proc.ErrThreadBlocked); ok {
2939
			return
2940
		}
2941
		if _, ok := err.(*proc.ErrNoSourceForPC); ok {
2942
			return
2943
		}
2944
		if _, ok := err.(proc.ErrProcessExited); ok {
2945 2946
			return
		}
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
		assertNoError(err, t, "Next")
	})
}

func TestStepInstructionNoGoroutine(t *testing.T) {
	protest.AllowRecording(t)
	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		// Call StepInstruction immediately after launching the program, it should
		// work even though no goroutine is selected.
		assertNoError(p.StepInstruction(), t, "StepInstruction")
	})
}
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970

func TestIssue871(t *testing.T) {
	protest.AllowRecording(t)
	withTestProcess("issue871", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")

		var scope *proc.EvalScope
		var err error
		if testBackend == "rr" {
			var frame proc.Stackframe
			frame, err = findFirstNonRuntimeFrame(p)
			if err == nil {
2971
				scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
			}
		} else {
			scope, err = proc.GoroutineScope(p.CurrentThread())
		}
		assertNoError(err, t, "scope")

		locals, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables")

		foundA, foundB := false, false

		for _, v := range locals {
			t.Logf("local %v", v)
			switch v.Name {
			case "a":
				foundA = true
				if v.Flags&proc.VariableEscaped == 0 {
					t.Errorf("variable a not flagged as escaped")
				}
			case "b":
				foundB = true
			}
		}

		if !foundA {
			t.Errorf("variable a not found")
		}

		if !foundB {
			t.Errorf("variable b not found")
		}
	})
}
A
aarzilli 已提交
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044

func TestShadowedFlag(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
		return
	}
	withTestProcess("testshadow", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope")
		locals, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables")
		foundShadowed := false
		foundNonShadowed := false
		for _, v := range locals {
			if v.Flags&proc.VariableShadowed != 0 {
				if v.Name != "a" {
					t.Errorf("wrong shadowed variable %s", v.Name)
				}
				foundShadowed = true
				if n, _ := constant.Int64Val(v.Value); n != 0 {
					t.Errorf("wrong value for shadowed variable a: %d", n)
				}
			} else {
				if v.Name != "a" {
					t.Errorf("wrong non-shadowed variable %s", v.Name)
				}
				foundNonShadowed = true
				if n, _ := constant.Int64Val(v.Value); n != 1 {
					t.Errorf("wrong value for non-shadowed variable a: %d", n)
				}
			}
		}
		if !foundShadowed {
			t.Error("could not find any shadowed variable")
		}
		if !foundNonShadowed {
			t.Error("could not find any non-shadowed variable")
		}
	})
}
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060

func TestAttachStripped(t *testing.T) {
	if testBackend == "lldb" && runtime.GOOS == "linux" {
		bs, _ := ioutil.ReadFile("/proc/sys/kernel/yama/ptrace_scope")
		if bs == nil || strings.TrimSpace(string(bs)) != "0" {
			t.Logf("can not run TestAttachStripped: %v\n", bs)
			return
		}
	}
	if testBackend == "rr" {
		return
	}
	if runtime.GOOS == "darwin" {
		t.Log("-s does not produce stripped executables on macOS")
		return
	}
3061 3062 3063
	if buildMode != "" {
		t.Skip("not enabled with buildmode=PIE")
	}
3064 3065 3066 3067 3068 3069 3070 3071 3072
	fixture := protest.BuildFixture("testnextnethttp", protest.LinkStrip)
	cmd := exec.Command(fixture.Path)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	assertNoError(cmd.Start(), t, "starting fixture")

	// wait for testnextnethttp to start listening
	t0 := time.Now()
	for {
3073
		conn, err := net.Dial("tcp", "127.0.0.1:9191")
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(50 * time.Millisecond)
		if time.Since(t0) > 10*time.Second {
			t.Fatal("fixture did not start")
		}
	}

	var p proc.Process
	var err error

	switch testBackend {
	case "native":
3089
		p, err = native.Attach(cmd.Process.Pid, []string{})
3090 3091 3092 3093 3094
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
3095
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path, []string{})
3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109
	default:
		t.Fatalf("unknown backend %q", testBackend)
	}

	t.Logf("error is %v", err)

	if err == nil {
		p.Detach(true)
		t.Fatalf("expected error after attach, got nothing")
	} else {
		cmd.Process.Kill()
	}
	os.Remove(fixture.Path)
}
3110 3111 3112 3113 3114

func TestIssue844(t *testing.T) {
	// Conditional breakpoints should not prevent next from working if their
	// condition isn't met.
	withTestProcess("nextcond", t, func(p proc.Process, fixture protest.Fixture) {
3115 3116
		setFileBreakpoint(p, t, fixture.Source, 9)
		condbp := setFileBreakpoint(p, t, fixture.Source, 10)
3117 3118 3119 3120 3121 3122 3123
		condbp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "11"},
		}
		assertNoError(proc.Continue(p), t, "Continue")
		assertNoError(proc.Next(p), t, "Next")
3124
		assertLineNumber(p, t, 10, "continued to wrong location,")
3125 3126
	})
}
A
aarzilli 已提交
3127

3128
func logStacktrace(t *testing.T, bi *proc.BinaryInfo, frames []proc.Stackframe) {
A
aarzilli 已提交
3129 3130 3131 3132 3133 3134 3135
	for j := range frames {
		name := "?"
		if frames[j].Current.Fn != nil {
			name = frames[j].Current.Fn.Name
		}

		t.Logf("\t%#x %#x %#x %s at %s:%d\n", frames[j].Call.PC, frames[j].FrameOffset(), frames[j].FramePointerOffset(), name, filepath.Base(frames[j].Call.File), frames[j].Call.Line)
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
		if frames[j].TopmostDefer != nil {
			f, l, fn := bi.PCToLine(frames[j].TopmostDefer.DeferredPC)
			fnname := ""
			if fn != nil {
				fnname = fn.Name
			}
			t.Logf("\t\ttopmost defer: %#x %s at %s:%d\n", frames[j].TopmostDefer.DeferredPC, fnname, f, l)
		}
		for deferIdx, _defer := range frames[j].Defers {
			f, l, fn := bi.PCToLine(_defer.DeferredPC)
			fnname := ""
			if fn != nil {
				fnname = fn.Name
			}
			t.Logf("\t\t%d defer: %#x %s at %s:%d\n", deferIdx, _defer.DeferredPC, fnname, f, l)

		}
A
aarzilli 已提交
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
	}
}

// stacktraceCheck checks that all the functions listed in tc appear in
// frames in the same order.
// Checks that all the functions in tc starting with "C." or with "!" are in
// a systemstack frame.
// Returns a slice m where m[i] is the index in frames of the function tc[i]
// or nil if any check fails.
func stacktraceCheck(t *testing.T, tc []string, frames []proc.Stackframe) []int {
	m := make([]int, len(tc))
	i, j := 0, 0
	for i < len(tc) {
		tcname := tc[i]
		tcsystem := strings.HasPrefix(tcname, "C.")
		if tcname[0] == '!' {
			tcsystem = true
			tcname = tcname[1:]
		}
		for j < len(frames) {
			name := "?"
			if frames[j].Current.Fn != nil {
				name = frames[j].Current.Fn.Name
			}
			if name == tcname {
				m[i] = j
				if tcsystem != frames[j].SystemStack {
					t.Logf("system stack check failed for frame %d (expected %v got %v)", j, tcsystem, frames[j].SystemStack)
					t.Logf("expected: %v\n", tc)
					return nil
				}
				break
			}

			j++
		}
		if j >= len(frames) {
			t.Logf("couldn't find frame %d %s", i, tc)
			t.Logf("expected: %v\n", tc)
			return nil
		}

		i++
	}
	return m
}

func frameInFile(frame proc.Stackframe, file string) bool {
	for _, loc := range []proc.Location{frame.Current, frame.Call} {
		if !strings.HasSuffix(loc.File, "/"+file) && !strings.HasSuffix(loc.File, "\\"+file) {
			return false
		}
		if loc.Line <= 0 {
			return false
		}
	}
	return true
}

func TestCgoStacktrace(t *testing.T) {
	if runtime.GOOS == "windows" {
		ver, _ := goversion.Parse(runtime.Version())
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
			t.Skip("disabled on windows with go before version 1.9")
		}
	}
	if runtime.GOOS == "darwin" {
		ver, _ := goversion.Parse(runtime.Version())
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 8, -1, 0, 0, ""}) {
			t.Skip("disabled on macOS with go before version 1.8")
		}
	}

	// Tests that:
	// a) we correctly identify the goroutine while we are executing cgo code
	// b) that we can stitch together the system stack (where cgo code
	// executes) and the normal goroutine stack

	// Each test case describes how the stack trace should appear after a
	// continue. The first function on each test case is the topmost function
	// that should be found on the stack, the actual stack trace can have more
	// frame than those listed here but all the frames listed must appear in
	// the specified order.
	testCases := [][]string{
		[]string{"main.main"},
		[]string{"C.helloworld_pt2", "C.helloworld", "main.main"},
		[]string{"main.helloWorldS", "main.helloWorld", "C.helloworld_pt2", "C.helloworld", "main.main"},
		[]string{"C.helloworld_pt4", "C.helloworld_pt3", "main.helloWorldS", "main.helloWorld", "C.helloworld_pt2", "C.helloworld", "main.main"},
		[]string{"main.helloWorld2", "C.helloworld_pt4", "C.helloworld_pt3", "main.helloWorldS", "main.helloWorld", "C.helloworld_pt2", "C.helloworld", "main.main"}}

	var gid int

	frameOffs := map[string]int64{}
	framePointerOffs := map[string]int64{}

	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
		for itidx, tc := range testCases {
			assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue at iteration step %d", itidx))

			g, err := proc.GetG(p.CurrentThread())
			assertNoError(err, t, fmt.Sprintf("GetG at iteration step %d", itidx))

			if itidx == 0 {
				gid = g.ID
			} else {
				if gid != g.ID {
					t.Fatalf("wrong goroutine id at iteration step %d (expected %d got %d)", itidx, gid, g.ID)
				}
			}

3263
			frames, err := g.Stacktrace(100, false)
A
aarzilli 已提交
3264 3265 3266
			assertNoError(err, t, fmt.Sprintf("Stacktrace at iteration step %d", itidx))

			t.Logf("iteration step %d", itidx)
3267
			logStacktrace(t, p.BinInfo(), frames)
A
aarzilli 已提交
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303

			m := stacktraceCheck(t, tc, frames)
			mismatch := (m == nil)

			for i, j := range m {
				if strings.HasPrefix(tc[i], "C.hellow") {
					if !frameInFile(frames[j], "hello.c") {
						t.Logf("position in %q is %s:%d (call %s:%d)", tc[i], frames[j].Current.File, frames[j].Current.Line, frames[j].Call.File, frames[j].Call.Line)
						mismatch = true
						break
					}
				}
				if frameOff, ok := frameOffs[tc[i]]; ok {
					if frameOff != frames[j].FrameOffset() {
						t.Logf("frame %s offset mismatch", tc[i])
					}
					if framePointerOffs[tc[i]] != frames[j].FramePointerOffset() {
						t.Logf("frame %s pointer offset mismatch", tc[i])
					}
				} else {
					frameOffs[tc[i]] = frames[j].FrameOffset()
					framePointerOffs[tc[i]] = frames[j].FramePointerOffset()
				}
			}

			// also check that ThreadStacktrace produces the same list of frames
			threadFrames, err := proc.ThreadStacktrace(p.CurrentThread(), 100)
			assertNoError(err, t, fmt.Sprintf("ThreadStacktrace at iteration step %d", itidx))

			if len(threadFrames) != len(frames) {
				mismatch = true
			} else {
				for j := range frames {
					if frames[j].Current.File != threadFrames[j].Current.File || frames[j].Current.Line != threadFrames[j].Current.Line {
						t.Logf("stack mismatch between goroutine stacktrace and thread stacktrace")
						t.Logf("thread stacktrace:")
3304
						logStacktrace(t, p.BinInfo(), threadFrames)
A
aarzilli 已提交
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
						mismatch = true
						break
					}
				}
			}
			if mismatch {
				t.Fatal("see previous loglines")
			}
		}
	})
}

func TestCgoSources(t *testing.T) {
	if runtime.GOOS == "windows" {
		ver, _ := goversion.Parse(runtime.Version())
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
			t.Skip("disabled on windows with go before version 1.9")
		}
	}

	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
		sources := p.BinInfo().Sources
		for _, needle := range []string{"main.go", "hello.c"} {
			found := false
			for _, k := range sources {
				if strings.HasSuffix(k, "/"+needle) || strings.HasSuffix(k, "\\"+needle) {
					found = true
					break
				}
			}
			if !found {
				t.Errorf("File %s not found", needle)
			}
		}
	})
}

func TestSystemstackStacktrace(t *testing.T) {
	// check that we can follow a stack switch initiated by runtime.systemstack()
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
3345
		setFunctionBreakpoint(p, t, "runtime.startpanic_m")
A
aarzilli 已提交
3346 3347 3348 3349
		assertNoError(proc.Continue(p), t, "first continue")
		assertNoError(proc.Continue(p), t, "second continue")
		g, err := proc.GetG(p.CurrentThread())
		assertNoError(err, t, "GetG")
3350
		frames, err := g.Stacktrace(100, false)
A
aarzilli 已提交
3351
		assertNoError(err, t, "stacktrace")
3352
		logStacktrace(t, p.BinInfo(), frames)
3353
		m := stacktraceCheck(t, []string{"!runtime.startpanic_m", "runtime.gopanic", "main.main"}, frames)
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
		if m == nil {
			t.Fatal("see previous loglines")
		}
	})
}

func TestSystemstackOnRuntimeNewstack(t *testing.T) {
	// The bug being tested here manifests as follows:
	// - set a breakpoint somewhere or interrupt the program with Ctrl-C
	// - try to look at stacktraces of other goroutines
	// If one of the other goroutines is resizing its own stack the stack
	// command won't work for it.
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
3367
		setFunctionBreakpoint(p, t, "main.main")
3368
		assertNoError(proc.Continue(p), t, "first continue")
3369

3370 3371
		g, err := proc.GetG(p.CurrentThread())
		assertNoError(err, t, "GetG")
3372 3373
		mainGoroutineID := g.ID

3374
		setFunctionBreakpoint(p, t, "runtime.newstack")
3375 3376 3377 3378 3379 3380 3381 3382
		for {
			assertNoError(proc.Continue(p), t, "second continue")
			g, err = proc.GetG(p.CurrentThread())
			assertNoError(err, t, "GetG")
			if g.ID == mainGoroutineID {
				break
			}
		}
3383
		frames, err := g.Stacktrace(100, false)
3384
		assertNoError(err, t, "stacktrace")
3385
		logStacktrace(t, p.BinInfo(), frames)
3386
		m := stacktraceCheck(t, []string{"!runtime.newstack", "main.main"}, frames)
A
aarzilli 已提交
3387 3388 3389 3390 3391
		if m == nil {
			t.Fatal("see previous loglines")
		}
	})
}
3392 3393 3394 3395 3396

func TestIssue1034(t *testing.T) {
	// The external linker on macOS produces an abbrev for DW_TAG_subprogram
	// without the "has children" flag, we should support this.
	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
3397
		setFunctionBreakpoint(p, t, "main.main")
3398
		assertNoError(proc.Continue(p), t, "Continue()")
3399
		frames, err := p.SelectedGoroutine().Stacktrace(10, false)
3400
		assertNoError(err, t, "Stacktrace")
3401
		scope := proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frames[2:]...)
3402 3403 3404 3405 3406 3407 3408
		args, _ := scope.FunctionArguments(normalLoadConfig)
		assertNoError(err, t, "FunctionArguments()")
		if len(args) > 0 {
			t.Fatalf("wrong number of arguments for frame %v (%d)", frames[2], len(args))
		}
	})
}
3409 3410 3411 3412 3413

func TestIssue1008(t *testing.T) {
	// The external linker on macOS inserts "end of sequence" extended opcodes
	// in debug_line. which we should support correctly.
	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
3414
		setFunctionBreakpoint(p, t, "main.main")
3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
		assertNoError(proc.Continue(p), t, "Continue()")
		loc, err := p.CurrentThread().Location()
		assertNoError(err, t, "CurrentThread().Location()")
		t.Logf("location %v\n", loc)
		if !strings.HasSuffix(loc.File, "/main.go") {
			t.Errorf("unexpected location %s:%d\n", loc.File, loc.Line)
		}
		if loc.Line > 31 {
			t.Errorf("unexpected location %s:%d (file only has 30 lines)\n", loc.File, loc.Line)
		}
	})
}
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454

func TestDeclLine(t *testing.T) {
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		t.Skip("go 1.9 and prior versions do not emit DW_AT_decl_line")
	}

	withTestProcess("decllinetest", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope (1)")
		vars, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables (1)")
		if len(vars) != 1 {
			t.Fatalf("wrong number of variables %d", len(vars))
		}

		assertNoError(proc.Continue(p), t, "Continue")
		scope, err = proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope (2)")
		scope.LocalVariables(normalLoadConfig)
		vars, err = scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables (2)")
		if len(vars) != 2 {
			t.Fatalf("wrong number of variables %d", len(vars))
		}
	})
}
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464

func TestIssue1137(t *testing.T) {
	withTestProcess("dotpackagesiface", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		v := evalVariable(p, t, "iface")
		assertNoError(v.Unreadable, t, "iface unreadable")
		v2 := evalVariable(p, t, "iface2")
		assertNoError(v2.Unreadable, t, "iface2 unreadable")
	})
}
3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483

func TestIssue1101(t *testing.T) {
	// If a breakpoint is hit close to process death on a thread that isn't the
	// group leader the process could die while we are trying to stop it.
	//
	// This can be easily reproduced by having the goroutine that's executing
	// main.main (which will almost always run on the thread group leader) wait
	// for a second goroutine before exiting, then setting a breakpoint on the
	// second goroutine and stepping through it (see TestIssue1101 in
	// proc_test.go).
	//
	// When stepping over the return instruction of main.f the deferred
	// wg.Done() call will be executed which will cause the main goroutine to
	// resume and proceed to exit. Both the temporary breakpoint on wg.Done and
	// the temporary breakpoint on the return address of main.f will be in
	// close proximity to main.main calling os.Exit() and causing the death of
	// the thread group leader.

	withTestProcess("issue1101", t, func(p proc.Process, fixture protest.Fixture) {
3484
		setFunctionBreakpoint(p, t, "main.f")
3485 3486 3487 3488 3489 3490 3491 3492 3493
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next() 1")
		assertNoError(proc.Next(p), t, "Next() 2")
		lastCmd := "Next() 3"
		exitErr := proc.Next(p)
		if exitErr == nil {
			lastCmd = "final Continue()"
			exitErr = proc.Continue(p)
		}
3494
		if pexit, exited := exitErr.(proc.ErrProcessExited); exited {
3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505
			if pexit.Status != 2 && testBackend != "lldb" {
				// looks like there's a bug with debugserver on macOS that sometimes
				// will report exit status 0 instead of the proper exit status.
				t.Fatalf("process exited status %d (expected 2)", pexit.Status)
			}
		} else {
			assertNoError(exitErr, t, lastCmd)
			t.Fatalf("process did not exit after %s", lastCmd)
		}
	})
}
3506 3507

func TestIssue1145(t *testing.T) {
3508
	withTestProcess("sleep", t, func(p proc.Process, fixture protest.Fixture) {
3509
		setFileBreakpoint(p, t, fixture.Source, 18)
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
		assertNoError(proc.Continue(p), t, "Continue()")
		resumeChan := make(chan struct{}, 1)
		p.ResumeNotify(resumeChan)
		go func() {
			<-resumeChan
			time.Sleep(100 * time.Millisecond)
			p.RequestManualStop()
		}()

		assertNoError(proc.Next(p), t, "Next()")
		if p.Breakpoints().HasInternalBreakpoints() {
			t.Fatal("has internal breakpoints after manual stop request")
		}
	})
}
3525 3526 3527 3528

func TestDisassembleGlobalVars(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		mainfn := p.BinInfo().LookupFunc["main.main"]
D
Derek Parker 已提交
3529 3530
		regs, _ := p.CurrentThread().Registers(false)
		text, err := proc.Disassemble(p.CurrentThread(), regs, p.Breakpoints(), p.BinInfo(), mainfn.Entry, mainfn.End)
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
		assertNoError(err, t, "Disassemble")
		found := false
		for i := range text {
			if strings.Index(text[i].Text(proc.IntelFlavour, p.BinInfo()), "main.v") > 0 {
				found = true
				break
			}
		}
		if !found {
			t.Fatalf("could not find main.v reference in disassembly")
		}
	})
}
A
aarzilli 已提交
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561

func checkFrame(frame proc.Stackframe, fnname, file string, line int, inlined bool) error {
	if frame.Call.Fn == nil || frame.Call.Fn.Name != fnname {
		return fmt.Errorf("wrong function name: %s", fnname)
	}
	if frame.Call.File != file || frame.Call.Line != line {
		return fmt.Errorf("wrong file:line %s:%d", frame.Call.File, frame.Call.Line)
	}
	if frame.Inlined != inlined {
		if inlined {
			return fmt.Errorf("not inlined")
		} else {
			return fmt.Errorf("inlined")
		}
	}
	return nil
}

3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582
func TestAllPCsForFileLines(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining, func(p proc.Process, fixture protest.Fixture) {
		l2pcs := p.BinInfo().AllPCsForFileLines(fixture.Source, []int{7, 20})
		if len(l2pcs) != 2 {
			t.Fatalf("expected two map entries for %s:{%d,%d} (got %d: %v)", fixture.Source, 7, 20, len(l2pcs), l2pcs)
		}
		pcs := l2pcs[20]
		if len(pcs) < 1 {
			t.Fatalf("expected at least one location for %s:%d (got %d: %#x)", fixture.Source, 20, len(pcs), pcs)
		}
		pcs = l2pcs[7]
		if len(pcs) < 2 {
			t.Fatalf("expected at least two locations for %s:%d (got %d: %#x)", fixture.Source, 7, len(pcs), pcs)
		}
	})
}

A
aarzilli 已提交
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
func TestInlinedStacktraceAndVariables(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}

	firstCallCheck := &scopeCheck{
		line: 7,
		ok:   false,
		varChecks: []varCheck{
			varCheck{
				name:   "a",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 3,
			},
			varCheck{
				name:   "z",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 9,
			},
		},
	}

	secondCallCheck := &scopeCheck{
		line: 7,
		ok:   false,
		varChecks: []varCheck{
			varCheck{
				name:   "a",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 4,
			},
			varCheck{
				name:   "z",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 16,
			},
		},
	}

	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining, func(p proc.Process, fixture protest.Fixture) {
		pcs := p.BinInfo().AllPCsForFileLine(fixture.Source, 7)
		if len(pcs) < 2 {
3634
			t.Fatalf("expected at least two locations for %s:%d (got %d: %#x)", fixture.Source, 7, len(pcs), pcs)
A
aarzilli 已提交
3635 3636
		}
		for _, pc := range pcs {
3637
			t.Logf("setting breakpoint at %#x\n", pc)
A
aarzilli 已提交
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
			_, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
			assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%#x)", pc))
		}

		// first inlined call
		assertNoError(proc.Continue(p), t, "Continue")
		frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
		assertNoError(err, t, "ThreadStacktrace")
		t.Logf("Stacktrace:\n")
		for i := range frames {
3648
			t.Logf("\t%s at %s:%d (%#x)\n", frames[i].Call.Fn.Name, frames[i].Call.File, frames[i].Call.Line, frames[i].Current.PC)
A
aarzilli 已提交
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674
		}

		if err := checkFrame(frames[0], "main.inlineThis", fixture.Source, 7, true); err != nil {
			t.Fatalf("Wrong frame 0: %v", err)
		}
		if err := checkFrame(frames[1], "main.main", fixture.Source, 18, false); err != nil {
			t.Fatalf("Wrong frame 1: %v", err)
		}

		if avar, _ := constant.Int64Val(evalVariable(p, t, "a").Value); avar != 3 {
			t.Fatalf("value of 'a' variable is not 3 (%d)", avar)
		}
		if zvar, _ := constant.Int64Val(evalVariable(p, t, "z").Value); zvar != 9 {
			t.Fatalf("value of 'z' variable is not 9 (%d)", zvar)
		}

		if _, ok := firstCallCheck.checkLocalsAndArgs(p, t); !ok {
			t.Fatalf("exiting for past errors")
		}

		// second inlined call
		assertNoError(proc.Continue(p), t, "Continue")
		frames, err = proc.ThreadStacktrace(p.CurrentThread(), 20)
		assertNoError(err, t, "ThreadStacktrace (2)")
		t.Logf("Stacktrace 2:\n")
		for i := range frames {
3675
			t.Logf("\t%s at %s:%d (%#x)\n", frames[i].Call.Fn.Name, frames[i].Call.File, frames[i].Call.Line, frames[i].Current.PC)
A
aarzilli 已提交
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
		}

		if err := checkFrame(frames[0], "main.inlineThis", fixture.Source, 7, true); err != nil {
			t.Fatalf("Wrong frame 0: %v", err)
		}
		if err := checkFrame(frames[1], "main.main", fixture.Source, 19, false); err != nil {
			t.Fatalf("Wrong frame 1: %v", err)
		}

		if avar, _ := constant.Int64Val(evalVariable(p, t, "a").Value); avar != 4 {
			t.Fatalf("value of 'a' variable is not 3 (%d)", avar)
		}
		if zvar, _ := constant.Int64Val(evalVariable(p, t, "z").Value); zvar != 16 {
			t.Fatalf("value of 'z' variable is not 9 (%d)", zvar)
		}
		if bvar, err := evalVariableOrError(p, "b"); err == nil {
			t.Fatalf("expected error evaluating 'b', but it succeeded instead: %v", bvar)
		}

		if _, ok := secondCallCheck.checkLocalsAndArgs(p, t); !ok {
			t.Fatalf("exiting for past errors")
		}
	})
}

func TestInlineStep(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contStep, 6},
		{contStep, 7},
		{contStep, 18},
		{contStep, 19},
	})
}

func TestInlineNext(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contStep, 6},
		{contNext, 7},
		{contNext, 18},
		{contNext, 19},
	})
}

func TestInlineStepOver(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contNext, 19},
		{contNext, 20},
	})
}

func TestInlineStepOut(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contStep, 6},
		{contStepout, 18},
	})
}
3752

3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
func TestInlineFunctionList(t *testing.T) {
	// We should be able to list all functions, even inlined ones.
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining|protest.EnableOptimization, func(p proc.Process, fixture protest.Fixture) {
		var found bool
		for _, fn := range p.BinInfo().Functions {
			if strings.Contains(fn.Name, "inlineThis") {
				found = true
				break
			}
		}
		if !found {
			t.Fatal("inline function not returned")
		}
	})
}

func TestInlineBreakpoint(t *testing.T) {
	// We should be able to set a breakpoint on the call site of an inlined function.
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining|protest.EnableOptimization, func(p proc.Process, fixture protest.Fixture) {
		pc, fn, err := p.BinInfo().LineToPC(fixture.Source, 17)
		if pc == 0 {
			t.Fatal("unable to get PC for inlined function call")
		}
		expectedFn := "main.main"
		if fn.Name != expectedFn {
			t.Fatalf("incorrect function returned, expected %s, got %s", expectedFn, fn.Name)
		}
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
		if err != nil {
			t.Fatalf("unable to set breakpoint: %v", err)
		}
	})
}

3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
func TestIssue951(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
		t.Skip("scopes not implemented in <=go1.8")
	}

	withTestProcess("issue951", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope")
		args, err := scope.FunctionArguments(normalLoadConfig)
		assertNoError(err, t, "FunctionArguments")
		t.Logf("%#v", args[0])
		if args[0].Flags&proc.VariableShadowed == 0 {
			t.Error("argument is not shadowed")
		}
		vars, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables")
		shadowed, notShadowed := 0, 0
		for i := range vars {
			t.Logf("var %d: %#v\n", i, vars[i])
			if vars[i].Flags&proc.VariableShadowed != 0 {
				shadowed++
			} else {
				notShadowed++
			}
		}
		if shadowed != 1 || notShadowed != 1 {
			t.Errorf("Wrong number of shadowed/non-shadowed local variables: %d %d", shadowed, notShadowed)
		}
	})
}
3826

3827 3828 3829 3830 3831 3832 3833
func TestDWZCompression(t *testing.T) {
	// If dwz is not available in the system, skip this test
	if _, err := exec.LookPath("dwz"); err != nil {
		t.Skip("dwz not installed")
	}

	withTestProcessArgs("dwzcompression", t, ".", []string{}, protest.EnableDWZCompression, func(p proc.Process, fixture protest.Fixture) {
3834
		setFunctionBreakpoint(p, t, "C.fortytwo")
3835 3836 3837 3838 3839 3840 3841
		assertNoError(proc.Continue(p), t, "first Continue()")
		val := evalVariable(p, t, "stdin")
		if val.RealType == nil {
			t.Errorf("Can't find type for \"stdin\" global variable")
		}
	})
}
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866

func TestMapLoadConfigWithReslice(t *testing.T) {
	// Check that load configuration is respected for resliced maps.
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
		zolotovLoadCfg := proc.LoadConfig{FollowPointers: true, MaxStructFields: -1, MaxVariableRecurse: 3, MaxStringLen: 10, MaxArrayValues: 10}
		assertNoError(proc.Continue(p), t, "First Continue()")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope")
		m1, err := scope.EvalExpression("m1", zolotovLoadCfg)
		assertNoError(err, t, "EvalVariable")
		t.Logf("m1 returned children %d (%d)", len(m1.Children)/2, m1.Len)

		expr := fmt.Sprintf("(*(*%q)(%d))[10:]", m1.DwarfType.String(), m1.Addr)
		t.Logf("expr %q\n", expr)

		m1cont, err := scope.EvalExpression(expr, zolotovLoadCfg)
		assertNoError(err, t, "EvalVariable")

		t.Logf("m1cont returned children %d", len(m1cont.Children)/2)

		if len(m1cont.Children) != 20 {
			t.Fatalf("wrong number of children returned %d\n", len(m1cont.Children)/2)
		}
	})
}
3867 3868 3869 3870 3871 3872 3873

func TestStepOutReturn(t *testing.T) {
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		t.Skip("return variables aren't marked on 1.9 or earlier")
	}
	withTestProcess("stepoutret", t, func(p proc.Process, fixture protest.Fixture) {
3874
		setFunctionBreakpoint(p, t, "main.stepout")
3875 3876 3877 3878 3879 3880 3881
		assertNoError(proc.Continue(p), t, "Continue")
		assertNoError(proc.StepOut(p), t, "StepOut")
		ret := p.CurrentThread().Common().ReturnValues(normalLoadConfig)
		if len(ret) != 2 {
			t.Fatalf("wrong number of return values %v", ret)
		}

3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
		stridx := 0
		numidx := 1

		if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 12) {
			// in 1.11 and earlier the order of return values in DWARF is
			// unspecified, in 1.11 and later it follows the order of definition
			// specified by the user
			for i := range ret {
				if ret[i].Name == "str" {
					stridx = i
					numidx = 1 - i
					break
				}
			}
		}

		if ret[stridx].Name != "str" {
			t.Fatalf("(str) bad return value name %s", ret[stridx].Name)
3900
		}
3901 3902
		if ret[stridx].Kind != reflect.String {
			t.Fatalf("(str) bad return value kind %v", ret[stridx].Kind)
3903
		}
3904
		if s := constant.StringVal(ret[stridx].Value); s != "return 47" {
3905 3906 3907
			t.Fatalf("(str) bad return value %q", s)
		}

3908 3909
		if ret[numidx].Name != "num" {
			t.Fatalf("(num) bad return value name %s", ret[numidx].Name)
3910
		}
3911 3912
		if ret[numidx].Kind != reflect.Int {
			t.Fatalf("(num) bad return value kind %v", ret[numidx].Kind)
3913
		}
3914
		if n, _ := constant.Int64Val(ret[numidx].Value); n != 48 {
3915 3916 3917 3918
			t.Fatalf("(num) bad return value %d", n)
		}
	})
}
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936

func TestOptimizationCheck(t *testing.T) {
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
		fn := p.BinInfo().LookupFunc["main.main"]
		if fn.Optimized() {
			t.Fatalf("main.main is optimized")
		}
	})

	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 10) {
		withTestProcessArgs("continuetestprog", t, ".", []string{}, protest.EnableOptimization|protest.EnableInlining, func(p proc.Process, fixture protest.Fixture) {
			fn := p.BinInfo().LookupFunc["main.main"]
			if !fn.Optimized() {
				t.Fatalf("main.main is not optimized")
			}
		})
	}
}
3937 3938 3939 3940 3941

func TestIssue1264(t *testing.T) {
	// It should be possible to set a breakpoint condition that consists only
	// of evaluating a single boolean variable.
	withTestProcess("issue1264", t, func(p proc.Process, fixture protest.Fixture) {
3942
		bp := setFileBreakpoint(p, t, fixture.Source, 8)
3943 3944 3945 3946 3947
		bp.Cond = &ast.Ident{Name: "equalsTwo"}
		assertNoError(proc.Continue(p), t, "Continue()")
		assertLineNumber(p, t, 8, "after continue")
	})
}
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006

func TestReadDefer(t *testing.T) {
	withTestProcess("deferstack", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		frames, err := p.SelectedGoroutine().Stacktrace(10, true)
		assertNoError(err, t, "Stacktrace")

		logStacktrace(t, p.BinInfo(), frames)

		examples := []struct {
			frameIdx     int
			topmostDefer string
			defers       []string
		}{
			// main.call3 (defers nothing, topmost defer main.f2)
			{0, "main.f2", []string{}},

			// main.call2 (defers main.f2, main.f3, topmost defer main.f2)
			{1, "main.f2", []string{"main.f2", "main.f3"}},

			// main.call1 (defers main.f1, main.f2, topmost defer main.f1)
			{2, "main.f1", []string{"main.f1", "main.f2"}},

			// main.main (defers nothing)
			{3, "", []string{}}}

		defercheck := func(d *proc.Defer, deferName, tgt string, frameIdx int) {
			if d == nil {
				t.Fatalf("expected %q as %s of frame %d, got nothing", tgt, deferName, frameIdx)
			}
			if d.Unreadable != nil {
				t.Fatalf("expected %q as %s of frame %d, got unreadable defer: %v", tgt, deferName, frameIdx, d.Unreadable)
			}
			_, _, dfn := p.BinInfo().PCToLine(d.DeferredPC)
			if dfn == nil {
				t.Fatalf("expected %q as %s of frame %d, got %#x", tgt, deferName, frameIdx, d.DeferredPC)
			}
			if dfn.Name != tgt {
				t.Fatalf("expected %q as %s of frame %d, got %q", tgt, deferName, frameIdx, dfn.Name)
			}
		}

		for _, example := range examples {
			frame := &frames[example.frameIdx]

			if example.topmostDefer != "" {
				defercheck(frame.TopmostDefer, "topmost defer", example.topmostDefer, example.frameIdx)
			}

			if len(example.defers) != len(frames[example.frameIdx].Defers) {
				t.Fatalf("expected %d defers for %d, got %v", len(example.defers), example.frameIdx, frame.Defers)
			}

			for deferIdx := range example.defers {
				defercheck(frame.Defers[deferIdx], fmt.Sprintf("defer %d", deferIdx), example.defers[deferIdx], example.frameIdx)
			}
		}
	})
}
A
aarzilli 已提交
4007 4008 4009 4010 4011 4012

func TestNextUnknownInstr(t *testing.T) {
	if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 10) {
		t.Skip("versions of Go before 1.10 can't assemble the instruction VPUNPCKLWD")
	}
	withTestProcess("nodisasm/", t, func(p proc.Process, fixture protest.Fixture) {
4013
		setFunctionBreakpoint(p, t, "main.asmFunc")
A
aarzilli 已提交
4014 4015 4016 4017
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
	})
}
4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060

func TestReadDeferArgs(t *testing.T) {
	var tests = []struct {
		frame, deferCall int
		a, b             int64
	}{
		{1, 1, 42, 61},
		{2, 2, 1, -1},
	}

	withTestProcess("deferstack", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")

		for _, test := range tests {
			scope, err := proc.ConvertEvalScope(p, -1, test.frame, test.deferCall)
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope(-1, %d, %d)", test.frame, test.deferCall))

			if scope.Fn.Name != "main.f2" {
				t.Fatalf("expected function \"main.f2\" got %q", scope.Fn.Name)
			}

			avar, err := scope.EvalVariable("a", normalLoadConfig)
			if err != nil {
				t.Fatal(err)
			}
			bvar, err := scope.EvalVariable("b", normalLoadConfig)
			if err != nil {
				t.Fatal(err)
			}

			a, _ := constant.Int64Val(avar.Value)
			b, _ := constant.Int64Val(bvar.Value)

			if a != test.a {
				t.Errorf("value of argument 'a' at frame %d, deferred call %d: %d (expected %d)", test.frame, test.deferCall, a, test.a)
			}

			if b != test.b {
				t.Errorf("value of argument 'b' at frame %d, deferred call %d: %d (expected %d)", test.frame, test.deferCall, b, test.b)
			}
		}
	})
}
4061 4062 4063 4064 4065

func TestIssue1374(t *testing.T) {
	// Continue did not work when stopped at a breakpoint immediately after calling CallFunction.
	protest.MustSupportFunctionCalls(t, testBackend)
	withTestProcess("issue1374", t, func(p proc.Process, fixture protest.Fixture) {
4066
		setFileBreakpoint(p, t, fixture.Source, 7)
4067 4068
		assertNoError(proc.Continue(p), t, "First Continue")
		assertLineNumber(p, t, 7, "Did not continue to correct location (first continue),")
4069
		assertNoError(proc.EvalExpressionWithCalls(p, p.SelectedGoroutine(), "getNum()", normalLoadConfig, true), t, "Call")
4070 4071 4072 4073 4074 4075 4076 4077
		err := proc.Continue(p)
		if _, isexited := err.(proc.ErrProcessExited); !isexited {
			regs, _ := p.CurrentThread().Registers(false)
			f, l, _ := p.BinInfo().PCToLine(regs.PC())
			t.Fatalf("expected process exited error got %v at %s:%d", err, f, l)
		}
	})
}
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095

func TestIssue1432(t *testing.T) {
	// Check that taking the address of a struct, casting it into a pointer to
	// the struct's type and then accessing a member field will still:
	// - perform auto-dereferencing on struct member access
	// - yield a Variable that's ultimately assignable (i.e. has an address)
	withTestProcess("issue1432", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		svar := evalVariable(p, t, "s")
		t.Logf("%#x", svar.Addr)

		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope()")

		err = scope.SetVariable(fmt.Sprintf("(*\"main.s\")(%#x).i", svar.Addr), "10")
		assertNoError(err, t, "SetVariable")
	})
}
A
aarzilli 已提交
4096 4097 4098

func TestGoroutinesInfoLimit(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
4099
		setFileBreakpoint(p, t, fixture.Source, 37)
A
aarzilli 已提交
4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124
		assertNoError(proc.Continue(p), t, "Continue()")

		gcount := 0
		nextg := 0
		const goroutinesInfoLimit = 10
		for nextg >= 0 {
			oldnextg := nextg
			var gs []*proc.G
			var err error
			gs, nextg, err = proc.GoroutinesInfo(p, nextg, goroutinesInfoLimit)
			assertNoError(err, t, fmt.Sprintf("GoroutinesInfo(%d, %d)", oldnextg, goroutinesInfoLimit))
			gcount += len(gs)
			t.Logf("got %d goroutines\n", len(gs))
		}

		t.Logf("number of goroutines: %d\n", gcount)

		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
		assertNoError(err, t, "GoroutinesInfo(0, 0)")
		t.Logf("number of goroutines (full scan): %d\n", gcount)
		if len(gs) != gcount {
			t.Fatalf("mismatch in the number of goroutines %d %d\n", gcount, len(gs))
		}
	})
}
4125 4126 4127

func TestIssue1469(t *testing.T) {
	withTestProcess("issue1469", t, func(p proc.Process, fixture protest.Fixture) {
4128
		setFileBreakpoint(p, t, fixture.Source, 13)
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
		assertNoError(proc.Continue(p), t, "Continue()")

		gid2thread := make(map[int][]proc.Thread)
		for _, thread := range p.ThreadList() {
			g, _ := proc.GetG(thread)
			if g == nil {
				continue
			}
			gid2thread[g.ID] = append(gid2thread[g.ID], thread)
		}

		for gid := range gid2thread {
			if len(gid2thread[gid]) > 1 {
				t.Logf("too many threads running goroutine %d", gid)
				for _, thread := range gid2thread[gid] {
					t.Logf("\tThread %d", thread.ThreadID())
					frames, err := proc.ThreadStacktrace(thread, 20)
					if err != nil {
						t.Logf("\t\tcould not get stacktrace %v", err)
					}
					for _, frame := range frames {
						t.Logf("\t\t%#x at %s:%d (systemstack: %v)", frame.Call.PC, frame.Call.File, frame.Call.Line, frame.SystemStack)
					}
				}
			}
		}
	})
}
4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174

func TestDeadlockBreakpoint(t *testing.T) {
	if buildMode == "pie" {
		t.Skip("See https://github.com/golang/go/issues/29322")
	}
	deadlockBp := proc.FatalThrow
	if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		deadlockBp = proc.UnrecoveredPanic
	}
	withTestProcess("testdeadlock", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")

		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != deadlockBp {
			t.Fatalf("did not stop at deadlock breakpoint %v", bp)
		}
	})
}
4175 4176

func TestListImages(t *testing.T) {
A
Alessandro Arzilli 已提交
4177
	pluginFixtures := protest.WithPlugins(t, protest.AllNonOptimized, "plugin1/", "plugin2/")
4178

A
Alessandro Arzilli 已提交
4179
	withTestProcessArgs("plugintest", t, ".", []string{pluginFixtures[0].Path, pluginFixtures[1].Path}, protest.AllNonOptimized, func(p proc.Process, fixture protest.Fixture) {
4180
		assertNoError(proc.Continue(p), t, "first continue")
4181
		f, l := currentLineNumber(p, t)
4182
		plugin1Found := false
4183
		t.Logf("Libraries before %s:%d:", f, l)
4184
		for _, image := range p.BinInfo().Images {
4185
			t.Logf("\t%#x %q err:%v", image.StaticBase, image.Path, image.LoadError())
4186 4187 4188 4189 4190 4191 4192 4193
			if image.Path == pluginFixtures[0].Path {
				plugin1Found = true
			}
		}
		if !plugin1Found {
			t.Fatalf("Could not find plugin1")
		}
		assertNoError(proc.Continue(p), t, "second continue")
4194
		f, l = currentLineNumber(p, t)
4195
		plugin1Found, plugin2Found := false, false
4196
		t.Logf("Libraries after %s:%d:", f, l)
4197
		for _, image := range p.BinInfo().Images {
4198
			t.Logf("\t%#x %q err:%v", image.StaticBase, image.Path, image.LoadError())
4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
			switch image.Path {
			case pluginFixtures[0].Path:
				plugin1Found = true
			case pluginFixtures[1].Path:
				plugin2Found = true
			}
		}
		if !plugin1Found {
			t.Fatalf("Could not find plugin1")
		}
		if !plugin2Found {
			t.Fatalf("Could not find plugin2")
		}
	})
}
4214 4215 4216 4217 4218 4219 4220 4221 4222

func TestAncestors(t *testing.T) {
	if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		t.Skip("not supported on Go <= 1.10")
	}
	savedGodebug := os.Getenv("GODEBUG")
	os.Setenv("GODEBUG", "tracebackancestors=100")
	defer os.Setenv("GODEBUG", savedGodebug)
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
4223
		setFunctionBreakpoint(p, t, "main.testgoroutine")
4224
		assertNoError(proc.Continue(p), t, "Continue()")
4225
		as, err := proc.Ancestors(p, p.SelectedGoroutine(), 1000)
4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
		assertNoError(err, t, "Ancestors")
		t.Logf("ancestors: %#v\n", as)
		if len(as) != 1 {
			t.Fatalf("expected only one ancestor got %d", len(as))
		}
		mainFound := false
		for i, a := range as {
			astack, err := a.Stack(100)
			assertNoError(err, t, fmt.Sprintf("Ancestor %d stack", i))
			t.Logf("ancestor %d\n", i)
			logStacktrace(t, p.BinInfo(), astack)
			for _, frame := range astack {
				if frame.Current.Fn != nil && frame.Current.Fn.Name == "main.main" {
					mainFound = true
				}
			}
		}
		if !mainFound {
			t.Fatal("could not find main.main function in ancestors")
		}
	})
}
4248

4249 4250
func testCallConcurrentCheckReturns(p proc.Process, t *testing.T, gid1, gid2 int) int {
	found := 0
4251 4252
	for _, thread := range p.ThreadList() {
		g, _ := proc.GetG(thread)
4253
		if g == nil || (g.ID != gid1 && g.ID != gid2) {
4254 4255 4256
			continue
		}
		retvals := thread.Common().ReturnValues(normalLoadConfig)
4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
		if len(retvals) == 0 {
			continue
		}
		n, _ := constant.Int64Val(retvals[0].Value)
		t.Logf("injection on goroutine %d (thread %d) returned %v\n", g.ID, thread.ThreadID(), n)
		switch g.ID {
		case gid1:
			if n != 11 {
				t.Errorf("wrong return value for goroutine %d", g.ID)
			}
			found++
		case gid2:
			if n != 12 {
				t.Errorf("wrong return value for goroutine %d", g.ID)
			}
			found++
4273 4274
		}
	}
4275
	return found
4276 4277 4278
}

func TestCallConcurrent(t *testing.T) {
4279 4280 4281
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
4282 4283
	protest.MustSupportFunctionCalls(t, testBackend)
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
4284
		bp := setFileBreakpoint(p, t, fixture.Source, 24)
4285
		assertNoError(proc.Continue(p), t, "Continue()")
4286 4287
		//_, err := p.ClearBreakpoint(bp.Addr)
		//assertNoError(err, t, "ClearBreakpoint() returned an error")
4288 4289 4290

		gid1 := p.SelectedGoroutine().ID
		t.Logf("starting injection in %d / %d", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
4291
		assertNoError(proc.EvalExpressionWithCalls(p, p.SelectedGoroutine(), "Foo(10, 1)", normalLoadConfig, false), t, "EvalExpressionWithCalls()")
4292

4293
		returned := testCallConcurrentCheckReturns(p, t, gid1, -1)
4294 4295

		curthread := p.CurrentThread()
4296 4297
		if curbp := curthread.Breakpoint(); curbp.Breakpoint == nil || curbp.ID != bp.ID || returned > 0 {
			t.Logf("skipping test, the call injection terminated before we hit a breakpoint in a different thread")
4298 4299 4300
			return
		}

4301 4302 4303 4304 4305 4306 4307
		_, err := p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint() returned an error")

		gid2 := p.SelectedGoroutine().ID
		t.Logf("starting second injection in %d / %d", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
		assertNoError(proc.EvalExpressionWithCalls(p, p.SelectedGoroutine(), "Foo(10, 2)", normalLoadConfig, false), t, "EvalExpressioniWithCalls")

4308
		for {
4309 4310
			returned += testCallConcurrentCheckReturns(p, t, gid1, gid2)
			if returned >= 2 {
4311 4312
				break
			}
4313
			t.Logf("Continuing... %d", returned)
4314 4315 4316 4317 4318 4319
			assertNoError(proc.Continue(p), t, "Continue()")
		}

		proc.Continue(p)
	})
}
4320 4321

func TestPluginStepping(t *testing.T) {
A
Alessandro Arzilli 已提交
4322
	pluginFixtures := protest.WithPlugins(t, protest.AllNonOptimized, "plugin1/", "plugin2/")
4323

A
Alessandro Arzilli 已提交
4324
	testseq2Args(".", []string{pluginFixtures[0].Path, pluginFixtures[1].Path}, protest.AllNonOptimized, t, "plugintest2", "", []seqTest{
4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336
		{contContinue, 41},
		{contStep, "plugin1.go:9"},
		{contStep, "plugin1.go:10"},
		{contStep, "plugin1.go:11"},
		{contNext, "plugin1.go:12"},
		{contNext, "plugintest2.go:41"},
		{contNext, "plugintest2.go:42"},
		{contStep, "plugin2.go:22"},
		{contNext, "plugin2.go:23"},
		{contNext, "plugin2.go:26"},
		{contNext, "plugintest2.go:42"}})
}
4337 4338 4339 4340 4341 4342 4343 4344

func TestIssue1601(t *testing.T) {
	//Tests that recursive types involving C qualifiers and typedefs are parsed correctly
	withTestProcess("issue1601", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		evalVariable(p, t, "C.globalq")
	})
}
4345 4346 4347 4348 4349

func TestIssue1615(t *testing.T) {
	// A breakpoint condition that tests for string equality with a constant string shouldn't fail with 'string too long for comparison' error

	withTestProcess("issue1615", t, func(p proc.Process, fixture protest.Fixture) {
4350
		bp := setFileBreakpoint(p, t, fixture.Source, 19)
4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "s"},
			Y:  &ast.BasicLit{Kind: token.STRING, Value: `"projects/my-gcp-project-id-string/locations/us-central1/queues/my-task-queue-name"`},
		}

		assertNoError(proc.Continue(p), t, "Continue")
		assertLineNumber(p, t, 19, "")
	})
}
4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375

func TestCgoStacktrace2(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("fixture crashes go runtime on windows")
	}
	// If a panic happens during cgo execution the stacktrace should show the C
	// function that caused the problem.
	withTestProcess("cgosigsegvstack", t, func(p proc.Process, fixture protest.Fixture) {
		proc.Continue(p)
		frames, err := proc.ThreadStacktrace(p.CurrentThread(), 100)
		assertNoError(err, t, "Stacktrace()")
		logStacktrace(t, p.BinInfo(), frames)
		stacktraceCheck(t, []string{"C.sigsegv", "C.testfn", "main.main"}, frames)
	})
}
4376 4377 4378

func TestIssue1656(t *testing.T) {
	withTestProcess("issue1656/", t, func(p proc.Process, fixture protest.Fixture) {
4379
		setFileBreakpoint(p, t, filepath.ToSlash(filepath.Join(fixture.BuildDir, "main.s")), 5)
4380 4381 4382 4383 4384 4385 4386 4387 4388
		assertNoError(proc.Continue(p), t, "Continue()")
		t.Logf("step1\n")
		assertNoError(proc.Step(p), t, "Step()")
		assertLineNumber(p, t, 8, "wrong line number after first step")
		t.Logf("step2\n")
		assertNoError(proc.Step(p), t, "Step()")
		assertLineNumber(p, t, 9, "wrong line number after second step")
	})
}