proc_test.go 130.6 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
	"strings"
D
Derek Parker 已提交
19
	"testing"
D
Derek Parker 已提交
20
	"time"
D
Dan Mace 已提交
21

22 23 24 25 26 27 28
	"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 已提交
29
)
30

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

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

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

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

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

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

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

	fn(p, fixture)
}

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

	return regs
}

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

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

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

123
	return regs.PC()
124 125
}

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

132 133 134 135 136 137 138 139 140
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
}

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

158
func TestExitAfterContinue(t *testing.T) {
159
	protest.AllowRecording(t)
160
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
161 162
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "setFunctionBreakpoint()")
163 164
		assertNoError(proc.Continue(p), t, "First Continue()")
		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
func setFunctionBreakpoint(p proc.Process, fname string) (*proc.Breakpoint, error) {
179
	addr, err := proc.FindFunctionLocation(p, fname, true, 0)
180 181 182
	if err != nil {
		return nil, err
	}
183
	return p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
184 185
}

186
func setFileBreakpoint(p proc.Process, t *testing.T, fixture protest.Fixture, lineno int) *proc.Breakpoint {
187
	addr, err := proc.FindFileLocation(p, fixture.Source, lineno)
A
aarzilli 已提交
188 189 190
	if err != nil {
		t.Fatalf("FindFileLocation: %v", err)
	}
191
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
A
aarzilli 已提交
192 193 194 195 196 197
	if err != nil {
		t.Fatalf("SetBreakpoint: %v", err)
	}
	return bp
}

D
Derek Parker 已提交
198
func TestHalt(t *testing.T) {
199
	stopChan := make(chan interface{}, 1)
200
	withTestProcess("loopprog", t, func(p proc.Process, fixture protest.Fixture) {
201
		_, err := setFunctionBreakpoint(p, "main.loop")
202
		assertNoError(err, t, "SetBreakpoint")
203 204 205
		assertNoError(proc.Continue(p), t, "Continue")
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
206 207
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
208 209
			}
		}
210
		resumeChan := make(chan struct{}, 1)
D
Derek Parker 已提交
211
		go func() {
A
aarzilli 已提交
212 213
			<-resumeChan
			time.Sleep(100 * time.Millisecond)
214
			stopChan <- p.RequestManualStop()
D
Derek Parker 已提交
215
		}()
A
aarzilli 已提交
216
		p.ResumeNotify(resumeChan)
217
		assertNoError(proc.Continue(p), t, "Continue")
218 219 220 221 222 223
		retVal := <-stopChan

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

D
Derek Parker 已提交
224 225 226
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
227 228 229 230 231 232
		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")
					}
233 234 235
				}
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
D
Derek Parker 已提交
236 237 238 239 240
			}
		}
	})
}

241
func TestStep(t *testing.T) {
242
	protest.AllowRecording(t)
243
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
244
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", false, 0)
245
		assertNoError(err, t, "FindFunctionLocation")
246

247
		_, err = p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
248
		assertNoError(err, t, "SetBreakpoint()")
249
		assertNoError(proc.Continue(p), t, "Continue()")
250

251
		regs := getRegisters(p, t)
252
		rip := regs.PC()
253

254
		err = p.CurrentThread().StepInstruction()
D
Derek Parker 已提交
255
		assertNoError(err, t, "Step()")
256

257
		regs = getRegisters(p, t)
258 259 260 261 262
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
263

D
Derek Parker 已提交
264
func TestBreakpoint(t *testing.T) {
265
	protest.AllowRecording(t)
266
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
267
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", false, 0)
268
		assertNoError(err, t, "FindFunctionLocation")
269

270
		bp, err := p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
271
		assertNoError(err, t, "SetBreakpoint()")
272
		assertNoError(proc.Continue(p), t, "Continue()")
273

274 275 276
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
277

278 279 280 281
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
282
		if pc-1 != bp.Addr && pc != bp.Addr {
283
			f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
284
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
285 286
		}
	})
287
}
288

J
Josh Soref 已提交
289
func TestBreakpointInSeparateGoRoutine(t *testing.T) {
290
	protest.AllowRecording(t)
291
	withTestProcess("testthreads", t, func(p proc.Process, fixture protest.Fixture) {
292
		fnentry, err := proc.FindFunctionLocation(p, "main.anotherthread", false, 0)
293
		assertNoError(err, t, "FindFunctionLocation")
294

295
		_, err = p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
296
		assertNoError(err, t, "SetBreakpoint")
297

298
		assertNoError(proc.Continue(p), t, "Continue")
299

300 301 302
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
303

304
		f, l, _ := p.BinInfo().PCToLine(pc)
305 306 307 308 309 310
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
311
func TestBreakpointWithNonExistantFunction(t *testing.T) {
312
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
313
		_, err := p.SetBreakpoint(0, proc.UserBreakpoint, nil)
314 315 316 317
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
318
}
319

320
func TestClearBreakpointBreakpoint(t *testing.T) {
321
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
322
		fnentry, err := proc.FindFunctionLocation(p, "main.sleepytime", false, 0)
323
		assertNoError(err, t, "FindFunctionLocation")
324
		bp, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
325
		assertNoError(err, t, "SetBreakpoint()")
326

327
		bp, err = p.ClearBreakpoint(fnentry)
328
		assertNoError(err, t, "ClearBreakpoint()")
329

330 331
		data, err := dataAtAddr(p.CurrentThread(), bp.Addr)
		assertNoError(err, t, "dataAtAddr")
332

333
		int3 := []byte{0xcc}
334 335 336 337
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

338
		if countBreakpoints(p) != 0 {
339 340 341
			t.Fatal("Breakpoint not removed internally")
		}
	})
342
}
343

344 345 346
type nextTest struct {
	begin, end int
}
347

348
func countBreakpoints(p proc.Process) int {
349
	bpcount := 0
A
aarzilli 已提交
350
	for _, bp := range p.Breakpoints().M {
351 352 353 354 355 356 357
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

A
aarzilli 已提交
358 359 360
type contFunc int

const (
361 362
	contContinue contFunc = iota
	contNext
A
aarzilli 已提交
363
	contStep
364
	contStepout
A
aarzilli 已提交
365 366
)

367 368 369 370 371
type seqTest struct {
	cf  contFunc
	pos int
}

A
aarzilli 已提交
372
func testseq(program string, contFunc contFunc, testcases []nextTest, initialLocation string, t *testing.T) {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
	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) {
393
	protest.AllowRecording(t)
394
	withTestProcessArgs(program, t, wd, args, buildFlags, func(p proc.Process, fixture protest.Fixture) {
395
		var bp *proc.Breakpoint
A
aarzilli 已提交
396 397 398
		var err error
		if initialLocation != "" {
			bp, err = setFunctionBreakpoint(p, initialLocation)
399
		} else if testcases[0].cf == contContinue {
A
aarzilli 已提交
400
			var pc uint64
401
			pc, err = proc.FindFileLocation(p, fixture.Source, testcases[0].pos)
A
aarzilli 已提交
402
			assertNoError(err, t, "FindFileLocation()")
403
			bp, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
404 405 406 407 408
		} else {
			panic("testseq2 can not set initial breakpoint")
		}
		if traceTestseq2 {
			t.Logf("initial breakpoint %v", bp)
A
aarzilli 已提交
409
		}
410
		assertNoError(err, t, "SetBreakpoint()")
411 412
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
413

D
Derek Parker 已提交
414
		f, ln := currentLineNumber(p, t)
415 416
		for i, tc := range testcases {
			switch tc.cf {
A
aarzilli 已提交
417
			case contNext:
418 419 420
				if traceTestseq2 {
					t.Log("next")
				}
421
				assertNoError(proc.Next(p), t, "Next() returned an error")
A
aarzilli 已提交
422
			case contStep:
423 424 425
				if traceTestseq2 {
					t.Log("step")
				}
426
				assertNoError(proc.Step(p), t, "Step() returned an error")
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
			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 已提交
444
			}
445

D
Derek Parker 已提交
446
			f, ln = currentLineNumber(p, t)
447
			regs, _ = p.CurrentThread().Registers(false)
448 449 450 451 452 453 454
			pc := regs.PC()

			if traceTestseq2 {
				t.Logf("at %#x %s:%d", pc, f, ln)
			}
			if ln != tc.pos {
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d (%#x) (testcase %d)", tc.pos, filepath.Base(f), ln, pc, i)
455 456
			}
		}
457

458
		if countBreakpoints(p) != 0 {
A
aarzilli 已提交
459
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints().M))
460
		}
461 462
	})
}
463

464
func TestNextGeneral(t *testing.T) {
465 466
	var testcases []nextTest

467
	ver, _ := goversion.Parse(runtime.Version())
468

469
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
		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},
		}
506
	}
507

A
aarzilli 已提交
508
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
509 510
}

511 512
func TestNextConcurrent(t *testing.T) {
	testcases := []nextTest{
513
		{8, 9},
514 515 516
		{9, 10},
		{10, 11},
	}
517
	protest.AllowRecording(t)
518
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
519
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
520
		assertNoError(err, t, "SetBreakpoint")
521
		assertNoError(proc.Continue(p), t, "Continue")
522
		f, ln := currentLineNumber(p, t)
523
		initV := evalVariable(p, t, "n")
524
		initVval, _ := constant.Int64Val(initV.Value)
525 526
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")
527
		for _, tc := range testcases {
528
			g, err := proc.GetG(p.CurrentThread())
529
			assertNoError(err, t, "GetG()")
530 531
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
532
			}
533 534 535
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
536
			assertNoError(proc.Next(p), t, "Next() returned an error")
537 538
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to the expected location")
			v := evalVariable(p, t, "n")
539 540
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
541 542 543 544 545 546
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

547 548 549
func TestNextConcurrentVariant2(t *testing.T) {
	// Just like TestNextConcurrent but instead of removing the initial breakpoint we check that when it happens is for other goroutines
	testcases := []nextTest{
550
		{8, 9},
551 552 553
		{9, 10},
		{10, 11},
	}
554
	protest.AllowRecording(t)
555
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
556 557
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint")
558
		assertNoError(proc.Continue(p), t, "Continue")
559
		f, ln := currentLineNumber(p, t)
560
		initV := evalVariable(p, t, "n")
561 562
		initVval, _ := constant.Int64Val(initV.Value)
		for _, tc := range testcases {
563
			t.Logf("test case %v", tc)
564
			g, err := proc.GetG(p.CurrentThread())
565
			assertNoError(err, t, "GetG()")
566 567
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
568 569 570 571
			}
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
572
			assertNoError(proc.Next(p), t, "Next() returned an error")
573 574
			var vval int64
			for {
575
				v := evalVariable(p, t, "n")
576 577 578
				for _, thread := range p.ThreadList() {
					proc.GetG(thread)
				}
579
				vval, _ = constant.Int64Val(v.Value)
580
				if bpstate := p.CurrentThread().Breakpoint(); bpstate.Breakpoint == nil {
581 582 583 584 585 586 587 588
					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")
					}
589
					assertNoError(proc.Continue(p), t, "Continue 2")
590 591
				}
			}
592
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to the expected location")
593 594 595 596
		}
	})
}

597 598
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
599
		{13, 14},
D
Derek Parker 已提交
600 601
		{14, 15},
		{15, 35},
602
	}
603
	protest.AllowRecording(t)
A
aarzilli 已提交
604
	testseq("testnextprog", contNext, testcases, "main.helloworld", t)
605 606 607
}

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

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

612
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
613 614 615 616 617 618 619 620 621 622 623
		testcases = []nextTest{
			{5, 6},
			{6, 9},
			{9, 10},
		}
	} else {
		testcases = []nextTest{
			{5, 8},
			{8, 9},
			{9, 10},
		}
624
	}
625
	protest.AllowRecording(t)
A
aarzilli 已提交
626
	testseq("testnextdefer", contNext, testcases, "main.main", t)
627 628
}

D
Derek Parker 已提交
629 630 631 632 633
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
634
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
635 636 637
		go func() {
			// Wait for program to start listening.
			for {
L
Luke Hoban 已提交
638
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
639 640 641 642 643 644
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
645
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
646
		}()
647
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
648 649 650 651 652 653 654 655
			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)
			}

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

658
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to correct next location")
D
Derek Parker 已提交
659 660 661 662
		}
	})
}

D
Derek Parker 已提交
663
func TestRuntimeBreakpoint(t *testing.T) {
664
	withTestProcess("testruntimebreakpoint", t, func(p proc.Process, fixture protest.Fixture) {
665
		err := proc.Continue(p)
D
Derek Parker 已提交
666 667 668
		if err != nil {
			t.Fatal(err)
		}
669 670 671
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
672
		f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
673
		if l != 10 {
674
			t.Fatalf("did not respect breakpoint %s:%d", f, l)
D
Derek Parker 已提交
675 676 677 678
		}
	})
}

679
func returnAddress(thread proc.Thread) (uint64, error) {
680
	locations, err := proc.ThreadStacktrace(thread, 2)
681 682 683 684
	if err != nil {
		return 0, err
	}
	if len(locations) < 2 {
A
aarzilli 已提交
685
		return 0, fmt.Errorf("no return address for function: %s", locations[0].Current.Fn.BaseName())
686 687 688 689
	}
	return locations[1].Current.PC, nil
}

690
func TestFindReturnAddress(t *testing.T) {
691
	protest.AllowRecording(t)
692
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
693
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 24)
694 695 696
		if err != nil {
			t.Fatal(err)
		}
697
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
698 699 700
		if err != nil {
			t.Fatal(err)
		}
701
		err = proc.Continue(p)
702 703 704
		if err != nil {
			t.Fatal(err)
		}
705
		addr, err := returnAddress(p.CurrentThread())
706 707 708
		if err != nil {
			t.Fatal(err)
		}
709
		_, l, _ := p.BinInfo().PCToLine(addr)
710 711
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
712
		}
713 714
	})
}
715

716
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
717
	protest.AllowRecording(t)
718
	withTestProcess("testreturnaddress", t, func(p proc.Process, fixture protest.Fixture) {
719
		fnName := "runtime.rt0_go"
720
		fnentry, err := proc.FindFunctionLocation(p, fnName, false, 0)
721
		assertNoError(err, t, "FindFunctionLocation")
722
		if _, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil); err != nil {
723 724
			t.Fatal(err)
		}
725
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
726 727
			t.Fatal(err)
		}
728
		if _, err := returnAddress(p.CurrentThread()); err == nil {
729
			t.Fatal("expected error to be returned")
730 731 732
		}
	})
}
D
Derek Parker 已提交
733 734

func TestSwitchThread(t *testing.T) {
735
	protest.AllowRecording(t)
736
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
737 738 739 740 741
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
742
		pc, err := proc.FindFunctionLocation(p, "main.main", true, 0)
D
Derek Parker 已提交
743 744 745
		if err != nil {
			t.Fatal(err)
		}
746
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
D
Derek Parker 已提交
747 748 749
		if err != nil {
			t.Fatal(err)
		}
750
		err = proc.Continue(p)
D
Derek Parker 已提交
751 752 753 754
		if err != nil {
			t.Fatal(err)
		}
		var nt int
755 756 757 758
		ct := p.CurrentThread().ThreadID()
		for _, thread := range p.ThreadList() {
			if thread.ThreadID() != ct {
				nt = thread.ThreadID()
D
Derek Parker 已提交
759 760 761 762 763 764 765 766 767 768 769
				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)
		}
770
		if p.CurrentThread().ThreadID() != nt {
D
Derek Parker 已提交
771 772 773 774
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
775

776 777 778 779 780 781
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 已提交
782 783 784
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
785

786
	protest.AllowRecording(t)
787
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
788
		pc, err := proc.FindFunctionLocation(p, "main.main", true, 0)
789 790 791
		if err != nil {
			t.Fatal(err)
		}
792
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
793 794 795
		if err != nil {
			t.Fatal(err)
		}
796
		err = proc.Continue(p)
797 798 799
		if err != nil {
			t.Fatal(err)
		}
800
		err = proc.Next(p)
801 802 803 804 805 806
		if err != nil {
			t.Fatal(err)
		}
	})
}

A
aarzilli 已提交
807 808 809 810 811
type loc struct {
	line int
	fn   string
}

812
func (l1 *loc) match(l2 proc.Stackframe) bool {
A
aarzilli 已提交
813
	if l1.line >= 0 {
814
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
815 816 817
			return false
		}
	}
818
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
819 820 821 822
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
823 824
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
825
	}
826
	protest.AllowRecording(t)
827
	withTestProcess("stacktraceprog", t, func(p proc.Process, fixture protest.Fixture) {
828
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
829 830 831
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
832 833
			assertNoError(proc.Continue(p), t, "Continue()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
A
aarzilli 已提交
834 835 836 837 838 839
			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)
			}

840 841 842 843
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
844

A
aarzilli 已提交
845 846 847 848 849 850 851
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

852
		p.ClearBreakpoint(bp.Addr)
853
		proc.Continue(p)
A
aarzilli 已提交
854 855 856
	})
}

857
func TestStacktrace2(t *testing.T) {
858
	withTestProcess("retstack", t, func(p proc.Process, fixture protest.Fixture) {
859
		assertNoError(proc.Continue(p), t, "Continue()")
860

861
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
862
		assertNoError(err, t, "Stacktrace()")
863
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
864 865 866
			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 已提交
867
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
868 869
		}

870 871
		assertNoError(proc.Continue(p), t, "Continue()")
		locations, err = proc.ThreadStacktrace(p.CurrentThread(), 40)
872
		assertNoError(err, t, "Stacktrace()")
873
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
874 875 876
			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 已提交
877
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
878 879 880 881 882
		}
	})

}

883
func stackMatch(stack []loc, locations []proc.Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
884 885 886
	if len(stack) > len(locations) {
		return false
	}
887 888 889 890 891 892 893 894 895 896 897
	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 已提交
898 899
			return false
		}
900
		i++
A
aarzilli 已提交
901
	}
902
	return i >= len(stack)
A
aarzilli 已提交
903 904 905
}

func TestStacktraceGoroutine(t *testing.T) {
906
	mainStack := []loc{{14, "main.stacktraceme"}, {29, "main.main"}}
907 908 909
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		mainStack[0].line = 15
	}
910 911 912 913 914
	agoroutineStacks := [][]loc{
		{{8, "main.agoroutine"}},
		{{9, "main.agoroutine"}},
		{{10, "main.agoroutine"}},
	}
A
aarzilli 已提交
915

916
	protest.AllowRecording(t)
917
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
918
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
919 920
		assertNoError(err, t, "BreakByLocation()")

921
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
922

923
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
aarzilli 已提交
924 925 926 927 928
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
929
		for i, g := range gs {
930
			locations, err := g.Stacktrace(40, false)
931 932
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
933
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
934 935
				continue
			}
A
aarzilli 已提交
936

937
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
938 939 940
				mainCount++
			}

941 942 943 944 945 946 947 948
			found := false
			for _, agoroutineStack := range agoroutineStacks {
				if stackMatch(agoroutineStack, locations, true) {
					found = true
				}
			}

			if found {
A
aarzilli 已提交
949 950
				agoroutineCount++
			} else {
D
Derek Parker 已提交
951
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
952 953
				for i := range locations {
					name := ""
954 955
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
956
					}
957
					t.Logf("\t%s:%d %s (%#x)\n", locations[i].Call.File, locations[i].Call.Line, name, locations[i].Current.PC)
A
aarzilli 已提交
958 959 960 961 962
				}
			}
		}

		if mainCount != 1 {
963
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
964 965 966 967 968 969
		}

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

970
		p.ClearBreakpoint(bp.Addr)
971
		proc.Continue(p)
A
aarzilli 已提交
972 973
	})
}
974 975

func TestKill(t *testing.T) {
976 977 978 979
	if testBackend == "lldb" {
		// k command presumably works but leaves the process around?
		return
	}
980 981 982 983
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
		if err := p.Detach(true); err != nil {
			t.Fatal(err)
		}
984
		if valid, _ := p.Valid(); valid {
985 986 987 988 989 990 991 992 993
			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())
			}
		}
	})
994
}
995

996
func testGSupportFunc(name string, t *testing.T, p proc.Process, fixture protest.Fixture) {
997
	bp, err := setFunctionBreakpoint(p, "main.main")
998 999
	assertNoError(err, t, name+": BreakByLocation()")

1000
	assertNoError(proc.Continue(p), t, name+": Continue()")
1001

1002
	g, err := proc.GetG(p.CurrentThread())
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
	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) {
1015
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
1016 1017 1018
		testGSupportFunc("nocgo", t, p, fixture)
	})

1019 1020 1021 1022
	// 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 已提交
1023 1024 1025
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
1026

1027
	protest.AllowRecording(t)
1028
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
1029 1030 1031
		testGSupportFunc("cgo", t, p, fixture)
	})
}
1032 1033

func TestContinueMulti(t *testing.T) {
1034
	protest.AllowRecording(t)
1035
	withTestProcess("integrationprog", t, func(p proc.Process, fixture protest.Fixture) {
1036
		bp1, err := setFunctionBreakpoint(p, "main.main")
1037 1038
		assertNoError(err, t, "BreakByLocation()")

1039
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
1040 1041 1042 1043 1044
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
1045
			err := proc.Continue(p)
1046
			if valid, _ := p.Valid(); !valid {
1047 1048 1049 1050
				break
			}
			assertNoError(err, t, "Continue()")

1051
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp1.ID {
1052 1053 1054
				mainCount++
			}

1055
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp2.ID {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
				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)
		}
	})
}
1069

1070
func TestBreakpointOnFunctionEntry(t *testing.T) {
1071
	testseq2(t, "testprog", "main.main", []seqTest{{contContinue, 17}})
1072
}
1073 1074

func TestProcessReceivesSIGCHLD(t *testing.T) {
1075
	protest.AllowRecording(t)
1076
	withTestProcess("sigchldprog", t, func(p proc.Process, fixture protest.Fixture) {
1077
		err := proc.Continue(p)
1078
		_, ok := err.(proc.ErrProcessExited)
1079
		if !ok {
1080
			t.Fatalf("Continue() returned unexpected error type %v", err)
1081 1082 1083
		}
	})
}
1084 1085

func TestIssue239(t *testing.T) {
1086
	withTestProcess("is sue239", t, func(p proc.Process, fixture protest.Fixture) {
1087
		pos, _, err := p.BinInfo().LineToPC(fixture.Source, 17)
1088
		assertNoError(err, t, "LineToPC()")
1089
		_, err = p.SetBreakpoint(pos, proc.UserBreakpoint, nil)
1090
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
1091
		assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue()"))
1092 1093
	})
}
1094

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
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")
}

1109
func evalVariableOrError(p proc.Process, symbol string) (*proc.Variable, error) {
1110 1111 1112 1113 1114 1115 1116
	var scope *proc.EvalScope
	var err error

	if testBackend == "rr" {
		var frame proc.Stackframe
		frame, err = findFirstNonRuntimeFrame(p)
		if err == nil {
1117
			scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)
1118 1119 1120 1121
		}
	} else {
		scope, err = proc.GoroutineScope(p.CurrentThread())
	}
1122

1123 1124 1125
	if err != nil {
		return nil, err
	}
1126
	return scope.EvalVariable(symbol, normalLoadConfig)
1127 1128
}

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
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
}

1139
func setVariable(p proc.Process, symbol, value string) error {
1140
	scope, err := proc.GoroutineScope(p.CurrentThread())
1141 1142 1143 1144 1145 1146 1147
	if err != nil {
		return err
	}
	return scope.SetVariable(symbol, value)
}

func TestVariableEvaluation(t *testing.T) {
1148
	protest.AllowRecording(t)
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
	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 已提交
1171 1172
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
		{"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},
	}

1184
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1185
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1186 1187

		for _, tc := range testcases {
1188
			v := evalVariable(p, t, tc.name)
1189 1190 1191 1192 1193 1194 1195

			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 {
1196 1197 1198
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1199 1200 1201
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1202 1203
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1204 1205 1206
					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 已提交
1207 1208 1209 1210 1211 1212
				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)
					}
1213 1214
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
						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) {
1233
	protest.AllowRecording(t)
1234
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
1235 1236
		_, err := setFunctionBreakpoint(p, "main.stacktraceme")
		assertNoError(err, t, "setFunctionBreakpoint")
1237
		assertNoError(proc.Continue(p), t, "Continue()")
1238

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

1241
		// Testing evaluation on goroutines
1242
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1243 1244 1245 1246
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
1247
			frames, err := g.Stacktrace(10, false)
1248 1249 1250 1251
			if err != nil {
				t.Logf("could not stacktrace goroutine %d: %v\n", g.ID, err)
				continue
			}
1252
			t.Logf("Goroutine %d", g.ID)
1253
			logStacktrace(t, p.BinInfo(), frames)
1254 1255 1256 1257 1258 1259 1260 1261
			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 已提交
1262
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1263 1264 1265
				continue
			}

1266
			scope, err := proc.ConvertEvalScope(p, g.ID, frame, 0)
1267 1268
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
1269
			v, err := scope.EvalVariable("i", normalLoadConfig)
1270 1271
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1272
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1273 1274
				continue
			}
1275 1276
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1277 1278 1279 1280 1281 1282 1283 1284
		}

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

1285
		// Testing evaluation on frames
1286 1287
		assertNoError(proc.Continue(p), t, "Continue() 2")
		g, err := proc.GetG(p.CurrentThread())
1288 1289 1290
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
1291
			scope, err := proc.ConvertEvalScope(p, g.ID, i+1, 0)
1292
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
1293
			v, err := scope.EvalVariable("n", normalLoadConfig)
1294
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1295
			n, _ := constant.Int64Val(v.Value)
1296 1297 1298 1299 1300 1301 1302 1303 1304
			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) {
1305
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1306
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1307 1308

		pval := func(n int64) {
1309
			variable := evalVariable(p, t, "p1")
1310 1311 1312
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1313 1314 1315 1316 1317 1318
			}
		}

		pval(1)

		// change p1 to point to i2
1319
		scope, err := proc.GoroutineScope(p.CurrentThread())
1320
		assertNoError(err, t, "Scope()")
1321
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1322 1323
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1324 1325 1326 1327 1328 1329 1330 1331 1332
		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) {
1333
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1334
		err := proc.Continue(p)
1335 1336
		assertNoError(err, t, "Continue() returned an error")

1337 1338
		evalVariable(p, t, "a1")
		evalVariable(p, t, "a2")
1339 1340

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

1344
		evalVariable(p, t, "a1")
1345

1346
		_, err = evalVariableOrError(p, "a2")
1347 1348 1349 1350 1351 1352 1353
		if err == nil {
			t.Fatalf("Can eval out of scope variable a2")
		}
	})
}

func TestRecursiveStructure(t *testing.T) {
1354
	protest.AllowRecording(t)
1355
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1356
		assertNoError(proc.Continue(p), t, "Continue()")
1357
		v := evalVariable(p, t, "aas")
1358 1359 1360
		t.Logf("v: %v\n", v)
	})
}
1361 1362 1363

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1364
	protest.AllowRecording(t)
1365
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1366
		assertNoError(proc.Continue(p), t, "Continue()")
1367
		evalVariable(p, t, "iface5")
1368 1369
	})
}
1370 1371 1372

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1373
	protest.AllowRecording(t)
1374
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1375
		assertNoError(proc.Continue(p), t, "Continue()")
1376
		iface2fn1v := evalVariable(p, t, "iface2fn1")
1377 1378
		t.Logf("iface2fn1: %v\n", iface2fn1v)

1379
		iface2fn2v := evalVariable(p, t, "iface2fn2")
1380 1381 1382
		t.Logf("iface2fn2: %v\n", iface2fn2v)
	})
}
1383 1384

func TestBreakpointCounts(t *testing.T) {
1385
	protest.AllowRecording(t)
1386
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1387
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1388
		assertNoError(err, t, "LineToPC")
1389
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1390 1391 1392
		assertNoError(err, t, "SetBreakpoint()")

		for {
1393
			if err := proc.Continue(p); err != nil {
1394
				if _, exited := err.(proc.ErrProcessExited); exited {
1395 1396 1397 1398 1399 1400 1401
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
		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)
			}
		}
	})
}

1418 1419
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
1420
	protest.AllowRecording(b)
1421
	b.SetBytes(int64(64 * 128))
1422
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1423
		assertNoError(proc.Continue(p), b, "Continue()")
1424
		for i := 0; i < b.N; i++ {
1425
			evalVariable(p, b, "bencharr")
1426 1427 1428 1429
		}
	})
}

1430 1431 1432 1433 1434 1435 1436
const doTestBreakpointCountsWithDetection = false

func TestBreakpointCountsWithDetection(t *testing.T) {
	if !doTestBreakpointCountsWithDetection {
		return
	}
	m := map[int64]int64{}
1437
	protest.AllowRecording(t)
1438
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1439
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1440
		assertNoError(err, t, "LineToPC")
1441
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1442 1443 1444
		assertNoError(err, t, "SetBreakpoint()")

		for {
1445
			if err := proc.Continue(p); err != nil {
1446
				if _, exited := err.(proc.ErrProcessExited); exited {
1447 1448 1449 1450
					break
				}
				assertNoError(err, t, "Continue()")
			}
1451
			for _, th := range p.ThreadList() {
1452
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
1453 1454
					continue
				}
1455
				scope, err := proc.GoroutineScope(th)
1456
				assertNoError(err, t, "Scope()")
1457
				v, err := scope.EvalVariable("i", normalLoadConfig)
1458 1459
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
1460
				v, err = scope.EvalVariable("id", normalLoadConfig)
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
				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)
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
		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)
			}
		}
	})
}
1492

1493 1494 1495
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
1496
	protest.AllowRecording(b)
1497
	b.SetBytes(int64(64*128 + 64*8))
1498
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1499
		assertNoError(proc.Continue(p), b, "Continue()")
1500
		for i := 0; i < b.N; i++ {
1501
			evalVariable(p, b, "bencharr")
1502 1503 1504 1505 1506 1507 1508 1509
		}
	})
}

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
1510
	protest.AllowRecording(b)
1511
	b.SetBytes(int64(41 * (2*8 + 9)))
1512
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1513
		assertNoError(proc.Continue(p), b, "Continue()")
1514
		for i := 0; i < b.N; i++ {
1515
			evalVariable(p, b, "m1")
1516 1517 1518 1519 1520
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1521
	protest.AllowRecording(b)
1522
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1523
		assertNoError(proc.Continue(p), b, "Continue()")
1524
		for i := 0; i < b.N; i++ {
1525
			p.Common().ClearAllGCache()
1526
			_, _, err := proc.GoroutinesInfo(p, 0, 0)
1527 1528 1529 1530 1531
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1532 1533
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
1534
	protest.AllowRecording(t)
1535
	withTestProcess("issue262", t, func(p proc.Process, fixture protest.Fixture) {
1536
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 11)
1537
		assertNoError(err, t, "LineToPC")
1538
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1539 1540
		assertNoError(err, t, "SetBreakpoint()")

1541 1542
		assertNoError(proc.Continue(p), t, "Continue()")
		err = proc.Continue(p)
1543 1544 1545
		if err == nil {
			t.Fatalf("No error on second continue")
		}
1546
		_, exited := err.(proc.ErrProcessExited)
1547 1548 1549 1550 1551
		if !exited {
			t.Fatalf("Process did not exit after second continue: %v", err)
		}
	})
}
1552

1553
func TestIssue305(t *testing.T) {
1554 1555 1556
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1557
	protest.AllowRecording(t)
1558
	withTestProcess("issue305", t, func(p proc.Process, fixture protest.Fixture) {
1559
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 5)
1560
		assertNoError(err, t, "LineToPC()")
1561
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1562 1563
		assertNoError(err, t, "SetBreakpoint()")

1564
		assertNoError(proc.Continue(p), t, "Continue()")
1565

1566 1567 1568 1569 1570
		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")
1571 1572 1573
	})
}

1574 1575 1576
func TestPointerLoops(t *testing.T) {
	// Pointer loops through map entries, pointers and slices
	// Regression test for issue #341
1577
	protest.AllowRecording(t)
1578
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1579
		assertNoError(proc.Continue(p), t, "Continue()")
1580 1581
		for _, expr := range []string{"mapinf", "ptrinf", "sliceinf"} {
			t.Logf("requesting %s", expr)
1582
			v := evalVariable(p, t, expr)
1583 1584
			t.Logf("%s: %v\n", expr, v)
		}
1585 1586
	})
}
1587 1588

func BenchmarkLocalVariables(b *testing.B) {
1589
	protest.AllowRecording(b)
1590
	withTestProcess("testvariables", b, func(p proc.Process, fixture protest.Fixture) {
1591 1592
		assertNoError(proc.Continue(p), b, "Continue() returned an error")
		scope, err := proc.GoroutineScope(p.CurrentThread())
1593 1594
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
1595
			_, err := scope.LocalVariables(normalLoadConfig)
1596 1597 1598 1599
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1600 1601

func TestCondBreakpoint(t *testing.T) {
1602
	protest.AllowRecording(t)
1603
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1604
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1605
		assertNoError(err, t, "LineToPC")
1606
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1607 1608 1609 1610 1611 1612 1613
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1614
		assertNoError(proc.Continue(p), t, "Continue()")
1615

1616
		nvar := evalVariable(p, t, "n")
1617 1618 1619 1620 1621 1622 1623 1624 1625

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

func TestCondBreakpointError(t *testing.T) {
1626
	protest.AllowRecording(t)
1627
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1628
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1629
		assertNoError(err, t, "LineToPC")
1630
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1631 1632 1633 1634 1635 1636 1637
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1638
		err = proc.Continue(p)
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
		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"},
		}

1653
		err = proc.Continue(p)
1654
		if err != nil {
1655
			if _, exited := err.(proc.ErrProcessExited); !exited {
1656 1657 1658
				t.Fatalf("Unexpected error on second Continue(): %v", err)
			}
		} else {
1659
			nvar := evalVariable(p, t, "n")
1660 1661 1662 1663 1664 1665 1666 1667

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

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1671
	protest.AllowRecording(t)
1672
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1673
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1674
		mmvar := evalVariable(p, t, "mainMenu")
1675 1676 1677 1678 1679
		if mmvar.Kind != reflect.Slice {
			t.Fatalf("Wrong kind for mainMenu: %v\n", mmvar.Kind)
		}
	})
}
1680 1681

func TestStepIntoFunction(t *testing.T) {
1682
	withTestProcess("teststep", t, func(p proc.Process, fixture protest.Fixture) {
1683
		// Continue until breakpoint
1684
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1685
		// Step into function
1686
		assertNoError(proc.Step(p), t, "Step() returned an error")
1687
		// We should now be inside the function.
1688
		loc, err := p.CurrentThread().Location()
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
		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)
		}
	})
}
1703 1704 1705

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
1706 1707 1708 1709 1710

	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.
1711
		t.Skip("can not evaluate not-yet-declared variables with go 1.10")
1712 1713
	}

1714
	protest.AllowRecording(t)
1715
	withTestProcess("issue384", t, func(p proc.Process, fixture protest.Fixture) {
1716
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 13)
1717
		assertNoError(err, t, "LineToPC()")
1718
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1719
		assertNoError(err, t, "SetBreakpoint()")
1720
		assertNoError(proc.Continue(p), t, "Continue()")
1721
		evalVariable(p, t, "st")
1722 1723
	})
}
A
aarzilli 已提交
1724 1725 1726

func TestIssue332_Part1(t *testing.T) {
	// Next shouldn't step inside a function call
1727
	protest.AllowRecording(t)
1728
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1729
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1730
		assertNoError(err, t, "LineToPC()")
1731
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1732
		assertNoError(err, t, "SetBreakpoint()")
1733 1734 1735
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "first Next()")
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
		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
1754
	protest.AllowRecording(t)
1755
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1756
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1757
		assertNoError(err, t, "LineToPC()")
1758
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1759
		assertNoError(err, t, "SetBreakpoint()")
1760
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
1761 1762 1763

		// step until we enter changeMe
		for {
1764 1765
			assertNoError(proc.Step(p), t, "Step()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1766 1767 1768 1769 1770 1771 1772 1773 1774
			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
			}
		}

1775 1776 1777
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers()")
		pc := regs.PC()
1778
		pcAfterPrologue, err := proc.FindFunctionLocation(p, "main.changeMe", true, -1)
1779
		assertNoError(err, t, "FindFunctionLocation()")
1780
		pcEntry, err := proc.FindFunctionLocation(p, "main.changeMe", false, 0)
1781 1782 1783
		if err != nil {
			t.Fatalf("got error while finding function location: %v", err)
		}
1784 1785 1786 1787 1788 1789 1790
		if pcAfterPrologue == pcEntry {
			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)
		}

1791 1792 1793 1794
		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)
1795
		if _, exited := err.(proc.ErrProcessExited); !exited {
A
aarzilli 已提交
1796 1797 1798 1799
			assertNoError(err, t, "final Continue()")
		}
	})
}
1800 1801

func TestIssue396(t *testing.T) {
1802
	withTestProcess("callme", t, func(p proc.Process, fixture protest.Fixture) {
1803
		_, err := proc.FindFunctionLocation(p, "main.init", true, -1)
1804 1805 1806
		assertNoError(err, t, "FindFunctionLocation()")
	})
}
1807 1808 1809

func TestIssue414(t *testing.T) {
	// Stepping until the program exits
1810
	protest.AllowRecording(t)
1811
	withTestProcess("math", t, func(p proc.Process, fixture protest.Fixture) {
1812
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1813
		assertNoError(err, t, "LineToPC()")
1814
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1815
		assertNoError(err, t, "SetBreakpoint()")
1816
		assertNoError(proc.Continue(p), t, "Continue()")
1817
		for {
1818
			err := proc.Step(p)
1819
			if err != nil {
1820
				if _, exited := err.(proc.ErrProcessExited); exited {
1821 1822 1823 1824 1825 1826 1827
					break
				}
			}
			assertNoError(err, t, "Step()")
		}
	})
}
1828 1829

func TestPackageVariables(t *testing.T) {
1830
	protest.AllowRecording(t)
1831
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1832
		err := proc.Continue(p)
1833
		assertNoError(err, t, "Continue()")
1834
		scope, err := proc.GoroutineScope(p.CurrentThread())
1835
		assertNoError(err, t, "Scope()")
1836
		vars, err := scope.PackageVariables(normalLoadConfig)
1837 1838 1839
		assertNoError(err, t, "PackageVariables()")
		failed := false
		for _, v := range vars {
1840
			if v.Unreadable != nil && v.Unreadable.Error() != "no location attribute Location" {
1841 1842 1843 1844 1845 1846 1847 1848 1849
				failed = true
				t.Logf("Unreadable variable %s: %v", v.Name, v.Unreadable)
			}
		}
		if failed {
			t.Fatalf("previous errors")
		}
	})
}
1850 1851

func TestIssue149(t *testing.T) {
1852 1853
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
1854 1855 1856
		return
	}
	// setting breakpoint on break statement
1857
	withTestProcess("break", t, func(p proc.Process, fixture protest.Fixture) {
1858
		_, err := proc.FindFileLocation(p, fixture.Source, 8)
1859 1860 1861
		assertNoError(err, t, "FindFileLocation()")
	})
}
1862 1863

func TestPanicBreakpoint(t *testing.T) {
1864
	protest.AllowRecording(t)
1865
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
1866
		assertNoError(proc.Continue(p), t, "Continue()")
1867 1868
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1869
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1870 1871 1872
		}
	})
}
1873

1874
func TestCmdLineArgs(t *testing.T) {
1875
	expectSuccess := func(p proc.Process, fixture protest.Fixture) {
1876
		err := proc.Continue(p)
1877 1878
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint != nil && bp.Name == proc.UnrecoveredPanic {
1879
			t.Fatalf("testing args failed on unrecovered-panic breakpoint: %v", bp)
1880
		}
1881
		exit, exited := err.(proc.ErrProcessExited)
1882
		if !exited {
1883
			t.Fatalf("Process did not exit: %v", err)
1884 1885
		} else {
			if exit.Status != 0 {
1886
				t.Fatalf("process exited with invalid status %d", exit.Status)
1887 1888 1889 1890
			}
		}
	}

1891
	expectPanic := func(p proc.Process, fixture protest.Fixture) {
1892
		proc.Continue(p)
1893 1894
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1895
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1896 1897 1898 1899
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
1900 1901 1902
	withTestProcessArgs("testargs", t, ".", []string{"test"}, 0, expectSuccess)
	withTestProcessArgs("testargs", t, ".", []string{"-test"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass flag"}, 0, expectSuccess)
1903
	// check that arguments with spaces are *only* passed correctly when correctly called
1904 1905 1906
	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)
1907 1908
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
1909 1910 1911
	withTestProcessArgs("testargs", t, ".", []string{"invalid"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "invalid"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"invalid", "pass flag"}, 0, expectPanic)
1912 1913
}

1914 1915 1916 1917 1918
func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
1919
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
		go func() {
			// Wait for program to start listening.
			for {
				conn, err := net.Dial("tcp", "localhost:9191")
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}

			p.RequestManualStop()
		}()

1934 1935
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
1936 1937 1938
		assertNoError(err, t, "Stacktrace()")
	})
}
1939

1940
func TestNextParked(t *testing.T) {
1941
	protest.AllowRecording(t)
1942
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1943 1944 1945 1946
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1947
		var parkedg *proc.G
1948
		for parkedg == nil {
1949
			err := proc.Continue(p)
1950
			if _, exited := err.(proc.ErrProcessExited); exited {
1951 1952 1953 1954 1955
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1956
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1957 1958
			assertNoError(err, t, "GoroutinesInfo()")

1959 1960 1961 1962
			// 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
1963
			for _, g := range gs {
1964 1965 1966
				if g.Thread != nil {
					continue
				}
1967
				frames, _ := g.Stacktrace(5, false)
1968 1969 1970 1971 1972 1973 1974 1975 1976
				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
1977 1978 1979 1980 1981 1982
				}
			}
		}

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

1985 1986
		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)
1987 1988 1989
		}
	})
}
1990 1991

func TestStepParked(t *testing.T) {
1992
	protest.AllowRecording(t)
1993
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1994 1995 1996 1997
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1998
		var parkedg *proc.G
1999 2000
	LookForParkedG:
		for {
2001
			err := proc.Continue(p)
2002
			if _, exited := err.(proc.ErrProcessExited); exited {
2003 2004 2005 2006 2007
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

2008
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
2009 2010 2011
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
2012
				if g.Thread == nil && g.CurrentLoc.Fn != nil && g.CurrentLoc.Fn.Name == "main.sayhi" {
2013 2014 2015 2016 2017 2018
					parkedg = g
					break LookForParkedG
				}
			}
		}

A
aarzilli 已提交
2019
		t.Logf("Parked g is: %v\n", parkedg)
2020
		frames, _ := parkedg.Stacktrace(20, false)
A
aarzilli 已提交
2021 2022 2023 2024 2025 2026 2027 2028
		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)
		}

2029 2030
		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
2031
		assertNoError(proc.Step(p), t, "Step()")
2032

2033 2034
		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)
2035 2036 2037
		}
	})
}
2038 2039 2040 2041 2042 2043 2044 2045

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")
2046 2047 2048 2049 2050
	defer os.Remove(exepath)
	var err error

	switch testBackend {
	case "native":
2051
		_, err = native.Launch([]string{exepath}, ".", false, []string{})
2052
	case "lldb":
2053
		_, err = gdbserial.LLDBLaunch([]string{exepath}, ".", false, []string{})
2054 2055 2056
	default:
		t.Skip("test not valid for this backend")
	}
2057 2058 2059
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
2060 2061
	if err != proc.ErrNotExecutable {
		t.Fatalf("expected error \"%v\" got \"%v\"", proc.ErrNotExecutable, err)
2062 2063 2064 2065
	}
}

func TestUnsupportedArch(t *testing.T) {
2066 2067
	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, ""}) {
2068 2069 2070
		// cross compile (with -N?) works only on select versions of go
		return
	}
2071

2072 2073 2074
	fixturesDir := protest.FindFixturesDir()
	infile := filepath.Join(fixturesDir, "math.go")
	outfile := filepath.Join(fixturesDir, "_math_debug_386")
2075

2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
	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)
2088

2089 2090 2091 2092
	var p proc.Process

	switch testBackend {
	case "native":
2093
		p, err = native.Launch([]string{outfile}, ".", false, []string{})
2094
	case "lldb":
2095
		p, err = gdbserial.LLDBLaunch([]string{outfile}, ".", false, []string{})
2096 2097 2098 2099
	default:
		t.Skip("test not valid for this backend")
	}

2100
	switch err {
2101
	case proc.ErrUnsupportedLinuxArch, proc.ErrUnsupportedWindowsArch, proc.ErrUnsupportedDarwinArch:
2102 2103
		// all good
	case nil:
A
aarzilli 已提交
2104
		p.Detach(true)
2105 2106 2107 2108 2109
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
2110

2111
func TestIssue573(t *testing.T) {
2112
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
2113
	// of the function and the internal breakpoint set by StepInto may be missed.
2114
	protest.AllowRecording(t)
2115
	withTestProcess("issue573", t, func(p proc.Process, fixture protest.Fixture) {
2116
		fentry, _ := proc.FindFunctionLocation(p, "main.foo", false, 0)
2117
		_, err := p.SetBreakpoint(fentry, proc.UserBreakpoint, nil)
2118
		assertNoError(err, t, "SetBreakpoint()")
2119 2120 2121 2122
		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.
2123 2124
	})
}
2125 2126

func TestTestvariables2Prologue(t *testing.T) {
2127
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2128
		addrEntry, err := proc.FindFunctionLocation(p, "main.main", false, 0)
2129
		assertNoError(err, t, "FindFunctionLocation - entrypoint")
2130
		addrPrologue, err := proc.FindFunctionLocation(p, "main.main", true, 0)
2131 2132 2133 2134 2135 2136
		assertNoError(err, t, "FindFunctionLocation - postprologue")
		if addrEntry == addrPrologue {
			t.Fatalf("Prologue detection failed on testvariables2.go/main.main")
		}
	})
}
2137 2138 2139 2140 2141

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 已提交
2142
	testseq("defercall", contNext, []nextTest{
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
		{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
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
	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)
	}
2167
}
A
aarzilli 已提交
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177

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.
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
	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 已提交
2192 2193 2194 2195 2196
}

func TestStepReturnAndPanic(t *testing.T) {
	// Tests that Step works correctly when returning from functions
	// and when a deferred function is called when panic'ing.
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
	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 已提交
2215 2216 2217 2218 2219 2220 2221 2222 2223
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 17},
			{17, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
2224
	default:
A
aarzilli 已提交
2225 2226 2227 2228 2229 2230 2231 2232 2233
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
	}
A
aarzilli 已提交
2234 2235 2236 2237 2238
}

func TestStepDeferReturn(t *testing.T) {
	// Tests that Step works correctly when a deferred function is
	// called during a return.
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
	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 已提交
2262 2263 2264 2265 2266
}

func TestStepIgnorePrivateRuntime(t *testing.T) {
	// Tests that Step will ignore calls to private runtime functions
	// (such as runtime.convT2E in this case)
2267 2268 2269 2270 2271 2272 2273
	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 已提交
2274 2275 2276 2277
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
2278 2279
			{15, 22}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 7):
2280 2281 2282 2283
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
2284 2285 2286 2287
			{15, 14},
			{14, 17},
			{17, 22}}, "", t)
	default:
A
aarzilli 已提交
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
		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.
2300
	protest.AllowRecording(t)
2301
	withTestProcess("issue561", t, func(p proc.Process, fixture protest.Fixture) {
2302
		setFileBreakpoint(p, t, fixture, 10)
2303 2304
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step()")
2305
		assertLineNumber(p, t, 5, "wrong line number after Step,")
A
aarzilli 已提交
2306 2307 2308
	})
}

A
aarzilli 已提交
2309
func TestStepOut(t *testing.T) {
2310
	testseq2(t, "testnextprog", "main.helloworld", []seqTest{{contContinue, 13}, {contStepout, 35}})
A
aarzilli 已提交
2311 2312
}

A
aarzilli 已提交
2313
func TestStepConcurrentDirect(t *testing.T) {
2314
	protest.AllowRecording(t)
2315
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2316
		pc, err := proc.FindFileLocation(p, fixture.Source, 37)
A
aarzilli 已提交
2317
		assertNoError(err, t, "FindFileLocation()")
2318
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2319 2320
		assertNoError(err, t, "SetBreakpoint()")

2321
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2322 2323 2324
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")

A
aarzilli 已提交
2325
		for _, b := range p.Breakpoints().M {
2326
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2327 2328 2329 2330 2331 2332
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

2333
		gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2334 2335 2336 2337 2338 2339

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

		i := 0
		count := 0
		for {
A
aarzilli 已提交
2340
			anyerr := false
2341 2342
			if p.SelectedGoroutine().ID != gid {
				t.Errorf("Step switched to different goroutine %d %d\n", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2343 2344
				anyerr = true
			}
A
aarzilli 已提交
2345 2346 2347 2348 2349 2350
			f, ln := currentLineNumber(p, t)
			if ln != seq[i] {
				if i == 1 && ln == 40 {
					// loop exited
					break
				}
2351
				frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
A
aarzilli 已提交
2352
				if err != nil {
2353
					t.Errorf("Could not get stacktrace of goroutine %d\n", p.SelectedGoroutine().ID)
A
aarzilli 已提交
2354
				} else {
2355
					t.Logf("Goroutine %d (thread: %d):", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
A
aarzilli 已提交
2356 2357 2358 2359 2360 2361
					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 已提交
2362
			}
A
aarzilli 已提交
2363 2364
			if anyerr {
				t.FailNow()
A
aarzilli 已提交
2365 2366 2367 2368 2369
			}
			i = (i + 1) % len(seq)
			if i == 0 {
				count++
			}
2370
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2371 2372 2373 2374 2375 2376 2377 2378 2379
		}

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

func TestStepConcurrentPtr(t *testing.T) {
2380
	protest.AllowRecording(t)
2381
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2382
		pc, err := proc.FindFileLocation(p, fixture.Source, 24)
A
aarzilli 已提交
2383
		assertNoError(err, t, "FindFileLocation()")
2384
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2385 2386
		assertNoError(err, t, "SetBreakpoint()")

A
aarzilli 已提交
2387
		for _, b := range p.Breakpoints().M {
2388
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2389 2390 2391 2392 2393 2394
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2395 2396 2397
		kvals := map[int]int64{}
		count := 0
		for {
2398
			err := proc.Continue(p)
2399
			_, exited := err.(proc.ErrProcessExited)
A
aarzilli 已提交
2400 2401 2402 2403 2404 2405 2406
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
2407
				for _, th := range p.ThreadList() {
2408
					t.Logf("thread %d stopped on breakpoint %v", th.ThreadID(), th.Breakpoint())
A
aarzilli 已提交
2409
				}
2410
				curbp := p.CurrentThread().Breakpoint()
2411
				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 已提交
2412 2413
			}

2414
			gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2415

2416
			kvar := evalVariable(p, t, "k")
A
aarzilli 已提交
2417 2418 2419 2420
			k, _ := constant.Int64Val(kvar.Value)

			if oldk, ok := kvals[gid]; ok {
				if oldk >= k {
2421
					t.Fatalf("Goroutine %d did not make progress?", gid)
A
aarzilli 已提交
2422 2423 2424 2425
				}
			}
			kvals[gid] = k

2426
			assertNoError(proc.Step(p), t, "Step()")
2427
			for p.Breakpoints().HasInternalBreakpoints() {
2428 2429
				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 已提交
2430
				}
2431
				assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2432 2433
			}

2434 2435
			if p.SelectedGoroutine().ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2436 2437
			}

2438
			f, ln = assertLineNumber(p, t, 13, "Step did not step into function call")
A
aarzilli 已提交
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453

			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 已提交
2454
func TestStepOutDefer(t *testing.T) {
2455
	protest.AllowRecording(t)
2456
	withTestProcess("testnextdefer", t, func(p proc.Process, fixture protest.Fixture) {
2457
		pc, err := proc.FindFileLocation(p, fixture.Source, 9)
A
aarzilli 已提交
2458
		assertNoError(err, t, "FindFileLocation()")
2459
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2460
		assertNoError(err, t, "SetBreakpoint()")
2461
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2462 2463
		p.ClearBreakpoint(bp.Addr)

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

2466
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2467

2468
		f, l, _ := p.BinInfo().PCToLine(currentPC(p, t))
A
aarzilli 已提交
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
		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
2479 2480 2481
	testseq2(t, "defercall", "", []seqTest{
		{contContinue, 11},
		{contStepout, 28}})
A
aarzilli 已提交
2482 2483
}

2484 2485
const maxInstructionLength uint64 = 15

A
aarzilli 已提交
2486
func TestStepOnCallPtrInstr(t *testing.T) {
2487
	protest.AllowRecording(t)
2488
	withTestProcess("teststepprog", t, func(p proc.Process, fixture protest.Fixture) {
2489
		pc, err := proc.FindFileLocation(p, fixture.Source, 10)
A
aarzilli 已提交
2490
		assertNoError(err, t, "FindFileLocation()")
2491
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2492 2493
		assertNoError(err, t, "SetBreakpoint()")

2494
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2495 2496 2497 2498 2499 2500 2501 2502

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
2503
			regs, err := p.CurrentThread().Registers(false)
2504
			assertNoError(err, t, "Registers()")
2505
			pc := regs.PC()
2506
			text, err := proc.Disassemble(p, nil, pc, pc+maxInstructionLength)
A
aarzilli 已提交
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
			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")
		}

2519
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2520

2521 2522 2523 2524 2525
		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 已提交
2526 2527
	})
}
2528 2529

func TestIssue594(t *testing.T) {
2530 2531 2532 2533 2534 2535 2536 2537
	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
	}
2538 2539 2540 2541
	// 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.
2542
	protest.AllowRecording(t)
2543
	withTestProcess("issue594", t, func(p proc.Process, fixture protest.Fixture) {
2544
		assertNoError(proc.Continue(p), t, "Continue()")
2545 2546 2547 2548 2549 2550 2551 2552 2553
		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)
		}
2554 2555 2556 2557 2558
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2559 2560 2561 2562 2563

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
2564 2565 2566 2567 2568 2569 2570 2571 2572
	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 已提交
2573
}
E
Evgeny L 已提交
2574 2575 2576 2577 2578 2579 2580

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"
	}
2581
	protest.AllowRecording(t)
2582
	withTestProcessArgs("workdir", t, wd, []string{}, 0, func(p proc.Process, fixture protest.Fixture) {
2583
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 14)
E
Evgeny L 已提交
2584
		assertNoError(err, t, "LineToPC")
2585 2586
		p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
		proc.Continue(p)
2587
		v := evalVariable(p, t, "pwd")
E
Evgeny L 已提交
2588 2589 2590 2591
		str := constant.StringVal(v.Value)
		if wd != str {
			t.Fatalf("Expected %s got %s\n", wd, str)
		}
2592
	})
E
Evgeny L 已提交
2593
}
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604

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)},
	}
2605
	protest.AllowRecording(t)
2606
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2607
		assertNoError(proc.Continue(p), t, "Continue()")
2608
		for _, tc := range testcases {
2609
			v := evalVariable(p, t, tc.name)
2610 2611 2612 2613 2614 2615 2616 2617 2618
			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)
			}
		}
	})
}
2619 2620 2621

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
2622
	protest.AllowRecording(t)
2623
	withTestProcess("issue683", t, func(p proc.Process, fixture protest.Fixture) {
2624 2625
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
2626
		assertNoError(proc.Continue(p), t, "First Continue()")
2627 2628 2629
		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
2630
			err := proc.Step(p)
2631 2632 2633 2634
			if err != nil {
				break
			}
		}
2635 2636 2637 2638
	})
}

func TestIssue664(t *testing.T) {
2639
	protest.AllowRecording(t)
2640
	withTestProcess("issue664", t, func(p proc.Process, fixture protest.Fixture) {
2641
		setFileBreakpoint(p, t, fixture, 4)
2642 2643
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
2644
		assertLineNumber(p, t, 5, "Did not continue to correct location,")
2645 2646
	})
}
A
Alessandro Arzilli 已提交
2647 2648 2649

// Benchmarks (*Processs).Continue + (*Scope).FunctionArguments
func BenchmarkTrace(b *testing.B) {
2650
	protest.AllowRecording(b)
2651
	withTestProcess("traceperf", b, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2652 2653 2654 2655
		_, err := setFunctionBreakpoint(p, "main.PerfCheck")
		assertNoError(err, b, "setFunctionBreakpoint()")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
2656 2657
			assertNoError(proc.Continue(p), b, "Continue()")
			s, err := proc.GoroutineScope(p.CurrentThread())
A
Alessandro Arzilli 已提交
2658
			assertNoError(err, b, "Scope()")
2659
			_, err = s.FunctionArguments(proc.LoadConfig{false, 0, 64, 0, 3, 0})
A
Alessandro Arzilli 已提交
2660 2661 2662 2663 2664
			assertNoError(err, b, "FunctionArguments()")
		}
		b.StopTimer()
	})
}
A
Alessandro Arzilli 已提交
2665 2666 2667 2668 2669 2670

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.
2671
	protest.AllowRecording(t)
2672
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2673
		_, err := setFunctionBreakpoint(p, "runtime.deferreturn")
2674
		assertNoError(err, t, "setFunctionBreakpoint(runtime.deferreturn)")
2675
		assertNoError(proc.Continue(p), t, "First Continue()")
2676 2677 2678 2679 2680 2681

		// 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.
		_, err = setFunctionBreakpoint(p, "main.sampleFunction")
		assertNoError(err, t, "setFunctionBreakpoint(main.sampleFunction)")
A
Alessandro Arzilli 已提交
2682
		for i := 0; i < 20; i++ {
2683 2684 2685 2686 2687 2688
			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
			}
2689
			assertNoError(proc.Next(p), t, fmt.Sprintf("Next() %d", i))
A
Alessandro Arzilli 已提交
2690 2691 2692 2693
		}
	})
}

2694
func getg(goid int, gs []*proc.G) *proc.G {
A
Alessandro Arzilli 已提交
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
	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.
2709

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

2715 2716 2717 2718 2719
	// 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")

2720
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2721 2722 2723 2724 2725
		// 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
		_, err := setFunctionBreakpoint(p, "runtime.gcInstallStackBarrier")
		assertNoError(err, t, "setFunctionBreakpoint()")
		stackBarrierGoids := []int{}
		for len(stackBarrierGoids) == 0 {
2726
			err := proc.Continue(p)
2727
			if _, exited := err.(proc.ErrProcessExited); exited {
2728 2729 2730 2731
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
2732
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
Alessandro Arzilli 已提交
2733
			assertNoError(err, t, "GoroutinesInfo()")
2734
			for _, th := range p.ThreadList() {
2735
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
A
Alessandro Arzilli 已提交
2736 2737 2738
					continue
				}

2739
				goidVar := evalVariable(p, t, "gp.goid")
A
Alessandro Arzilli 已提交
2740 2741 2742
				goid, _ := constant.Int64Val(goidVar.Value)

				if g := getg(int(goid), gs); g != nil {
2743
					stack, err := g.Stacktrace(50, false)
A
Alessandro Arzilli 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
					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)

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

2763
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
Alessandro Arzilli 已提交
2764 2765 2766 2767 2768
		assertNoError(err, t, "GoroutinesInfo()")

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

2769
			stack, err := g.Stacktrace(200, false)
A
Alessandro Arzilli 已提交
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
			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
				}
2792
				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 已提交
2793 2794 2795
			}

			if !found {
2796
				t.Logf("Truncated stacktrace for %d\n", goid)
A
Alessandro Arzilli 已提交
2797 2798 2799 2800
			}
		}
	})
}
2801 2802

func TestAttachDetach(t *testing.T) {
2803 2804 2805 2806 2807 2808
	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
		}
2809
	}
2810 2811 2812
	if testBackend == "rr" {
		return
	}
2813 2814 2815 2816 2817
	var buildFlags protest.BuildFlags
	if buildMode == "pie" {
		buildFlags |= protest.BuildModePIE
	}
	fixture := protest.BuildFixture("testnextnethttp", buildFlags)
2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
	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 {
		conn, err := net.Dial("tcp", "localhost:9191")
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(50 * time.Millisecond)
		if time.Since(t0) > 10*time.Second {
			t.Fatal("fixture did not start")
		}
	}

2837
	var p proc.Process
2838 2839 2840 2841
	var err error

	switch testBackend {
	case "native":
2842
		p, err = native.Attach(cmd.Process.Pid, []string{})
2843 2844 2845 2846 2847
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
2848
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path, []string{})
2849 2850 2851 2852
	default:
		err = fmt.Errorf("unknown backend %q", testBackend)
	}

2853 2854 2855 2856 2857 2858
	assertNoError(err, t, "Attach")
	go func() {
		time.Sleep(1 * time.Second)
		http.Get("http://localhost:9191")
	}()

2859
	assertNoError(proc.Continue(p), t, "Continue")
2860
	assertLineNumber(p, t, 11, "Did not continue to correct location,")
2861 2862 2863 2864 2865 2866 2867

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

	resp, err := http.Get("http://localhost:9191/nobp")
	assertNoError(err, t, "Page request after detach")
	bs, err := ioutil.ReadAll(resp.Body)
	assertNoError(err, t, "Reading /nobp page")
2868
	if out := string(bs); !strings.Contains(out, "hello, world!") {
2869 2870 2871 2872 2873
		t.Fatalf("/nobp page does not contain \"hello, world!\": %q", out)
	}

	cmd.Process.Kill()
}
2874 2875

func TestVarSum(t *testing.T) {
2876
	protest.AllowRecording(t)
2877 2878
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2879
		sumvar := evalVariable(p, t, "s1[0] + s1[1]")
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
		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) {
2891
	protest.AllowRecording(t)
2892 2893
	withTestProcess("pkgrenames", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2894 2895
		evalVariable(p, t, "pkg.SomeVar")
		evalVariable(p, t, "pkg.SomeVar.X")
2896 2897
	})
}
2898 2899

func TestEnvironment(t *testing.T) {
2900
	protest.AllowRecording(t)
2901 2902 2903
	os.Setenv("SOMEVAR", "bah")
	withTestProcess("testenv", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2904
		v := evalVariable(p, t, "x")
2905 2906 2907 2908 2909 2910 2911
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != "bah" {
			t.Fatalf("value of v is %q (expected \"bah\")", vv)
		}
	})
}
2912 2913

func getFrameOff(p proc.Process, t *testing.T) int64 {
2914
	frameoffvar := evalVariable(p, t, "runtime.frameoff")
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
	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) {
		bp, err := setFunctionBreakpoint(p, "main.Increment")
		assertNoError(err, t, "setFunctionBreakpoint")
		assertNoError(proc.Continue(p), t, "Continue")
		_, err = p.ClearBreakpoint(bp.Addr)
		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?")
		}
2944
		assertLineNumber(p, t, 6, "program did not continue to expected location,")
2945
		assertNoError(proc.Next(p), t, "Next 4")
2946
		assertLineNumber(p, t, 7, "program did not continue to expected location,")
2947
		assertNoError(proc.StepOut(p), t, "StepOut")
2948
		assertLineNumber(p, t, 11, "program did not continue to expected location,")
2949 2950 2951 2952 2953 2954
		frameoff2 := getFrameOff(p, t)
		if frameoff0 != frameoff2 {
			t.Fatalf("frame offset mismatch %x != %x", frameoff0, frameoff2)
		}
	})
}
2955 2956 2957 2958 2959 2960 2961

// 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 已提交
2962 2963 2964 2965 2966
	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")
	}
2967 2968 2969 2970
	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()")
2971
		v := evalVariable(p, t, "dyldenv")
2972 2973 2974 2975 2976 2977 2978
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != envval {
			t.Fatalf("value of v is %q (expected %q)", vv, envval)
		}
	})
}
2979 2980 2981 2982

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
2983
	// error, (c) program runs to completion
2984 2985 2986 2987 2988 2989
	protest.AllowRecording(t)
	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		err := proc.Next(p)
		if err == nil {
			return
		}
2990
		if _, ok := err.(*frame.ErrNoFDEForPC); ok {
2991 2992
			return
		}
2993
		if _, ok := err.(proc.ErrThreadBlocked); ok {
2994
			return
2995
		}
2996
		if _, ok := err.(*proc.ErrNoSourceForPC); ok {
2997
			return
2998
		}
2999
		if _, ok := err.(proc.ErrProcessExited); ok {
3000 3001
			return
		}
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
		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")
	})
}
3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025

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 {
3026
				scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)
3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
			}
		} 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 已提交
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099

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")
		}
	})
}
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115

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
	}
3116 3117 3118
	if buildMode != "" {
		t.Skip("not enabled with buildmode=PIE")
	}
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143
	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 {
		conn, err := net.Dial("tcp", "localhost:9191")
		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":
3144
		p, err = native.Attach(cmd.Process.Pid, []string{})
3145 3146 3147 3148 3149
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
3150
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path, []string{})
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
	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)
}
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178

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) {
		setFileBreakpoint(p, t, fixture, 9)
		condbp := setFileBreakpoint(p, t, fixture, 10)
		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")
3179
		assertLineNumber(p, t, 10, "continued to wrong location,")
3180 3181
	})
}
A
aarzilli 已提交
3182

3183
func logStacktrace(t *testing.T, bi *proc.BinaryInfo, frames []proc.Stackframe) {
A
aarzilli 已提交
3184 3185 3186 3187 3188 3189 3190
	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)
3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
		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 已提交
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 3263 3264 3265 3266 3267 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 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
	}
}

// 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)
				}
			}

3318
			frames, err := g.Stacktrace(100, false)
A
aarzilli 已提交
3319 3320 3321
			assertNoError(err, t, fmt.Sprintf("Stacktrace at iteration step %d", itidx))

			t.Logf("iteration step %d", itidx)
3322
			logStacktrace(t, p.BinInfo(), frames)
A
aarzilli 已提交
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358

			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:")
3359
						logStacktrace(t, p.BinInfo(), threadFrames)
A
aarzilli 已提交
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
						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) {
		_, err := setFunctionBreakpoint(p, "runtime.startpanic_m")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "first continue")
		assertNoError(proc.Continue(p), t, "second continue")
		g, err := proc.GetG(p.CurrentThread())
		assertNoError(err, t, "GetG")
3406
		frames, err := g.Stacktrace(100, false)
A
aarzilli 已提交
3407
		assertNoError(err, t, "stacktrace")
3408
		logStacktrace(t, p.BinInfo(), frames)
3409
		m := stacktraceCheck(t, []string{"!runtime.startpanic_m", "runtime.gopanic", "main.main"}, frames)
3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
		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) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint(main.main)")
		assertNoError(proc.Continue(p), t, "first continue")
3426

3427 3428
		g, err := proc.GetG(p.CurrentThread())
		assertNoError(err, t, "GetG")
3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
		mainGoroutineID := g.ID

		_, err = setFunctionBreakpoint(p, "runtime.newstack")
		assertNoError(err, t, "setFunctionBreakpoint(runtime.newstack)")
		for {
			assertNoError(proc.Continue(p), t, "second continue")
			g, err = proc.GetG(p.CurrentThread())
			assertNoError(err, t, "GetG")
			if g.ID == mainGoroutineID {
				break
			}
		}
3441
		frames, err := g.Stacktrace(100, false)
3442
		assertNoError(err, t, "stacktrace")
3443
		logStacktrace(t, p.BinInfo(), frames)
3444
		m := stacktraceCheck(t, []string{"!runtime.newstack", "main.main"}, frames)
A
aarzilli 已提交
3445 3446 3447 3448 3449
		if m == nil {
			t.Fatal("see previous loglines")
		}
	})
}
3450 3451 3452 3453 3454 3455 3456 3457

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) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
3458
		frames, err := p.SelectedGoroutine().Stacktrace(10, false)
3459
		assertNoError(err, t, "Stacktrace")
3460
		scope := proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frames[2:]...)
3461 3462 3463 3464 3465 3466 3467
		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))
		}
	})
}
3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486

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) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
		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)
		}
	})
}
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514

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))
		}
	})
}
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524

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")
	})
}
3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554

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) {
		_, err := setFunctionBreakpoint(p, "main.f")
		assertNoError(err, t, "setFunctionBreakpoint()")
		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)
		}
3555
		if pexit, exited := exitErr.(proc.ErrProcessExited); exited {
3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
			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)
		}
	})
}
3567 3568

func TestIssue1145(t *testing.T) {
3569 3570
	withTestProcess("sleep", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 18)
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
		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")
		}
	})
}
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603

func TestDisassembleGlobalVars(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		mainfn := p.BinInfo().LookupFunc["main.main"]
		text, err := proc.Disassemble(p, nil, mainfn.Entry, mainfn.End)
		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 已提交
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 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 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 3675

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
}

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 {
			t.Fatalf("expected at least two locations for %s:%d (got %d: %#x)", fixture.Source, 6, len(pcs), pcs)
		}
		for _, pc := range pcs {
3676
			t.Logf("setting breakpoint at %#x\n", pc)
A
aarzilli 已提交
3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
			_, 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 {
3687
			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 已提交
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
		}

		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 {
3714
			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 已提交
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 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
		}

		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},
	})
}
3791

3792 3793 3794 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 3826 3827 3828 3829 3830 3831 3832 3833
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)
		}
	})
}

3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
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)
		}
	})
}
3865

3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881
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) {
		_, err := setFunctionBreakpoint(p, "C.fortytwo")
		assertNoError(err, t, "setFunctionBreakpoint()")
		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")
		}
	})
}
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906

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)
		}
	})
}
3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922

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) {
		_, err := setFunctionBreakpoint(p, "main.stepout")
		assertNoError(err, t, "SetBreakpoint")
		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)
		}

3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940
		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)
3941
		}
3942 3943
		if ret[stridx].Kind != reflect.String {
			t.Fatalf("(str) bad return value kind %v", ret[stridx].Kind)
3944
		}
3945
		if s := constant.StringVal(ret[stridx].Value); s != "return 47" {
3946 3947 3948
			t.Fatalf("(str) bad return value %q", s)
		}

3949 3950
		if ret[numidx].Name != "num" {
			t.Fatalf("(num) bad return value name %s", ret[numidx].Name)
3951
		}
3952 3953
		if ret[numidx].Kind != reflect.Int {
			t.Fatalf("(num) bad return value kind %v", ret[numidx].Kind)
3954
		}
3955
		if n, _ := constant.Int64Val(ret[numidx].Value); n != 48 {
3956 3957 3958 3959
			t.Fatalf("(num) bad return value %d", n)
		}
	})
}
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977

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")
			}
		})
	}
}
3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988

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) {
		bp := setFileBreakpoint(p, t, fixture, 8)
		bp.Cond = &ast.Ident{Name: "equalsTwo"}
		assertNoError(proc.Continue(p), t, "Continue()")
		assertLineNumber(p, t, 8, "after continue")
	})
}
3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 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

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 已提交
4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059

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) {
		_, err := setFunctionBreakpoint(p, "main.asmFunc")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
	})
}
4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102

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)
			}
		}
	})
}
4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119

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) {
		setFileBreakpoint(p, t, fixture, 7)
		assertNoError(proc.Continue(p), t, "First Continue")
		assertLineNumber(p, t, 7, "Did not continue to correct location (first continue),")
		assertNoError(proc.CallFunction(p, "getNum()", &normalLoadConfig, true), t, "Call")
		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)
		}
	})
}
4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137

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 已提交
4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166

func TestGoroutinesInfoLimit(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 37)
		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))
		}
	})
}
4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198

func TestIssue1469(t *testing.T) {
	withTestProcess("issue1469", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 13)
		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)
					}
				}
			}
		}
	})
}
4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216

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)
		}
	})
}
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253

func TestListImages(t *testing.T) {
	pluginFixtures := protest.WithPlugins(t, "plugin1/", "plugin2/")

	withTestProcessArgs("plugintest", t, ".", []string{pluginFixtures[0].Path, pluginFixtures[1].Path}, 0, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "first continue")
		plugin1Found := false
		t.Logf("Libraries before:")
		for _, image := range p.BinInfo().Images {
			t.Logf("\t%#v", image)
			if image.Path == pluginFixtures[0].Path {
				plugin1Found = true
			}
		}
		if !plugin1Found {
			t.Fatalf("Could not find plugin1")
		}
		assertNoError(proc.Continue(p), t, "second continue")
		plugin1Found, plugin2Found := false, false
		t.Logf("Libraries after:")
		for _, image := range p.BinInfo().Images {
			t.Logf("\t%#v", image)
			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")
		}
	})
}
4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288

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) {
		_, err := setFunctionBreakpoint(p, "main.testgoroutine")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
		as, err := p.SelectedGoroutine().Ancestors(1000)
		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")
		}
	})
}
4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308

func testCallConcurrentCheckReturns(p proc.Process, t *testing.T, gid1 int) bool {
	for _, thread := range p.ThreadList() {
		g, _ := proc.GetG(thread)
		if g == nil || g.ID != gid1 {
			continue
		}
		retvals := thread.Common().ReturnValues(normalLoadConfig)
		if len(retvals) != 0 {
			return true
		}
	}
	return false
}

func TestCallConcurrent(t *testing.T) {
	protest.MustSupportFunctionCalls(t, testBackend)
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		bp := setFileBreakpoint(p, t, fixture, 24)
		assertNoError(proc.Continue(p), t, "Continue()")
4309 4310
		_, err := p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint() returned an error")
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334

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

		returned := testCallConcurrentCheckReturns(p, t, gid1)

		curthread := p.CurrentThread()
		if curbp := curthread.Breakpoint(); curbp.Breakpoint == nil || curbp.ID != bp.ID || returned {
			return
		}

		for {
			returned = testCallConcurrentCheckReturns(p, t, gid1)
			if returned {
				break
			}
			t.Logf("Continuing... %v", returned)
			assertNoError(proc.Continue(p), t, "Continue()")
		}

		proc.Continue(p)
	})
}