proc_test.go 97.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
	"github.com/derekparker/delve/pkg/dwarf/frame"
23
	"github.com/derekparker/delve/pkg/goversion"
24 25 26
	"github.com/derekparker/delve/pkg/proc"
	"github.com/derekparker/delve/pkg/proc/gdbserial"
	"github.com/derekparker/delve/pkg/proc/native"
D
Derek Parker 已提交
27
	protest "github.com/derekparker/delve/pkg/proc/test"
D
Derek Parker 已提交
28
)
29

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

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

D
Dan Mace 已提交
38
func TestMain(m *testing.M) {
39 40 41 42 43 44 45 46
	flag.StringVar(&testBackend, "backend", "", "selects backend")
	flag.Parse()
	if testBackend == "" {
		testBackend = os.Getenv("PROCTEST")
		if testBackend == "" {
			testBackend = "native"
		}
	}
D
Derek Parker 已提交
47
	os.Exit(protest.RunTestsWithFixtures(m))
D
Dan Mace 已提交
48 49
}

50
func withTestProcess(name string, t testing.TB, fn func(p proc.Process, fixture protest.Fixture)) {
51
	withTestProcessArgs(name, t, ".", []string{}, fn)
52 53
}

54
func withTestProcessArgs(name string, t testing.TB, wd string, args []string, fn func(p proc.Process, fixture protest.Fixture)) {
55
	fixture := protest.BuildFixture(name, 0)
56
	var p proc.Process
57
	var err error
58
	var tracedir string
59 60 61

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

	defer func() {
		p.Halt()
79
		p.Detach(true)
80 81 82
		if tracedir != "" {
			protest.SafeRemoveAll(tracedir)
		}
83 84 85 86 87
	}()

	fn(p, fixture)
}

88
func getRegisters(p proc.Process, t *testing.T) proc.Registers {
89
	regs, err := p.CurrentThread().Registers(false)
90 91 92 93 94 95 96
	if err != nil {
		t.Fatal("Registers():", err)
	}

	return regs
}

97
func dataAtAddr(thread proc.MemoryReadWriter, addr uint64) ([]byte, error) {
98 99 100
	data := make([]byte, 1)
	_, err := thread.ReadMemory(data, uintptr(addr))
	return data, err
101 102
}

103
func assertNoError(err error, t testing.TB, s string) {
104
	if err != nil {
105 106
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
107
		t.Fatalf("failed assertion at %s:%d: %s - %s\n", fname, line, s, err)
108 109 110
	}
}

111
func currentPC(p proc.Process, t *testing.T) uint64 {
112
	regs, err := p.CurrentThread().Registers(false)
113 114 115 116
	if err != nil {
		t.Fatal(err)
	}

117
	return regs.PC()
118 119
}

120
func currentLineNumber(p proc.Process, t *testing.T) (string, int) {
121
	pc := currentPC(p, t)
122
	f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
123
	return f, l
124 125
}

126
func TestExit(t *testing.T) {
127
	protest.AllowRecording(t)
128
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
129 130
		err := proc.Continue(p)
		pe, ok := err.(proc.ProcessExitedError)
131
		if !ok {
132
			t.Fatalf("Continue() returned unexpected error type %s", err)
133 134 135 136
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
137
		if pe.Pid != p.Pid() {
138 139 140 141 142
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

143
func TestExitAfterContinue(t *testing.T) {
144
	protest.AllowRecording(t)
145
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
146 147
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "setFunctionBreakpoint()")
148 149 150
		assertNoError(proc.Continue(p), t, "First Continue()")
		err = proc.Continue(p)
		pe, ok := err.(proc.ProcessExitedError)
151
		if !ok {
L
Luke Hoban 已提交
152
			t.Fatalf("Continue() returned unexpected error type %s", pe)
153 154 155 156
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
157
		if pe.Pid != p.Pid() {
158 159 160 161 162
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

163
func setFunctionBreakpoint(p proc.Process, fname string) (*proc.Breakpoint, error) {
164
	addr, err := proc.FindFunctionLocation(p, fname, true, 0)
165 166 167
	if err != nil {
		return nil, err
	}
168
	return p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
169 170
}

171
func setFileBreakpoint(p proc.Process, t *testing.T, fixture protest.Fixture, lineno int) *proc.Breakpoint {
172
	addr, err := proc.FindFileLocation(p, fixture.Source, lineno)
A
aarzilli 已提交
173 174 175
	if err != nil {
		t.Fatalf("FindFileLocation: %v", err)
	}
176
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
A
aarzilli 已提交
177 178 179 180 181 182
	if err != nil {
		t.Fatalf("SetBreakpoint: %v", err)
	}
	return bp
}

D
Derek Parker 已提交
183
func TestHalt(t *testing.T) {
184
	stopChan := make(chan interface{}, 1)
185
	withTestProcess("loopprog", t, func(p proc.Process, fixture protest.Fixture) {
186
		_, err := setFunctionBreakpoint(p, "main.loop")
187
		assertNoError(err, t, "SetBreakpoint")
188 189 190
		assertNoError(proc.Continue(p), t, "Continue")
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
191 192
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
193 194
			}
		}
195
		resumeChan := make(chan struct{}, 1)
D
Derek Parker 已提交
196
		go func() {
A
aarzilli 已提交
197 198
			<-resumeChan
			time.Sleep(100 * time.Millisecond)
199
			stopChan <- p.RequestManualStop()
D
Derek Parker 已提交
200
		}()
A
aarzilli 已提交
201
		p.ResumeNotify(resumeChan)
202
		assertNoError(proc.Continue(p), t, "Continue")
203 204 205 206 207 208
		retVal := <-stopChan

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

D
Derek Parker 已提交
209 210 211
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
212 213 214 215 216 217
		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")
					}
218 219 220
				}
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
D
Derek Parker 已提交
221 222 223 224 225
			}
		}
	})
}

226
func TestStep(t *testing.T) {
227
	protest.AllowRecording(t)
228
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
229
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", false, 0)
230
		assertNoError(err, t, "FindFunctionLocation")
231

232
		_, err = p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
233
		assertNoError(err, t, "SetBreakpoint()")
234
		assertNoError(proc.Continue(p), t, "Continue()")
235

236
		regs := getRegisters(p, t)
237
		rip := regs.PC()
238

239
		err = p.CurrentThread().StepInstruction()
D
Derek Parker 已提交
240
		assertNoError(err, t, "Step()")
241

242
		regs = getRegisters(p, t)
243 244 245 246 247
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
248

D
Derek Parker 已提交
249
func TestBreakpoint(t *testing.T) {
250
	protest.AllowRecording(t)
251
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
252
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", false, 0)
253
		assertNoError(err, t, "FindFunctionLocation")
254

255
		bp, err := p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
256
		assertNoError(err, t, "SetBreakpoint()")
257
		assertNoError(proc.Continue(p), t, "Continue()")
258

259 260 261
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
262

263 264 265 266
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
267
		if pc-1 != bp.Addr && pc != bp.Addr {
268
			f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
269
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
270 271
		}
	})
272
}
273

D
Derek Parker 已提交
274
func TestBreakpointInSeperateGoRoutine(t *testing.T) {
275
	protest.AllowRecording(t)
276
	withTestProcess("testthreads", t, func(p proc.Process, fixture protest.Fixture) {
277
		fnentry, err := proc.FindFunctionLocation(p, "main.anotherthread", false, 0)
278
		assertNoError(err, t, "FindFunctionLocation")
279

280
		_, err = p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
281
		assertNoError(err, t, "SetBreakpoint")
282

283
		assertNoError(proc.Continue(p), t, "Continue")
284

285 286 287
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
288

289
		f, l, _ := p.BinInfo().PCToLine(pc)
290 291 292 293 294 295
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
296
func TestBreakpointWithNonExistantFunction(t *testing.T) {
297
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
298
		_, err := p.SetBreakpoint(0, proc.UserBreakpoint, nil)
299 300 301 302
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
303
}
304

305
func TestClearBreakpointBreakpoint(t *testing.T) {
306
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
307
		fnentry, err := proc.FindFunctionLocation(p, "main.sleepytime", false, 0)
308
		assertNoError(err, t, "FindFunctionLocation")
309
		bp, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
310
		assertNoError(err, t, "SetBreakpoint()")
311

312
		bp, err = p.ClearBreakpoint(fnentry)
313
		assertNoError(err, t, "ClearBreakpoint()")
314

315 316
		data, err := dataAtAddr(p.CurrentThread(), bp.Addr)
		assertNoError(err, t, "dataAtAddr")
317

318
		int3 := []byte{0xcc}
319 320 321 322
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

323
		if countBreakpoints(p) != 0 {
324 325 326
			t.Fatal("Breakpoint not removed internally")
		}
	})
327
}
328

329 330 331
type nextTest struct {
	begin, end int
}
332

333
func countBreakpoints(p proc.Process) int {
334
	bpcount := 0
A
aarzilli 已提交
335
	for _, bp := range p.Breakpoints().M {
336 337 338 339 340 341 342
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

A
aarzilli 已提交
343 344 345 346 347 348 349 350
type contFunc int

const (
	contNext contFunc = iota
	contStep
)

func testseq(program string, contFunc contFunc, testcases []nextTest, initialLocation string, t *testing.T) {
351
	protest.AllowRecording(t)
352
	withTestProcess(program, t, func(p proc.Process, fixture protest.Fixture) {
353
		var bp *proc.Breakpoint
A
aarzilli 已提交
354 355 356 357 358
		var err error
		if initialLocation != "" {
			bp, err = setFunctionBreakpoint(p, initialLocation)
		} else {
			var pc uint64
359
			pc, err = proc.FindFileLocation(p, fixture.Source, testcases[0].begin)
A
aarzilli 已提交
360
			assertNoError(err, t, "FindFileLocation()")
361
			bp, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
362
		}
363
		assertNoError(err, t, "SetBreakpoint()")
364
		assertNoError(proc.Continue(p), t, "Continue()")
365
		p.ClearBreakpoint(bp.Addr)
366 367
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
368 369 370
		if testBackend != "rr" {
			assertNoError(regs.SetPC(p.CurrentThread(), bp.Addr), t, "SetPC")
		}
371

D
Derek Parker 已提交
372
		f, ln := currentLineNumber(p, t)
373
		for _, tc := range testcases {
374 375
			regs, _ := p.CurrentThread().Registers(false)
			pc := regs.PC()
376
			if ln != tc.begin {
D
Derek Parker 已提交
377
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
378 379
			}

A
aarzilli 已提交
380 381
			switch contFunc {
			case contNext:
382
				assertNoError(proc.Next(p), t, "Next() returned an error")
A
aarzilli 已提交
383
			case contStep:
384
				assertNoError(proc.Step(p), t, "Step() returned an error")
A
aarzilli 已提交
385
			}
386

D
Derek Parker 已提交
387
			f, ln = currentLineNumber(p, t)
388 389
			regs, _ = p.CurrentThread().Registers(false)
			pc = regs.PC()
390
			if ln != tc.end {
A
aarzilli 已提交
391
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d (%#x)", tc.end, filepath.Base(f), ln, pc)
392 393
			}
		}
394

395
		if countBreakpoints(p) != 0 {
A
aarzilli 已提交
396
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints().M))
397
		}
398 399
	})
}
400

401
func TestNextGeneral(t *testing.T) {
402 403
	var testcases []nextTest

404
	ver, _ := goversion.Parse(runtime.Version())
405

406
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
		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},
		}
443
	}
444

A
aarzilli 已提交
445
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
446 447
}

448 449
func TestNextConcurrent(t *testing.T) {
	testcases := []nextTest{
450
		{8, 9},
451 452 453
		{9, 10},
		{10, 11},
	}
454
	protest.AllowRecording(t)
455
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
456
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
457
		assertNoError(err, t, "SetBreakpoint")
458
		assertNoError(proc.Continue(p), t, "Continue")
459
		f, ln := currentLineNumber(p, t)
460
		initV, err := evalVariable(p, "n")
461
		initVval, _ := constant.Int64Val(initV.Value)
462
		assertNoError(err, t, "EvalVariable")
463 464
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")
465
		for _, tc := range testcases {
466
			g, err := proc.GetG(p.CurrentThread())
467
			assertNoError(err, t, "GetG()")
468 469
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
470
			}
471 472 473
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
474
			assertNoError(proc.Next(p), t, "Next() returned an error")
475 476 477 478
			f, ln = currentLineNumber(p, t)
			if ln != tc.end {
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d", tc.end, filepath.Base(f), ln)
			}
479
			v, err := evalVariable(p, "n")
480
			assertNoError(err, t, "EvalVariable")
481 482
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
483 484 485 486 487 488
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

489 490 491
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{
492
		{8, 9},
493 494 495
		{9, 10},
		{10, 11},
	}
496
	protest.AllowRecording(t)
497
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
498 499
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint")
500
		assertNoError(proc.Continue(p), t, "Continue")
501 502 503 504 505
		f, ln := currentLineNumber(p, t)
		initV, err := evalVariable(p, "n")
		initVval, _ := constant.Int64Val(initV.Value)
		assertNoError(err, t, "EvalVariable")
		for _, tc := range testcases {
506
			t.Logf("test case %v", tc)
507
			g, err := proc.GetG(p.CurrentThread())
508
			assertNoError(err, t, "GetG()")
509 510
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
511 512 513 514
			}
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
515
			assertNoError(proc.Next(p), t, "Next() returned an error")
516 517 518
			var vval int64
			for {
				v, err := evalVariable(p, "n")
519 520 521
				for _, thread := range p.ThreadList() {
					proc.GetG(thread)
				}
522 523
				assertNoError(err, t, "EvalVariable")
				vval, _ = constant.Int64Val(v.Value)
524
				if bpstate := p.CurrentThread().Breakpoint(); bpstate.Breakpoint == nil {
525 526 527 528 529 530 531 532
					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")
					}
533
					assertNoError(proc.Continue(p), t, "Continue 2")
534 535 536 537 538 539 540 541 542 543
				}
			}
			f, ln = currentLineNumber(p, t)
			if ln != tc.end {
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d", tc.end, filepath.Base(f), ln)
			}
		}
	})
}

544 545
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
546
		{13, 14},
D
Derek Parker 已提交
547 548
		{14, 15},
		{15, 35},
549
	}
550
	protest.AllowRecording(t)
A
aarzilli 已提交
551
	testseq("testnextprog", contNext, testcases, "main.helloworld", t)
552 553 554
}

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

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

559
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
560 561 562 563 564 565 566 567 568 569 570
		testcases = []nextTest{
			{5, 6},
			{6, 9},
			{9, 10},
		}
	} else {
		testcases = []nextTest{
			{5, 8},
			{8, 9},
			{9, 10},
		}
571
	}
572
	protest.AllowRecording(t)
A
aarzilli 已提交
573
	testseq("testnextdefer", contNext, testcases, "main.main", t)
574 575
}

D
Derek Parker 已提交
576 577 578 579 580
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
581
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
582 583 584
		go func() {
			// Wait for program to start listening.
			for {
L
Luke Hoban 已提交
585
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
586 587 588 589 590 591
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
592
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
593
		}()
594
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
595 596 597 598 599 600 601 602
			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)
			}

603
			assertNoError(proc.Next(p), t, "Next() returned an error")
D
Derek Parker 已提交
604 605 606 607 608 609 610 611 612

			f, ln = currentLineNumber(p, t)
			if ln != tc.end {
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d", tc.end, filepath.Base(f), ln)
			}
		}
	})
}

D
Derek Parker 已提交
613
func TestRuntimeBreakpoint(t *testing.T) {
614
	withTestProcess("testruntimebreakpoint", t, func(p proc.Process, fixture protest.Fixture) {
615
		err := proc.Continue(p)
D
Derek Parker 已提交
616 617 618
		if err != nil {
			t.Fatal(err)
		}
619 620 621
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
622
		f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
623
		if l != 10 {
624
			t.Fatalf("did not respect breakpoint %s:%d", f, l)
D
Derek Parker 已提交
625 626 627 628
		}
	})
}

629
func returnAddress(thread proc.Thread) (uint64, error) {
630
	locations, err := proc.ThreadStacktrace(thread, 2)
631 632 633 634
	if err != nil {
		return 0, err
	}
	if len(locations) < 2 {
635
		return 0, proc.NoReturnAddr{locations[0].Current.Fn.BaseName()}
636 637 638 639
	}
	return locations[1].Current.PC, nil
}

640
func TestFindReturnAddress(t *testing.T) {
641
	protest.AllowRecording(t)
642
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
643
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 24)
644 645 646
		if err != nil {
			t.Fatal(err)
		}
647
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
648 649 650
		if err != nil {
			t.Fatal(err)
		}
651
		err = proc.Continue(p)
652 653 654
		if err != nil {
			t.Fatal(err)
		}
655
		addr, err := returnAddress(p.CurrentThread())
656 657 658
		if err != nil {
			t.Fatal(err)
		}
659
		_, l, _ := p.BinInfo().PCToLine(addr)
660 661
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
662
		}
663 664
	})
}
665

666
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
667
	protest.AllowRecording(t)
668
	withTestProcess("testreturnaddress", t, func(p proc.Process, fixture protest.Fixture) {
669
		fnName := "runtime.rt0_go"
670
		fnentry, err := proc.FindFunctionLocation(p, fnName, false, 0)
671
		assertNoError(err, t, "FindFunctionLocation")
672
		if _, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil); err != nil {
673 674
			t.Fatal(err)
		}
675
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
676 677
			t.Fatal(err)
		}
678
		if _, err := returnAddress(p.CurrentThread()); err == nil {
679
			t.Fatal("expected error to be returned")
680 681 682
		}
	})
}
D
Derek Parker 已提交
683 684

func TestSwitchThread(t *testing.T) {
685
	protest.AllowRecording(t)
686
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
687 688 689 690 691
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
692
		pc, err := proc.FindFunctionLocation(p, "main.main", true, 0)
D
Derek Parker 已提交
693 694 695
		if err != nil {
			t.Fatal(err)
		}
696
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
D
Derek Parker 已提交
697 698 699
		if err != nil {
			t.Fatal(err)
		}
700
		err = proc.Continue(p)
D
Derek Parker 已提交
701 702 703 704
		if err != nil {
			t.Fatal(err)
		}
		var nt int
705 706 707 708
		ct := p.CurrentThread().ThreadID()
		for _, thread := range p.ThreadList() {
			if thread.ThreadID() != ct {
				nt = thread.ThreadID()
D
Derek Parker 已提交
709 710 711 712 713 714 715 716 717 718 719
				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)
		}
720
		if p.CurrentThread().ThreadID() != nt {
D
Derek Parker 已提交
721 722 723 724
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
725

726 727 728 729 730 731
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 已提交
732 733 734
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
735

736
	protest.AllowRecording(t)
737
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
738
		pc, err := proc.FindFunctionLocation(p, "main.main", true, 0)
739 740 741
		if err != nil {
			t.Fatal(err)
		}
742
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
743 744 745
		if err != nil {
			t.Fatal(err)
		}
746
		err = proc.Continue(p)
747 748 749
		if err != nil {
			t.Fatal(err)
		}
750
		err = proc.Next(p)
751 752 753 754 755 756
		if err != nil {
			t.Fatal(err)
		}
	})
}

A
aarzilli 已提交
757 758 759 760 761
type loc struct {
	line int
	fn   string
}

762
func (l1 *loc) match(l2 proc.Stackframe) bool {
A
aarzilli 已提交
763
	if l1.line >= 0 {
764
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
765 766 767
			return false
		}
	}
768
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
769 770 771 772
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
773 774
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
775
	}
776
	protest.AllowRecording(t)
777
	withTestProcess("stacktraceprog", t, func(p proc.Process, fixture protest.Fixture) {
778
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
779 780 781
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
782 783
			assertNoError(proc.Continue(p), t, "Continue()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
A
aarzilli 已提交
784 785 786 787 788 789
			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)
			}

790 791 792 793
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
794

A
aarzilli 已提交
795 796 797 798 799 800 801
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

802
		p.ClearBreakpoint(bp.Addr)
803
		proc.Continue(p)
A
aarzilli 已提交
804 805 806
	})
}

807
func TestStacktrace2(t *testing.T) {
808
	withTestProcess("retstack", t, func(p proc.Process, fixture protest.Fixture) {
809
		assertNoError(proc.Continue(p), t, "Continue()")
810

811
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
812
		assertNoError(err, t, "Stacktrace()")
813
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
814 815 816
			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 已提交
817
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
818 819
		}

820 821
		assertNoError(proc.Continue(p), t, "Continue()")
		locations, err = proc.ThreadStacktrace(p.CurrentThread(), 40)
822
		assertNoError(err, t, "Stacktrace()")
823
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
824 825 826
			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 已提交
827
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
828 829 830 831 832
		}
	})

}

833
func stackMatch(stack []loc, locations []proc.Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
834 835 836
	if len(stack) > len(locations) {
		return false
	}
837 838 839 840 841 842 843 844 845 846 847
	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 已提交
848 849
			return false
		}
850
		i++
A
aarzilli 已提交
851
	}
852
	return i >= len(stack)
A
aarzilli 已提交
853 854 855
}

func TestStacktraceGoroutine(t *testing.T) {
856
	mainStack := []loc{{13, "main.stacktraceme"}, {26, "main.main"}}
857 858 859 860 861
	agoroutineStacks := [][]loc{
		{{8, "main.agoroutine"}},
		{{9, "main.agoroutine"}},
		{{10, "main.agoroutine"}},
	}
A
aarzilli 已提交
862

863
	protest.AllowRecording(t)
864
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
865
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
866 867
		assertNoError(err, t, "BreakByLocation()")

868
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
869

870
		gs, err := proc.GoroutinesInfo(p)
A
aarzilli 已提交
871 872 873 874 875
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
876
		for i, g := range gs {
A
aarzilli 已提交
877
			locations, err := g.Stacktrace(40)
878 879
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
880
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
881 882
				continue
			}
A
aarzilli 已提交
883

884
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
885 886 887
				mainCount++
			}

888 889 890 891 892 893 894 895
			found := false
			for _, agoroutineStack := range agoroutineStacks {
				if stackMatch(agoroutineStack, locations, true) {
					found = true
				}
			}

			if found {
A
aarzilli 已提交
896 897
				agoroutineCount++
			} else {
D
Derek Parker 已提交
898
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
899 900
				for i := range locations {
					name := ""
901 902
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
903
					}
904
					t.Logf("\t%s:%d %s (%#x)\n", locations[i].Call.File, locations[i].Call.Line, name, locations[i].Current.PC)
A
aarzilli 已提交
905 906 907 908 909
				}
			}
		}

		if mainCount != 1 {
910
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
911 912 913 914 915 916
		}

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

917
		p.ClearBreakpoint(bp.Addr)
918
		proc.Continue(p)
A
aarzilli 已提交
919 920
	})
}
921 922

func TestKill(t *testing.T) {
923 924 925 926
	if testBackend == "lldb" {
		// k command presumably works but leaves the process around?
		return
	}
927
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
928 929 930
		if err := p.Kill(); err != nil {
			t.Fatal(err)
		}
931
		if !p.Exited() {
932 933 934
			t.Fatal("expected process to have exited")
		}
		if runtime.GOOS == "linux" {
935
			_, err := os.Open(fmt.Sprintf("/proc/%d/", p.Pid()))
936
			if err == nil {
937
				t.Fatal("process has not exited", p.Pid())
938 939 940
			}
		}
	})
941 942 943 944
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
		if err := p.Detach(true); err != nil {
			t.Fatal(err)
		}
945
		if !p.Exited() {
946 947 948 949 950 951 952 953 954
			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())
			}
		}
	})
955
}
956

957
func testGSupportFunc(name string, t *testing.T, p proc.Process, fixture protest.Fixture) {
958
	bp, err := setFunctionBreakpoint(p, "main.main")
959 960
	assertNoError(err, t, name+": BreakByLocation()")

961
	assertNoError(proc.Continue(p), t, name+": Continue()")
962

963
	g, err := proc.GetG(p.CurrentThread())
964 965 966 967 968 969 970 971 972 973 974 975
	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) {
976
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
977 978 979
		testGSupportFunc("nocgo", t, p, fixture)
	})

980 981 982 983
	// 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 已提交
984 985 986
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
987

988
	protest.AllowRecording(t)
989
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
990 991 992
		testGSupportFunc("cgo", t, p, fixture)
	})
}
993 994

func TestContinueMulti(t *testing.T) {
995
	protest.AllowRecording(t)
996
	withTestProcess("integrationprog", t, func(p proc.Process, fixture protest.Fixture) {
997
		bp1, err := setFunctionBreakpoint(p, "main.main")
998 999
		assertNoError(err, t, "BreakByLocation()")

1000
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
1001 1002 1003 1004 1005
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
1006
			err := proc.Continue(p)
1007
			if p.Exited() {
1008 1009 1010 1011
				break
			}
			assertNoError(err, t, "Continue()")

1012
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp1.ID {
1013 1014 1015
				mainCount++
			}

1016
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp2.ID {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
				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)
		}
	})
}
1030

1031
func TestBreakpointOnFunctionEntry(t *testing.T) {
1032
	protest.AllowRecording(t)
1033
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
1034
		addr, err := proc.FindFunctionLocation(p, "main.main", false, 0)
1035
		assertNoError(err, t, "FindFunctionLocation()")
1036
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1037
		assertNoError(err, t, "SetBreakpoint()")
1038
		assertNoError(proc.Continue(p), t, "Continue()")
1039 1040 1041 1042 1043 1044
		_, ln := currentLineNumber(p, t)
		if ln != 17 {
			t.Fatalf("Wrong line number: %d (expected: 17)\n", ln)
		}
	})
}
1045 1046

func TestProcessReceivesSIGCHLD(t *testing.T) {
1047
	protest.AllowRecording(t)
1048
	withTestProcess("sigchldprog", t, func(p proc.Process, fixture protest.Fixture) {
1049 1050
		err := proc.Continue(p)
		_, ok := err.(proc.ProcessExitedError)
1051
		if !ok {
1052
			t.Fatalf("Continue() returned unexpected error type %v", err)
1053 1054 1055
		}
	})
}
1056 1057

func TestIssue239(t *testing.T) {
1058
	withTestProcess("is sue239", t, func(p proc.Process, fixture protest.Fixture) {
1059
		pos, _, err := p.BinInfo().LineToPC(fixture.Source, 17)
1060
		assertNoError(err, t, "LineToPC()")
1061
		_, err = p.SetBreakpoint(pos, proc.UserBreakpoint, nil)
1062
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
1063
		assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue()"))
1064 1065
	})
}
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
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")
}

1081
func evalVariable(p proc.Process, symbol string) (*proc.Variable, error) {
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
	var scope *proc.EvalScope
	var err error

	if testBackend == "rr" {
		var frame proc.Stackframe
		frame, err = findFirstNonRuntimeFrame(p)
		if err == nil {
			scope = proc.FrameToScope(p, frame)
		}
	} else {
		scope, err = proc.GoroutineScope(p.CurrentThread())
	}
1094

1095 1096 1097
	if err != nil {
		return nil, err
	}
1098
	return scope.EvalVariable(symbol, normalLoadConfig)
1099 1100
}

1101
func setVariable(p proc.Process, symbol, value string) error {
1102
	scope, err := proc.GoroutineScope(p.CurrentThread())
1103 1104 1105 1106 1107 1108 1109
	if err != nil {
		return err
	}
	return scope.SetVariable(symbol, value)
}

func TestVariableEvaluation(t *testing.T) {
1110
	protest.AllowRecording(t)
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
	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 已提交
1133 1134
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
		{"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},
	}

1146
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1147
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

		for _, tc := range testcases {
			v, err := evalVariable(p, tc.name)
			assertNoError(err, t, fmt.Sprintf("EvalVariable(%s)", tc.name))

			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 {
1159 1160 1161
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1162 1163 1164
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1165 1166
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1167 1168 1169
					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 已提交
1170 1171 1172 1173 1174 1175
				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)
					}
1176 1177
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
						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) {
1196
	protest.AllowRecording(t)
1197
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
1198 1199
		_, err := setFunctionBreakpoint(p, "main.stacktraceme")
		assertNoError(err, t, "setFunctionBreakpoint")
1200
		assertNoError(proc.Continue(p), t, "Continue()")
1201

1202
		// Testing evaluation on goroutines
1203
		gs, err := proc.GoroutinesInfo(p)
1204 1205 1206 1207
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
A
aarzilli 已提交
1208
			frames, err := g.Stacktrace(10)
1209 1210 1211 1212
			if err != nil {
				t.Logf("could not stacktrace goroutine %d: %v\n", g.ID, err)
				continue
			}
1213 1214 1215 1216 1217 1218 1219 1220
			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 已提交
1221
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1222 1223 1224
				continue
			}

1225
			scope, err := proc.ConvertEvalScope(p, g.ID, frame)
1226 1227
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
1228
			v, err := scope.EvalVariable("i", normalLoadConfig)
1229 1230
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1231
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1232 1233
				continue
			}
1234 1235
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1236 1237 1238 1239 1240 1241 1242 1243
		}

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

1244
		// Testing evaluation on frames
1245 1246
		assertNoError(proc.Continue(p), t, "Continue() 2")
		g, err := proc.GetG(p.CurrentThread())
1247 1248 1249
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
1250
			scope, err := proc.ConvertEvalScope(p, g.ID, i+1)
1251
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
1252
			v, err := scope.EvalVariable("n", normalLoadConfig)
1253
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1254
			n, _ := constant.Int64Val(v.Value)
1255 1256 1257 1258 1259 1260 1261 1262 1263
			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) {
1264
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1265
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1266 1267 1268 1269

		pval := func(n int64) {
			variable, err := evalVariable(p, "p1")
			assertNoError(err, t, "EvalVariable()")
1270 1271 1272
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1273 1274 1275 1276 1277 1278
			}
		}

		pval(1)

		// change p1 to point to i2
1279
		scope, err := proc.GoroutineScope(p.CurrentThread())
1280
		assertNoError(err, t, "Scope()")
1281
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1282 1283
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1284 1285 1286 1287 1288 1289 1290 1291 1292
		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) {
1293
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1294
		err := proc.Continue(p)
1295 1296 1297 1298 1299 1300 1301 1302 1303
		assertNoError(err, t, "Continue() returned an error")

		_, err = evalVariable(p, "a1")
		assertNoError(err, t, "Unable to find variable a1")

		_, err = evalVariable(p, "a2")
		assertNoError(err, t, "Unable to find variable a1")

		// Move scopes, a1 exists here by a2 does not
1304
		err = proc.Continue(p)
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
		assertNoError(err, t, "Continue() returned an error")

		_, err = evalVariable(p, "a1")
		assertNoError(err, t, "Unable to find variable a1")

		_, err = evalVariable(p, "a2")
		if err == nil {
			t.Fatalf("Can eval out of scope variable a2")
		}
	})
}

func TestRecursiveStructure(t *testing.T) {
1318
	protest.AllowRecording(t)
1319
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1320
		assertNoError(proc.Continue(p), t, "Continue()")
1321 1322 1323 1324 1325
		v, err := evalVariable(p, "aas")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("v: %v\n", v)
	})
}
1326 1327 1328

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1329
	protest.AllowRecording(t)
1330
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1331
		assertNoError(proc.Continue(p), t, "Continue()")
1332 1333 1334 1335
		_, err := evalVariable(p, "iface5")
		assertNoError(err, t, "EvalVariable()")
	})
}
1336 1337 1338

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1339
	protest.AllowRecording(t)
1340
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1341
		assertNoError(proc.Continue(p), t, "Continue()")
1342 1343 1344 1345 1346 1347 1348 1349 1350
		iface2fn1v, err := evalVariable(p, "iface2fn1")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("iface2fn1: %v\n", iface2fn1v)

		iface2fn2v, err := evalVariable(p, "iface2fn2")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("iface2fn2: %v\n", iface2fn2v)
	})
}
1351 1352

func TestBreakpointCounts(t *testing.T) {
1353
	protest.AllowRecording(t)
1354
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1355
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1356
		assertNoError(err, t, "LineToPC")
1357
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1358 1359 1360
		assertNoError(err, t, "SetBreakpoint()")

		for {
1361 1362
			if err := proc.Continue(p); err != nil {
				if _, exited := err.(proc.ProcessExitedError); exited {
1363 1364 1365 1366 1367 1368 1369
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
		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)
			}
		}
	})
}

1386 1387
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
1388
	protest.AllowRecording(b)
1389
	b.SetBytes(int64(64 * 128))
1390
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1391
		assertNoError(proc.Continue(p), b, "Continue()")
1392 1393 1394 1395 1396 1397 1398
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "bencharr")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

1399 1400 1401 1402 1403 1404 1405
const doTestBreakpointCountsWithDetection = false

func TestBreakpointCountsWithDetection(t *testing.T) {
	if !doTestBreakpointCountsWithDetection {
		return
	}
	m := map[int64]int64{}
1406
	protest.AllowRecording(t)
1407
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1408
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1409
		assertNoError(err, t, "LineToPC")
1410
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1411 1412 1413
		assertNoError(err, t, "SetBreakpoint()")

		for {
1414 1415
			if err := proc.Continue(p); err != nil {
				if _, exited := err.(proc.ProcessExitedError); exited {
1416 1417 1418 1419
					break
				}
				assertNoError(err, t, "Continue()")
			}
1420
			for _, th := range p.ThreadList() {
1421
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
1422 1423
					continue
				}
1424
				scope, err := proc.GoroutineScope(th)
1425
				assertNoError(err, t, "Scope()")
1426
				v, err := scope.EvalVariable("i", normalLoadConfig)
1427 1428
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
1429
				v, err = scope.EvalVariable("id", normalLoadConfig)
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
				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)
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
		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)
			}
		}
	})
}
1461

1462 1463 1464
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
1465
	protest.AllowRecording(b)
1466
	b.SetBytes(int64(64*128 + 64*8))
1467
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1468
		assertNoError(proc.Continue(p), b, "Continue()")
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "bencharr")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

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
1480
	protest.AllowRecording(b)
1481
	b.SetBytes(int64(41 * (2*8 + 9)))
1482
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1483
		assertNoError(proc.Continue(p), b, "Continue()")
1484 1485 1486 1487 1488 1489 1490 1491
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "m1")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1492
	protest.AllowRecording(b)
1493
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1494
		assertNoError(proc.Continue(p), b, "Continue()")
1495
		for i := 0; i < b.N; i++ {
1496 1497 1498 1499 1500
			if p, ok := p.(proc.AllGCache); ok {
				allgcache := p.AllGCache()
				*allgcache = nil
			}
			_, err := proc.GoroutinesInfo(p)
1501 1502 1503 1504 1505
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1506 1507
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
1508
	protest.AllowRecording(t)
1509
	withTestProcess("issue262", t, func(p proc.Process, fixture protest.Fixture) {
1510
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 11)
1511
		assertNoError(err, t, "LineToPC")
1512
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1513 1514
		assertNoError(err, t, "SetBreakpoint()")

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

1527
func TestIssue305(t *testing.T) {
1528 1529 1530
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1531
	protest.AllowRecording(t)
1532
	withTestProcess("issue305", t, func(p proc.Process, fixture protest.Fixture) {
1533
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 5)
1534
		assertNoError(err, t, "LineToPC()")
1535
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1536 1537
		assertNoError(err, t, "SetBreakpoint()")

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

1540 1541 1542 1543 1544
		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")
1545 1546 1547
	})
}

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

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

func TestCondBreakpoint(t *testing.T) {
1577
	protest.AllowRecording(t)
1578
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1579
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1580
		assertNoError(err, t, "LineToPC")
1581
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1582 1583 1584 1585 1586 1587 1588
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1589
		assertNoError(proc.Continue(p), t, "Continue()")
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601

		nvar, err := evalVariable(p, "n")
		assertNoError(err, t, "EvalVariable()")

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

func TestCondBreakpointError(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: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1614
		err = proc.Continue(p)
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
		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"},
		}

1629
		err = proc.Continue(p)
1630
		if err != nil {
1631
			if _, exited := err.(proc.ProcessExitedError); !exited {
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
				t.Fatalf("Unexpected error on second Continue(): %v", err)
			}
		} else {
			nvar, err := evalVariable(p, "n")
			assertNoError(err, t, "EvalVariable()")

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

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

func TestStepIntoFunction(t *testing.T) {
1660
	withTestProcess("teststep", t, func(p proc.Process, fixture protest.Fixture) {
1661
		// Continue until breakpoint
1662
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1663
		// Step into function
1664
		assertNoError(proc.Step(p), t, "Step() returned an error")
1665
		// We should now be inside the function.
1666
		loc, err := p.CurrentThread().Location()
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
		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)
		}
	})
}
1681 1682 1683

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
1684
	protest.AllowRecording(t)
1685
	withTestProcess("issue384", t, func(p proc.Process, fixture protest.Fixture) {
1686
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 13)
1687
		assertNoError(err, t, "LineToPC()")
1688
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1689
		assertNoError(err, t, "SetBreakpoint()")
1690
		assertNoError(proc.Continue(p), t, "Continue()")
1691 1692 1693 1694
		_, err = evalVariable(p, "st")
		assertNoError(err, t, "EvalVariable()")
	})
}
A
aarzilli 已提交
1695 1696 1697

func TestIssue332_Part1(t *testing.T) {
	// Next shouldn't step inside a function call
1698
	protest.AllowRecording(t)
1699
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1700
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1701
		assertNoError(err, t, "LineToPC()")
1702
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1703
		assertNoError(err, t, "SetBreakpoint()")
1704 1705 1706
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "first Next()")
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
		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
1725
	protest.AllowRecording(t)
1726
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1727
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1728
		assertNoError(err, t, "LineToPC()")
1729
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1730
		assertNoError(err, t, "SetBreakpoint()")
1731
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
1732 1733 1734

		// step until we enter changeMe
		for {
1735 1736
			assertNoError(proc.Step(p), t, "Step()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745
			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
			}
		}

1746 1747 1748
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers()")
		pc := regs.PC()
1749
		pcAfterPrologue, err := proc.FindFunctionLocation(p, "main.changeMe", true, -1)
1750
		assertNoError(err, t, "FindFunctionLocation()")
1751
		pcEntry, err := proc.FindFunctionLocation(p, "main.changeMe", false, 0)
1752 1753 1754
		if err != nil {
			t.Fatalf("got error while finding function location: %v", err)
		}
1755 1756 1757 1758 1759 1760 1761
		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)
		}

1762 1763 1764 1765 1766
		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)
		if _, exited := err.(proc.ProcessExitedError); !exited {
A
aarzilli 已提交
1767 1768 1769 1770
			assertNoError(err, t, "final Continue()")
		}
	})
}
1771 1772

func TestIssue396(t *testing.T) {
1773
	withTestProcess("callme", t, func(p proc.Process, fixture protest.Fixture) {
1774
		_, err := proc.FindFunctionLocation(p, "main.init", true, -1)
1775 1776 1777
		assertNoError(err, t, "FindFunctionLocation()")
	})
}
1778 1779 1780

func TestIssue414(t *testing.T) {
	// Stepping until the program exits
1781
	protest.AllowRecording(t)
1782
	withTestProcess("math", t, func(p proc.Process, fixture protest.Fixture) {
1783
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1784
		assertNoError(err, t, "LineToPC()")
1785
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1786
		assertNoError(err, t, "SetBreakpoint()")
1787
		assertNoError(proc.Continue(p), t, "Continue()")
1788
		for {
1789
			err := proc.Step(p)
1790
			if err != nil {
1791
				if _, exited := err.(proc.ProcessExitedError); exited {
1792 1793 1794 1795 1796 1797 1798
					break
				}
			}
			assertNoError(err, t, "Step()")
		}
	})
}
1799 1800

func TestPackageVariables(t *testing.T) {
1801
	protest.AllowRecording(t)
1802
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1803
		err := proc.Continue(p)
1804
		assertNoError(err, t, "Continue()")
1805
		scope, err := proc.GoroutineScope(p.CurrentThread())
1806
		assertNoError(err, t, "Scope()")
1807
		vars, err := scope.PackageVariables(normalLoadConfig)
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
		assertNoError(err, t, "PackageVariables()")
		failed := false
		for _, v := range vars {
			if v.Unreadable != nil {
				failed = true
				t.Logf("Unreadable variable %s: %v", v.Name, v.Unreadable)
			}
		}
		if failed {
			t.Fatalf("previous errors")
		}
	})
}
1821 1822

func TestIssue149(t *testing.T) {
1823 1824
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
1825 1826 1827
		return
	}
	// setting breakpoint on break statement
1828
	withTestProcess("break", t, func(p proc.Process, fixture protest.Fixture) {
1829
		_, err := proc.FindFileLocation(p, fixture.Source, 8)
1830 1831 1832
		assertNoError(err, t, "FindFileLocation()")
	})
}
1833 1834

func TestPanicBreakpoint(t *testing.T) {
1835
	protest.AllowRecording(t)
1836
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
1837
		assertNoError(proc.Continue(p), t, "Continue()")
1838 1839
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1840
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1841 1842 1843
		}
	})
}
1844

1845
func TestCmdLineArgs(t *testing.T) {
1846
	expectSuccess := func(p proc.Process, fixture protest.Fixture) {
1847
		err := proc.Continue(p)
1848 1849
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint != nil && bp.Name == proc.UnrecoveredPanic {
1850
			t.Fatalf("testing args failed on unrecovered-panic breakpoint: %v", bp)
1851
		}
1852
		exit, exited := err.(proc.ProcessExitedError)
1853
		if !exited {
1854
			t.Fatalf("Process did not exit: %v", err)
1855 1856
		} else {
			if exit.Status != 0 {
1857
				t.Fatalf("process exited with invalid status %d", exit.Status)
1858 1859 1860 1861
			}
		}
	}

1862
	expectPanic := func(p proc.Process, fixture protest.Fixture) {
1863
		proc.Continue(p)
1864 1865
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1866
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1867 1868 1869 1870
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
1871 1872 1873
	withTestProcessArgs("testargs", t, ".", []string{"test"}, expectSuccess)
	withTestProcessArgs("testargs", t, ".", []string{"-test"}, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass flag"}, expectSuccess)
1874
	// check that arguments with spaces are *only* passed correctly when correctly called
1875 1876 1877
	withTestProcessArgs("testargs", t, ".", []string{"test pass", "flag"}, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass", "flag"}, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test pass flag"}, expectPanic)
1878 1879
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
1880 1881 1882
	withTestProcessArgs("testargs", t, ".", []string{"invalid"}, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "invalid"}, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"invalid", "pass flag"}, expectPanic)
1883 1884
}

1885 1886 1887 1888 1889
func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
1890
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
		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()
		}()

1905 1906
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
1907 1908 1909
		assertNoError(err, t, "Stacktrace()")
	})
}
1910

1911
func TestNextParked(t *testing.T) {
1912
	protest.AllowRecording(t)
1913
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1914 1915 1916 1917
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1918
		var parkedg *proc.G
1919
		for parkedg == nil {
1920 1921
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
1922 1923 1924 1925 1926
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1927
			gs, err := proc.GoroutinesInfo(p)
1928 1929
			assertNoError(err, t, "GoroutinesInfo()")

1930 1931 1932 1933
			// 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
1934
			for _, g := range gs {
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
				if g.Thread != nil {
					continue
				}
				frames, _ := g.Stacktrace(5)
				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
1948 1949 1950 1951 1952 1953
				}
			}
		}

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

1956 1957
		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)
1958 1959 1960
		}
	})
}
1961 1962

func TestStepParked(t *testing.T) {
1963
	protest.AllowRecording(t)
1964
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1965 1966 1967 1968
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1969
		var parkedg *proc.G
1970 1971
	LookForParkedG:
		for {
1972 1973
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
1974 1975 1976 1977 1978
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1979
			gs, err := proc.GoroutinesInfo(p)
1980 1981 1982
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
1983
				if g.Thread == nil && g.CurrentLoc.Fn != nil && g.CurrentLoc.Fn.Name == "main.sayhi" {
1984 1985 1986 1987 1988 1989
					parkedg = g
					break LookForParkedG
				}
			}
		}

A
aarzilli 已提交
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
		t.Logf("Parked g is: %v\n", parkedg)
		frames, _ := parkedg.Stacktrace(20)
		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)
		}

2000 2001
		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
2002
		assertNoError(proc.Step(p), t, "Step()")
2003

2004 2005
		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)
2006 2007 2008
		}
	})
}
2009 2010 2011 2012 2013 2014 2015 2016

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")
2017
	_, err := native.Launch([]string{exepath}, ".")
2018 2019 2020
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
2021 2022
	if err != proc.NotExecutableErr {
		t.Fatalf("expected error \"%v\" got \"%v\"", proc.NotExecutableErr, err)
2023 2024 2025 2026 2027
	}
	os.Remove(exepath)
}

func TestUnsupportedArch(t *testing.T) {
2028 2029
	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, ""}) {
2030 2031 2032
		// cross compile (with -N?) works only on select versions of go
		return
	}
2033

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

2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
	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)
2050

2051
	p, err := native.Launch([]string{outfile}, ".")
2052
	switch err {
2053
	case proc.UnsupportedLinuxArchErr, proc.UnsupportedWindowsArchErr, proc.UnsupportedDarwinArchErr:
2054 2055 2056 2057 2058 2059 2060 2061 2062
		// all good
	case nil:
		p.Halt()
		p.Kill()
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
2063

2064
func TestIssue573(t *testing.T) {
2065
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
2066
	// of the function and the internal breakpoint set by StepInto may be missed.
2067
	protest.AllowRecording(t)
2068
	withTestProcess("issue573", t, func(p proc.Process, fixture protest.Fixture) {
2069
		fentry, _ := proc.FindFunctionLocation(p, "main.foo", false, 0)
2070
		_, err := p.SetBreakpoint(fentry, proc.UserBreakpoint, nil)
2071
		assertNoError(err, t, "SetBreakpoint()")
2072 2073 2074 2075
		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.
2076 2077
	})
}
2078 2079

func TestTestvariables2Prologue(t *testing.T) {
2080
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2081
		addrEntry, err := proc.FindFunctionLocation(p, "main.main", false, 0)
2082
		assertNoError(err, t, "FindFunctionLocation - entrypoint")
2083
		addrPrologue, err := proc.FindFunctionLocation(p, "main.main", true, 0)
2084 2085 2086 2087 2088 2089
		assertNoError(err, t, "FindFunctionLocation - postprologue")
		if addrEntry == addrPrologue {
			t.Fatalf("Prologue detection failed on testvariables2.go/main.main")
		}
	})
}
2090 2091 2092 2093 2094

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 已提交
2095
	testseq("defercall", contNext, []nextTest{
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
		{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
A
aarzilli 已提交
2107
	testseq("defercall", contNext, []nextTest{
2108 2109 2110 2111 2112
		{15, 16},
		{16, 17},
		{17, 18},
		{18, 5}}, "main.callAndPanic2", t)
}
A
aarzilli 已提交
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133

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.
	testseq("teststepprog", contStep, []nextTest{
		{9, 10},
		{10, 5},
		{5, 6},
		{6, 7},
		{7, 11}}, "", t)
}

func TestStepReturnAndPanic(t *testing.T) {
	// Tests that Step works correctly when returning from functions
	// and when a deferred function is called when panic'ing.
2134 2135
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 17},
			{17, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)

	} else {
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
	}
A
aarzilli 已提交
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
}

func TestStepDeferReturn(t *testing.T) {
	// Tests that Step works correctly when a deferred function is
	// called during a return.
	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)
}

func TestStepIgnorePrivateRuntime(t *testing.T) {
	// Tests that Step will ignore calls to private runtime functions
	// (such as runtime.convT2E in this case)
2177
	ver, _ := goversion.Parse(runtime.Version())
A
aarzilli 已提交
2178

2179
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
A
aarzilli 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
			{15, 14},
			{14, 17},
			{17, 22}}, "", t)
	} else {
		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.
2200
	protest.AllowRecording(t)
2201
	withTestProcess("issue561", t, func(p proc.Process, fixture protest.Fixture) {
2202
		setFileBreakpoint(p, t, fixture, 10)
2203 2204
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2205 2206 2207 2208 2209 2210 2211
		_, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number after Step, expected 5 got %d", ln)
		}
	})
}

A
aarzilli 已提交
2212
func TestStepOut(t *testing.T) {
2213
	protest.AllowRecording(t)
2214
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2215 2216
		bp, err := setFunctionBreakpoint(p, "main.helloworld")
		assertNoError(err, t, "SetBreakpoint()")
2217
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2218 2219 2220 2221 2222 2223 2224
		p.ClearBreakpoint(bp.Addr)

		f, lno := currentLineNumber(p, t)
		if lno != 13 {
			t.Fatalf("wrong line number %s:%d, expected %d", f, lno, 13)
		}

2225
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2226 2227 2228

		f, lno = currentLineNumber(p, t)
		if lno != 35 {
2229
			t.Fatalf("wrong line number %s:%d, expected %d", f, lno, 35)
A
aarzilli 已提交
2230 2231 2232 2233
		}
	})
}

A
aarzilli 已提交
2234
func TestStepConcurrentDirect(t *testing.T) {
2235
	protest.AllowRecording(t)
2236
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2237
		pc, err := proc.FindFileLocation(p, fixture.Source, 37)
A
aarzilli 已提交
2238
		assertNoError(err, t, "FindFileLocation()")
2239
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2240 2241
		assertNoError(err, t, "SetBreakpoint()")

2242
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2243 2244 2245
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")

A
aarzilli 已提交
2246
		for _, b := range p.Breakpoints().M {
2247
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2248 2249 2250 2251 2252 2253
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

2254
		gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2255 2256 2257 2258 2259 2260

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

		i := 0
		count := 0
		for {
A
aarzilli 已提交
2261
			anyerr := false
2262 2263
			if p.SelectedGoroutine().ID != gid {
				t.Errorf("Step switched to different goroutine %d %d\n", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2264 2265
				anyerr = true
			}
A
aarzilli 已提交
2266 2267 2268 2269 2270 2271
			f, ln := currentLineNumber(p, t)
			if ln != seq[i] {
				if i == 1 && ln == 40 {
					// loop exited
					break
				}
2272
				frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
A
aarzilli 已提交
2273
				if err != nil {
2274
					t.Errorf("Could not get stacktrace of goroutine %d\n", p.SelectedGoroutine().ID)
A
aarzilli 已提交
2275
				} else {
2276
					t.Logf("Goroutine %d (thread: %d):", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
A
aarzilli 已提交
2277 2278 2279 2280 2281 2282
					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 已提交
2283
			}
A
aarzilli 已提交
2284 2285
			if anyerr {
				t.FailNow()
A
aarzilli 已提交
2286 2287 2288 2289 2290
			}
			i = (i + 1) % len(seq)
			if i == 0 {
				count++
			}
2291
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300
		}

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

func TestStepConcurrentPtr(t *testing.T) {
2301
	protest.AllowRecording(t)
2302
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2303
		pc, err := proc.FindFileLocation(p, fixture.Source, 24)
A
aarzilli 已提交
2304
		assertNoError(err, t, "FindFileLocation()")
2305
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2306 2307
		assertNoError(err, t, "SetBreakpoint()")

A
aarzilli 已提交
2308
		for _, b := range p.Breakpoints().M {
2309
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2310 2311 2312 2313 2314 2315
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2316 2317 2318
		kvals := map[int]int64{}
		count := 0
		for {
2319 2320
			err := proc.Continue(p)
			_, exited := err.(proc.ProcessExitedError)
A
aarzilli 已提交
2321 2322 2323 2324 2325 2326 2327
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
2328
				for _, th := range p.ThreadList() {
2329
					t.Logf("thread %d stopped on breakpoint %v", th.ThreadID(), th.Breakpoint())
A
aarzilli 已提交
2330
				}
2331
				curbp := p.CurrentThread().Breakpoint()
2332
				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 已提交
2333 2334
			}

2335
			gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2336 2337 2338 2339 2340 2341 2342

			kvar, err := evalVariable(p, "k")
			assertNoError(err, t, "EvalVariable()")
			k, _ := constant.Int64Val(kvar.Value)

			if oldk, ok := kvals[gid]; ok {
				if oldk >= k {
2343
					t.Fatalf("Goroutine %d did not make progress?", gid)
A
aarzilli 已提交
2344 2345 2346 2347
				}
			}
			kvals[gid] = k

2348
			assertNoError(proc.Step(p), t, "Step()")
2349
			for p.Breakpoints().HasInternalBreakpoints() {
2350 2351
				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 已提交
2352
				}
2353
				assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2354 2355
			}

2356 2357
			if p.SelectedGoroutine().ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2358 2359
			}

2360 2361 2362
			f, ln = currentLineNumber(p, t)
			if ln != 13 {
				t.Fatalf("Step did not step into function call (13): %s:%d", f, ln)
A
aarzilli 已提交
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
			}

			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 已提交
2379
func TestStepOutDefer(t *testing.T) {
2380
	protest.AllowRecording(t)
2381
	withTestProcess("testnextdefer", t, func(p proc.Process, fixture protest.Fixture) {
2382
		pc, err := proc.FindFileLocation(p, fixture.Source, 9)
A
aarzilli 已提交
2383
		assertNoError(err, t, "FindFileLocation()")
2384
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2385
		assertNoError(err, t, "SetBreakpoint()")
2386
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2387 2388 2389 2390 2391 2392 2393
		p.ClearBreakpoint(bp.Addr)

		f, lno := currentLineNumber(p, t)
		if lno != 9 {
			t.Fatalf("worng line number %s:%d, expected %d", f, lno, 5)
		}

2394
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2395

2396
		f, l, _ := p.BinInfo().PCToLine(currentPC(p, t))
A
aarzilli 已提交
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
		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
2407
	protest.AllowRecording(t)
2408
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2409
		bp := setFileBreakpoint(p, t, fixture, 11)
2410
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2411 2412
		p.ClearBreakpoint(bp.Addr)

2413
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2414 2415 2416 2417 2418 2419 2420 2421

		f, ln := currentLineNumber(p, t)
		if ln != 28 {
			t.Fatalf("wrong line number, expected %d got %s:%d", 28, f, ln)
		}
	})
}

2422 2423
const maxInstructionLength uint64 = 15

A
aarzilli 已提交
2424
func TestStepOnCallPtrInstr(t *testing.T) {
2425
	protest.AllowRecording(t)
2426
	withTestProcess("teststepprog", t, func(p proc.Process, fixture protest.Fixture) {
2427
		pc, err := proc.FindFileLocation(p, fixture.Source, 10)
A
aarzilli 已提交
2428
		assertNoError(err, t, "FindFileLocation()")
2429
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2430 2431
		assertNoError(err, t, "SetBreakpoint()")

2432
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2433 2434 2435 2436 2437 2438 2439 2440

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
2441
			regs, err := p.CurrentThread().Registers(false)
2442
			assertNoError(err, t, "Registers()")
2443
			pc := regs.PC()
2444
			text, err := proc.Disassemble(p, nil, pc, pc+maxInstructionLength)
A
aarzilli 已提交
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
			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")
		}

2457
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2458 2459 2460 2461 2462 2463 2464

		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("Step continued to wrong line, expected 5 was %s:%d", f, ln)
		}
	})
}
2465 2466

func TestIssue594(t *testing.T) {
2467 2468 2469 2470 2471 2472 2473 2474
	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
	}
2475 2476 2477 2478
	// 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.
2479
	protest.AllowRecording(t)
2480
	withTestProcess("issue594", t, func(p proc.Process, fixture protest.Fixture) {
2481
		assertNoError(proc.Continue(p), t, "Continue()")
2482 2483 2484 2485 2486 2487 2488 2489 2490
		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)
		}
2491 2492 2493 2494 2495
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2496 2497 2498 2499 2500

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
2501
	protest.AllowRecording(t)
2502
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2503
		bp := setFileBreakpoint(p, t, fixture, 17)
2504
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2505 2506
		p.ClearBreakpoint(bp.Addr)

2507
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2508 2509 2510 2511 2512 2513 2514

		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number, expected %d got %s:%d", 5, f, ln)
		}
	})
}
E
Evgeny L 已提交
2515 2516 2517 2518 2519 2520 2521

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"
	}
2522
	protest.AllowRecording(t)
2523
	withTestProcessArgs("workdir", t, wd, []string{}, func(p proc.Process, fixture protest.Fixture) {
2524
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 14)
E
Evgeny L 已提交
2525
		assertNoError(err, t, "LineToPC")
2526 2527
		p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
		proc.Continue(p)
E
Evgeny L 已提交
2528 2529 2530 2531 2532 2533
		v, err := evalVariable(p, "pwd")
		assertNoError(err, t, "EvalVariable")
		str := constant.StringVal(v.Value)
		if wd != str {
			t.Fatalf("Expected %s got %s\n", wd, str)
		}
2534
	})
E
Evgeny L 已提交
2535
}
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546

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)},
	}
2547
	protest.AllowRecording(t)
2548
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2549
		assertNoError(proc.Continue(p), t, "Continue()")
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
		for _, tc := range testcases {
			v, err := evalVariable(p, tc.name)
			assertNoError(err, t, "EvalVariable()")
			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)
			}
		}
	})
}
2562 2563 2564

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
2565
	protest.AllowRecording(t)
2566
	withTestProcess("issue683", t, func(p proc.Process, fixture protest.Fixture) {
2567 2568
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
2569
		assertNoError(proc.Continue(p), t, "First Continue()")
2570 2571 2572
		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
2573
			err := proc.Step(p)
2574 2575 2576 2577
			if err != nil {
				break
			}
		}
2578 2579 2580 2581
	})
}

func TestIssue664(t *testing.T) {
2582
	protest.AllowRecording(t)
2583
	withTestProcess("issue664", t, func(p proc.Process, fixture protest.Fixture) {
2584
		setFileBreakpoint(p, t, fixture, 4)
2585 2586
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
2587 2588 2589
		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("Did not continue to line 5: %s:%d", f, ln)
2590 2591 2592
		}
	})
}
A
Alessandro Arzilli 已提交
2593 2594 2595

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

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.
2617
	protest.AllowRecording(t)
2618
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2619 2620
		_, err := setFunctionBreakpoint(p, "runtime.deferreturn")
		assertNoError(err, t, "setFunctionBreakpoint()")
2621
		assertNoError(proc.Continue(p), t, "First Continue()")
A
Alessandro Arzilli 已提交
2622
		for i := 0; i < 20; i++ {
2623
			assertNoError(proc.Next(p), t, fmt.Sprintf("Next() %d", i))
A
Alessandro Arzilli 已提交
2624 2625 2626 2627
		}
	})
}

2628
func getg(goid int, gs []*proc.G) *proc.G {
A
Alessandro Arzilli 已提交
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
	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.
2643

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

2649 2650 2651 2652 2653
	// 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")

2654
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2655 2656 2657 2658 2659
		// 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 {
2660 2661
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
2662 2663 2664 2665
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
2666
			gs, err := proc.GoroutinesInfo(p)
A
Alessandro Arzilli 已提交
2667
			assertNoError(err, t, "GoroutinesInfo()")
2668
			for _, th := range p.ThreadList() {
2669
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
A
Alessandro Arzilli 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
					continue
				}

				goidVar, err := evalVariable(p, "gp.goid")
				assertNoError(err, t, "evalVariable")
				goid, _ := constant.Int64Val(goidVar.Value)

				if g := getg(int(goid), gs); g != nil {
					stack, err := g.Stacktrace(50)
					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)

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

2698
		gs, err := proc.GoroutinesInfo(p)
A
Alessandro Arzilli 已提交
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
		assertNoError(err, t, "GoroutinesInfo()")

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

			stack, err := g.Stacktrace(200)
			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
				}
2727
				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 已提交
2728 2729 2730
			}

			if !found {
2731
				t.Logf("Truncated stacktrace for %d\n", goid)
A
Alessandro Arzilli 已提交
2732 2733 2734 2735
			}
		}
	})
}
2736 2737

func TestAttachDetach(t *testing.T) {
2738 2739 2740 2741 2742 2743
	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
		}
2744
	}
2745 2746 2747
	if testBackend == "rr" {
		return
	}
2748
	fixture := protest.BuildFixture("testnextnethttp", 0)
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
	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")
		}
	}

2768
	var p proc.Process
2769 2770 2771 2772
	var err error

	switch testBackend {
	case "native":
2773
		p, err = native.Attach(cmd.Process.Pid)
2774 2775 2776 2777 2778
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
2779
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path)
2780 2781 2782 2783
	default:
		err = fmt.Errorf("unknown backend %q", testBackend)
	}

2784 2785 2786 2787 2788 2789
	assertNoError(err, t, "Attach")
	go func() {
		time.Sleep(1 * time.Second)
		http.Get("http://localhost:9191")
	}()

2790
	assertNoError(proc.Continue(p), t, "Continue")
2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802

	f, ln := currentLineNumber(p, t)
	if ln != 11 {
		t.Fatalf("Expected line :11 got %s:%d", f, ln)
	}

	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")
2803
	if out := string(bs); !strings.Contains(out, "hello, world!") {
2804 2805 2806 2807 2808
		t.Fatalf("/nobp page does not contain \"hello, world!\": %q", out)
	}

	cmd.Process.Kill()
}
2809 2810

func TestVarSum(t *testing.T) {
2811
	protest.AllowRecording(t)
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		sumvar, err := evalVariable(p, "s1[0] + s1[1]")
		assertNoError(err, t, "EvalVariable")
		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) {
2827
	protest.AllowRecording(t)
2828 2829 2830 2831 2832 2833 2834 2835
	withTestProcess("pkgrenames", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := evalVariable(p, "pkg.SomeVar")
		assertNoError(err, t, "EvalVariable(pkg.SomeVar)")
		_, err = evalVariable(p, "pkg.SomeVar.X")
		assertNoError(err, t, "EvalVariable(pkg.SomeVar.X)")
	})
}
2836 2837

func TestEnvironment(t *testing.T) {
2838
	protest.AllowRecording(t)
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
	os.Setenv("SOMEVAR", "bah")
	withTestProcess("testenv", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		v, err := evalVariable(p, "x")
		assertNoError(err, t, "EvalVariable()")
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != "bah" {
			t.Fatalf("value of v is %q (expected \"bah\")", vv)
		}
	})
}
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903

func getFrameOff(p proc.Process, t *testing.T) int64 {
	frameoffvar, err := evalVariable(p, "runtime.frameoff")
	assertNoError(err, t, "EvalVariable(runtime.frameoff)")
	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?")
		}
		_, ln := currentLineNumber(p, t)
		if ln != 6 {
			t.Fatalf("program did not continue to expected location %d", ln)
		}
		assertNoError(proc.Next(p), t, "Next 4")
		_, ln = currentLineNumber(p, t)
		if ln != 7 {
			t.Fatalf("program did not continue to expected location %d", ln)
		}
		assertNoError(proc.StepOut(p), t, "StepOut")
		_, ln = currentLineNumber(p, t)
		if ln != 11 {
			t.Fatalf("program did not continue to expected location %d", ln)
		}
		frameoff2 := getFrameOff(p, t)
		if frameoff0 != frameoff2 {
			t.Fatalf("frame offset mismatch %x != %x", frameoff0, frameoff2)
		}
	})
}
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923

// 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
	}
	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()")
		v, err := evalVariable(p, "dyldenv")
		assertNoError(err, t, "EvalVariable()")
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != envval {
			t.Fatalf("value of v is %q (expected %q)", vv, envval)
		}
	})
}
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937

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
	// error.
	protest.AllowRecording(t)
	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		err := proc.Next(p)
		if err == nil {
			return
		}
		if _, ok := err.(*frame.NoFDEForPCError); ok {
			return
		}
2938 2939
		if _, ok := err.(proc.ThreadBlockedError); ok {
			return
2940 2941 2942
		}
		if _, ok := err.(*proc.NoSourceForPCError); ok {
			return
2943
		}
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
		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")
	})
}
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001

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 {
				scope = proc.FrameToScope(p, frame)
			}
		} 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 已提交
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041

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")
		}
	})
}
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 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 3100 3101 3102 3103

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
	}
	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":
		p, err = native.Attach(cmd.Process.Pid)
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path)
	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)
}
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123

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")
		f, l := currentLineNumber(p, t)
		if l != 10 {
			t.Fatalf("continued to wrong location %s:%d (expected 10)", f, l)
		}
	})
}
A
aarzilli 已提交
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 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 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339

func logStacktrace(t *testing.T, frames []proc.Stackframe) {
	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)
	}
}

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

			frames, err := g.Stacktrace(100)
			assertNoError(err, t, fmt.Sprintf("Stacktrace at iteration step %d", itidx))

			t.Logf("iteration step %d", itidx)
			logStacktrace(t, frames)

			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:")
						logStacktrace(t, threadFrames)
						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")
		frames, err := g.Stacktrace(100)
		assertNoError(err, t, "stacktrace")
		logStacktrace(t, frames)
		m := stacktraceCheck(t, []string{"!runtime.startpanic_m", "!runtime.systemstack", "runtime.startpanic", "main.main"}, frames)
		if m == nil {
			t.Fatal("see previous loglines")
		}
	})
}