proc_test.go 89.4 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
	fixture := protest.BuildFixture(name)
52
	var p proc.Process
53
	var err error
54
	var tracedir string
55 56
	switch testBackend {
	case "native":
57
		p, err = native.Launch([]string{fixture.Path}, ".")
58
	case "lldb":
59
		p, err = gdbserial.LLDBLaunch([]string{fixture.Path}, ".")
60 61 62 63 64
	case "rr":
		protest.MustHaveRecordingAllowed(t)
		t.Log("recording")
		p, tracedir, err = gdbserial.RecordAndReplay([]string{fixture.Path}, ".", true)
		t.Logf("replaying %q", tracedir)
65 66 67
	default:
		t.Fatalf("unknown backend %q", testBackend)
	}
68 69 70 71
	if err != nil {
		t.Fatal("Launch():", err)
	}

72 73
	defer func() {
		p.Halt()
74
		p.Detach(true)
75 76 77
		if tracedir != "" {
			protest.SafeRemoveAll(tracedir)
		}
78
	}()
79

D
Dan Mace 已提交
80
	fn(p, fixture)
81 82
}

83
func withTestProcessArgs(name string, t testing.TB, wd string, fn func(p proc.Process, fixture protest.Fixture), args []string) {
84
	fixture := protest.BuildFixture(name)
85
	var p proc.Process
86
	var err error
87
	var tracedir string
88 89 90

	switch testBackend {
	case "native":
91
		p, err = native.Launch(append([]string{fixture.Path}, args...), wd)
92
	case "lldb":
93
		p, err = gdbserial.LLDBLaunch(append([]string{fixture.Path}, args...), wd)
94 95 96 97 98
	case "rr":
		protest.MustHaveRecordingAllowed(t)
		t.Log("recording")
		p, tracedir, err = gdbserial.RecordAndReplay([]string{fixture.Path}, wd, true)
		t.Logf("replaying %q", tracedir)
99 100 101
	default:
		t.Fatal("unknown backend")
	}
102 103 104 105 106 107
	if err != nil {
		t.Fatal("Launch():", err)
	}

	defer func() {
		p.Halt()
108
		p.Detach(true)
109 110 111
		if tracedir != "" {
			protest.SafeRemoveAll(tracedir)
		}
112 113 114 115 116
	}()

	fn(p, fixture)
}

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

	return regs
}

126
func dataAtAddr(thread proc.MemoryReadWriter, addr uint64) ([]byte, error) {
127 128 129
	data := make([]byte, 1)
	_, err := thread.ReadMemory(data, uintptr(addr))
	return data, err
130 131
}

132
func assertNoError(err error, t testing.TB, s string) {
133
	if err != nil {
134 135
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
136
		t.Fatalf("failed assertion at %s:%d: %s - %s\n", fname, line, s, err)
137 138 139
	}
}

140
func currentPC(p proc.Process, t *testing.T) uint64 {
141
	regs, err := p.CurrentThread().Registers(false)
142 143 144 145
	if err != nil {
		t.Fatal(err)
	}

146
	return regs.PC()
147 148
}

149
func currentLineNumber(p proc.Process, t *testing.T) (string, int) {
150
	pc := currentPC(p, t)
151
	f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
152
	return f, l
153 154
}

155
func TestExit(t *testing.T) {
156
	protest.AllowRecording(t)
157
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
158 159
		err := proc.Continue(p)
		pe, ok := err.(proc.ProcessExitedError)
160
		if !ok {
161
			t.Fatalf("Continue() returned unexpected error type %s", err)
162 163 164 165
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
166
		if pe.Pid != p.Pid() {
167 168 169 170 171
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

172
func TestExitAfterContinue(t *testing.T) {
173
	protest.AllowRecording(t)
174
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
175 176
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "setFunctionBreakpoint()")
177 178 179
		assertNoError(proc.Continue(p), t, "First Continue()")
		err = proc.Continue(p)
		pe, ok := err.(proc.ProcessExitedError)
180
		if !ok {
L
Luke Hoban 已提交
181
			t.Fatalf("Continue() returned unexpected error type %s", pe)
182 183 184 185
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
186
		if pe.Pid != p.Pid() {
187 188 189 190 191
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

192
func setFunctionBreakpoint(p proc.Process, fname string) (*proc.Breakpoint, error) {
193
	addr, err := proc.FindFunctionLocation(p, fname, true, 0)
194 195 196
	if err != nil {
		return nil, err
	}
197
	return p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
198 199
}

200
func setFileBreakpoint(p proc.Process, t *testing.T, fixture protest.Fixture, lineno int) *proc.Breakpoint {
201
	addr, err := proc.FindFileLocation(p, fixture.Source, lineno)
A
aarzilli 已提交
202 203 204
	if err != nil {
		t.Fatalf("FindFileLocation: %v", err)
	}
205
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
A
aarzilli 已提交
206 207 208 209 210 211
	if err != nil {
		t.Fatalf("SetBreakpoint: %v", err)
	}
	return bp
}

D
Derek Parker 已提交
212
func TestHalt(t *testing.T) {
213
	stopChan := make(chan interface{}, 1)
214
	withTestProcess("loopprog", t, func(p proc.Process, fixture protest.Fixture) {
215
		_, err := setFunctionBreakpoint(p, "main.loop")
216
		assertNoError(err, t, "SetBreakpoint")
217 218 219
		assertNoError(proc.Continue(p), t, "Continue")
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
220 221
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
222 223
			}
		}
224
		resumeChan := make(chan struct{}, 1)
D
Derek Parker 已提交
225
		go func() {
A
aarzilli 已提交
226 227
			<-resumeChan
			time.Sleep(100 * time.Millisecond)
228
			stopChan <- p.RequestManualStop()
D
Derek Parker 已提交
229
		}()
A
aarzilli 已提交
230
		p.ResumeNotify(resumeChan)
231
		assertNoError(proc.Continue(p), t, "Continue")
232 233 234 235 236 237
		retVal := <-stopChan

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

D
Derek Parker 已提交
238 239 240
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
241 242 243 244 245 246
		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")
					}
247 248 249
				}
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
D
Derek Parker 已提交
250 251 252 253 254
			}
		}
	})
}

255
func TestStep(t *testing.T) {
256
	protest.AllowRecording(t)
257
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
258
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", false, 0)
259
		assertNoError(err, t, "FindFunctionLocation")
260

261
		_, err = p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
262
		assertNoError(err, t, "SetBreakpoint()")
263
		assertNoError(proc.Continue(p), t, "Continue()")
264

265
		regs := getRegisters(p, t)
266
		rip := regs.PC()
267

268
		err = p.CurrentThread().StepInstruction()
D
Derek Parker 已提交
269
		assertNoError(err, t, "Step()")
270

271
		regs = getRegisters(p, t)
272 273 274 275 276
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
277

D
Derek Parker 已提交
278
func TestBreakpoint(t *testing.T) {
279
	protest.AllowRecording(t)
280
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
281
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", false, 0)
282
		assertNoError(err, t, "FindFunctionLocation")
283

284
		bp, err := p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
285
		assertNoError(err, t, "SetBreakpoint()")
286
		assertNoError(proc.Continue(p), t, "Continue()")
287

288 289 290
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
291

292 293 294 295
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
296
		if pc-1 != bp.Addr && pc != bp.Addr {
297
			f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
298
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
299 300
		}
	})
301
}
302

D
Derek Parker 已提交
303
func TestBreakpointInSeperateGoRoutine(t *testing.T) {
304
	protest.AllowRecording(t)
305
	withTestProcess("testthreads", t, func(p proc.Process, fixture protest.Fixture) {
306
		fnentry, err := proc.FindFunctionLocation(p, "main.anotherthread", false, 0)
307
		assertNoError(err, t, "FindFunctionLocation")
308

309
		_, err = p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
310
		assertNoError(err, t, "SetBreakpoint")
311

312
		assertNoError(proc.Continue(p), t, "Continue")
313

314 315 316
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
317

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

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

334
func TestClearBreakpointBreakpoint(t *testing.T) {
335
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
336
		fnentry, err := proc.FindFunctionLocation(p, "main.sleepytime", false, 0)
337
		assertNoError(err, t, "FindFunctionLocation")
338
		bp, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
339
		assertNoError(err, t, "SetBreakpoint()")
340

341
		bp, err = p.ClearBreakpoint(fnentry)
342
		assertNoError(err, t, "ClearBreakpoint()")
343

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

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

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

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

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

A
aarzilli 已提交
372 373 374 375 376 377 378 379
type contFunc int

const (
	contNext contFunc = iota
	contStep
)

func testseq(program string, contFunc contFunc, testcases []nextTest, initialLocation string, t *testing.T) {
380
	protest.AllowRecording(t)
381
	withTestProcess(program, t, func(p proc.Process, fixture protest.Fixture) {
382
		var bp *proc.Breakpoint
A
aarzilli 已提交
383 384 385 386 387
		var err error
		if initialLocation != "" {
			bp, err = setFunctionBreakpoint(p, initialLocation)
		} else {
			var pc uint64
388
			pc, err = proc.FindFileLocation(p, fixture.Source, testcases[0].begin)
A
aarzilli 已提交
389
			assertNoError(err, t, "FindFileLocation()")
390
			bp, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
391
		}
392
		assertNoError(err, t, "SetBreakpoint()")
393
		assertNoError(proc.Continue(p), t, "Continue()")
394
		p.ClearBreakpoint(bp.Addr)
395 396
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
397 398 399
		if testBackend != "rr" {
			assertNoError(regs.SetPC(p.CurrentThread(), bp.Addr), t, "SetPC")
		}
400

D
Derek Parker 已提交
401
		f, ln := currentLineNumber(p, t)
402
		for _, tc := range testcases {
403 404
			regs, _ := p.CurrentThread().Registers(false)
			pc := regs.PC()
405
			if ln != tc.begin {
D
Derek Parker 已提交
406
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
407 408
			}

A
aarzilli 已提交
409 410
			switch contFunc {
			case contNext:
411
				assertNoError(proc.Next(p), t, "Next() returned an error")
A
aarzilli 已提交
412
			case contStep:
413
				assertNoError(proc.Step(p), t, "Step() returned an error")
A
aarzilli 已提交
414
			}
415

D
Derek Parker 已提交
416
			f, ln = currentLineNumber(p, t)
417 418
			regs, _ = p.CurrentThread().Registers(false)
			pc = regs.PC()
419
			if ln != tc.end {
A
aarzilli 已提交
420
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d (%#x)", tc.end, filepath.Base(f), ln, pc)
421 422
			}
		}
423

424
		if countBreakpoints(p) != 0 {
425
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints()))
426
		}
427 428
	})
}
429

430
func TestNextGeneral(t *testing.T) {
431 432
	var testcases []nextTest

433
	ver, _ := goversion.Parse(runtime.Version())
434

435
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
		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},
		}
472
	}
473

A
aarzilli 已提交
474
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
475 476
}

477 478
func TestNextConcurrent(t *testing.T) {
	testcases := []nextTest{
479
		{8, 9},
480 481 482
		{9, 10},
		{10, 11},
	}
483
	protest.AllowRecording(t)
484
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
485
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
486
		assertNoError(err, t, "SetBreakpoint")
487
		assertNoError(proc.Continue(p), t, "Continue")
488
		f, ln := currentLineNumber(p, t)
489
		initV, err := evalVariable(p, "n")
490
		initVval, _ := constant.Int64Val(initV.Value)
491
		assertNoError(err, t, "EvalVariable")
492 493
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")
494
		for _, tc := range testcases {
495
			g, err := proc.GetG(p.CurrentThread())
496
			assertNoError(err, t, "GetG()")
497 498
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
499
			}
500 501 502
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
503
			assertNoError(proc.Next(p), t, "Next() returned an error")
504 505 506 507
			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)
			}
508
			v, err := evalVariable(p, "n")
509
			assertNoError(err, t, "EvalVariable")
510 511
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
512 513 514 515 516 517
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

518 519 520
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{
521
		{8, 9},
522 523 524
		{9, 10},
		{10, 11},
	}
525
	protest.AllowRecording(t)
526
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
527 528
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint")
529
		assertNoError(proc.Continue(p), t, "Continue")
530 531 532 533 534
		f, ln := currentLineNumber(p, t)
		initV, err := evalVariable(p, "n")
		initVval, _ := constant.Int64Val(initV.Value)
		assertNoError(err, t, "EvalVariable")
		for _, tc := range testcases {
535
			t.Logf("test case %v", tc)
536
			g, err := proc.GetG(p.CurrentThread())
537
			assertNoError(err, t, "GetG()")
538 539
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
540 541 542 543
			}
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
544
			assertNoError(proc.Next(p), t, "Next() returned an error")
545 546 547
			var vval int64
			for {
				v, err := evalVariable(p, "n")
548 549 550
				for _, thread := range p.ThreadList() {
					proc.GetG(thread)
				}
551 552
				assertNoError(err, t, "EvalVariable")
				vval, _ = constant.Int64Val(v.Value)
553
				if bp, _, _ := p.CurrentThread().Breakpoint(); bp == nil {
554 555 556 557 558 559 560 561
					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")
					}
562
					assertNoError(proc.Continue(p), t, "Continue 2")
563 564 565 566 567 568 569 570 571 572
				}
			}
			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)
			}
		}
	})
}

573 574
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
575
		{13, 14},
D
Derek Parker 已提交
576 577
		{14, 15},
		{15, 35},
578
	}
579
	protest.AllowRecording(t)
A
aarzilli 已提交
580
	testseq("testnextprog", contNext, testcases, "main.helloworld", t)
581 582 583
}

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

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

588
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
		testcases = []nextTest{
			{5, 6},
			{6, 9},
			{9, 10},
			{10, 6},
			{6, 7},
			{7, 8},
		}
	} else {
		testcases = []nextTest{
			{5, 8},
			{8, 9},
			{9, 10},
			{10, 6},
			{6, 7},
			{7, 8},
		}
606
	}
607
	protest.AllowRecording(t)
A
aarzilli 已提交
608
	testseq("testnextdefer", contNext, testcases, "main.main", t)
609 610
}

D
Derek Parker 已提交
611 612 613 614 615
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
616
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
617 618 619
		go func() {
			// Wait for program to start listening.
			for {
L
Luke Hoban 已提交
620
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
621 622 623 624 625 626
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
627
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
628
		}()
629
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
630 631 632 633 634 635 636 637
			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)
			}

638
			assertNoError(proc.Next(p), t, "Next() returned an error")
D
Derek Parker 已提交
639 640 641 642 643 644 645 646 647

			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 已提交
648
func TestRuntimeBreakpoint(t *testing.T) {
649
	withTestProcess("testruntimebreakpoint", t, func(p proc.Process, fixture protest.Fixture) {
650
		err := proc.Continue(p)
D
Derek Parker 已提交
651 652 653
		if err != nil {
			t.Fatal(err)
		}
654 655 656
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
657
		f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
658
		if l != 10 {
659
			t.Fatalf("did not respect breakpoint %s:%d", f, l)
D
Derek Parker 已提交
660 661 662 663
		}
	})
}

664
func returnAddress(thread proc.Thread) (uint64, error) {
665
	locations, err := proc.ThreadStacktrace(thread, 2)
666 667 668 669
	if err != nil {
		return 0, err
	}
	if len(locations) < 2 {
670
		return 0, proc.NoReturnAddr{locations[0].Current.Fn.BaseName()}
671 672 673 674
	}
	return locations[1].Current.PC, nil
}

675
func TestFindReturnAddress(t *testing.T) {
676
	protest.AllowRecording(t)
677
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
678
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 24)
679 680 681
		if err != nil {
			t.Fatal(err)
		}
682
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
683 684 685
		if err != nil {
			t.Fatal(err)
		}
686
		err = proc.Continue(p)
687 688 689
		if err != nil {
			t.Fatal(err)
		}
690
		addr, err := returnAddress(p.CurrentThread())
691 692 693
		if err != nil {
			t.Fatal(err)
		}
694
		_, l, _ := p.BinInfo().PCToLine(addr)
695 696
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
697
		}
698 699
	})
}
700

701
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
702
	protest.AllowRecording(t)
703
	withTestProcess("testreturnaddress", t, func(p proc.Process, fixture protest.Fixture) {
704
		fnName := "runtime.rt0_go"
705
		fnentry, err := proc.FindFunctionLocation(p, fnName, false, 0)
706
		assertNoError(err, t, "FindFunctionLocation")
707
		if _, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil); err != nil {
708 709
			t.Fatal(err)
		}
710
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
711 712
			t.Fatal(err)
		}
713
		if _, err := returnAddress(p.CurrentThread()); err == nil {
714
			t.Fatal("expected error to be returned")
715 716 717
		}
	})
}
D
Derek Parker 已提交
718 719

func TestSwitchThread(t *testing.T) {
720
	protest.AllowRecording(t)
721
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
722 723 724 725 726
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
727
		pc, err := proc.FindFunctionLocation(p, "main.main", true, 0)
D
Derek Parker 已提交
728 729 730
		if err != nil {
			t.Fatal(err)
		}
731
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
D
Derek Parker 已提交
732 733 734
		if err != nil {
			t.Fatal(err)
		}
735
		err = proc.Continue(p)
D
Derek Parker 已提交
736 737 738 739
		if err != nil {
			t.Fatal(err)
		}
		var nt int
740 741 742 743
		ct := p.CurrentThread().ThreadID()
		for _, thread := range p.ThreadList() {
			if thread.ThreadID() != ct {
				nt = thread.ThreadID()
D
Derek Parker 已提交
744 745 746 747 748 749 750 751 752 753 754
				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)
		}
755
		if p.CurrentThread().ThreadID() != nt {
D
Derek Parker 已提交
756 757 758 759
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
760

761 762 763 764 765 766
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 已提交
767 768 769
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
770

771
	protest.AllowRecording(t)
772
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
773
		pc, err := proc.FindFunctionLocation(p, "main.main", true, 0)
774 775 776
		if err != nil {
			t.Fatal(err)
		}
777
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
778 779 780
		if err != nil {
			t.Fatal(err)
		}
781
		err = proc.Continue(p)
782 783 784
		if err != nil {
			t.Fatal(err)
		}
785
		err = proc.Next(p)
786 787 788 789 790 791
		if err != nil {
			t.Fatal(err)
		}
	})
}

A
aarzilli 已提交
792 793 794 795 796
type loc struct {
	line int
	fn   string
}

797
func (l1 *loc) match(l2 proc.Stackframe) bool {
A
aarzilli 已提交
798
	if l1.line >= 0 {
799
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
800 801 802
			return false
		}
	}
803
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
804 805 806 807
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
808 809
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
810
	}
811
	protest.AllowRecording(t)
812
	withTestProcess("stacktraceprog", t, func(p proc.Process, fixture protest.Fixture) {
813
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
814 815 816
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
817 818
			assertNoError(proc.Continue(p), t, "Continue()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
A
aarzilli 已提交
819 820 821 822 823 824
			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)
			}

825 826 827 828
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
829

A
aarzilli 已提交
830 831 832 833 834 835 836
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

837
		p.ClearBreakpoint(bp.Addr)
838
		proc.Continue(p)
A
aarzilli 已提交
839 840 841
	})
}

842
func TestStacktrace2(t *testing.T) {
843
	withTestProcess("retstack", t, func(p proc.Process, fixture protest.Fixture) {
844
		assertNoError(proc.Continue(p), t, "Continue()")
845

846
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
847
		assertNoError(err, t, "Stacktrace()")
848
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
849 850 851
			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 已提交
852
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
853 854
		}

855 856
		assertNoError(proc.Continue(p), t, "Continue()")
		locations, err = proc.ThreadStacktrace(p.CurrentThread(), 40)
857
		assertNoError(err, t, "Stacktrace()")
858
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
859 860 861
			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 已提交
862
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
863 864 865 866 867
		}
	})

}

868
func stackMatch(stack []loc, locations []proc.Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
869 870 871
	if len(stack) > len(locations) {
		return false
	}
872 873 874 875 876 877 878 879 880 881 882
	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 已提交
883 884
			return false
		}
885
		i++
A
aarzilli 已提交
886
	}
887
	return i >= len(stack)
A
aarzilli 已提交
888 889 890
}

func TestStacktraceGoroutine(t *testing.T) {
891
	mainStack := []loc{{13, "main.stacktraceme"}, {26, "main.main"}}
892 893 894 895 896
	agoroutineStacks := [][]loc{
		{{8, "main.agoroutine"}},
		{{9, "main.agoroutine"}},
		{{10, "main.agoroutine"}},
	}
A
aarzilli 已提交
897

898
	protest.AllowRecording(t)
899
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
900
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
901 902
		assertNoError(err, t, "BreakByLocation()")

903
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
904

905
		gs, err := proc.GoroutinesInfo(p)
A
aarzilli 已提交
906 907 908 909 910
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
911
		for i, g := range gs {
A
aarzilli 已提交
912
			locations, err := g.Stacktrace(40)
913 914
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
915
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
916 917
				continue
			}
A
aarzilli 已提交
918

919
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
920 921 922
				mainCount++
			}

923 924 925 926 927 928 929 930
			found := false
			for _, agoroutineStack := range agoroutineStacks {
				if stackMatch(agoroutineStack, locations, true) {
					found = true
				}
			}

			if found {
A
aarzilli 已提交
931 932
				agoroutineCount++
			} else {
D
Derek Parker 已提交
933
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
934 935
				for i := range locations {
					name := ""
936 937
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
938
					}
939
					t.Logf("\t%s:%d %s\n", locations[i].Call.File, locations[i].Call.Line, name)
A
aarzilli 已提交
940 941 942 943 944
				}
			}
		}

		if mainCount != 1 {
945
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
946 947 948 949 950 951
		}

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

952
		p.ClearBreakpoint(bp.Addr)
953
		proc.Continue(p)
A
aarzilli 已提交
954 955
	})
}
956 957

func TestKill(t *testing.T) {
958 959 960 961
	if testBackend == "lldb" {
		// k command presumably works but leaves the process around?
		return
	}
962
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
963 964 965
		if err := p.Kill(); err != nil {
			t.Fatal(err)
		}
966
		if !p.Exited() {
967 968 969
			t.Fatal("expected process to have exited")
		}
		if runtime.GOOS == "linux" {
970
			_, err := os.Open(fmt.Sprintf("/proc/%d/", p.Pid()))
971
			if err == nil {
972
				t.Fatal("process has not exited", p.Pid())
973 974 975
			}
		}
	})
976 977 978 979
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
		if err := p.Detach(true); err != nil {
			t.Fatal(err)
		}
980
		if !p.Exited() {
981 982 983 984 985 986 987 988 989
			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())
			}
		}
	})
990
}
991

992
func testGSupportFunc(name string, t *testing.T, p proc.Process, fixture protest.Fixture) {
993
	bp, err := setFunctionBreakpoint(p, "main.main")
994 995
	assertNoError(err, t, name+": BreakByLocation()")

996
	assertNoError(proc.Continue(p), t, name+": Continue()")
997

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

1015 1016 1017 1018
	// 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 已提交
1019 1020 1021
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
1022

1023
	protest.AllowRecording(t)
1024
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
1025 1026 1027
		testGSupportFunc("cgo", t, p, fixture)
	})
}
1028 1029

func TestContinueMulti(t *testing.T) {
1030
	protest.AllowRecording(t)
1031
	withTestProcess("integrationprog", t, func(p proc.Process, fixture protest.Fixture) {
1032
		bp1, err := setFunctionBreakpoint(p, "main.main")
1033 1034
		assertNoError(err, t, "BreakByLocation()")

1035
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
1036 1037 1038 1039 1040
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
1041
			err := proc.Continue(p)
1042
			if p.Exited() {
1043 1044 1045 1046
				break
			}
			assertNoError(err, t, "Continue()")

1047
			if bp, _, _ := p.CurrentThread().Breakpoint(); bp.ID == bp1.ID {
1048 1049 1050
				mainCount++
			}

1051
			if bp, _, _ := p.CurrentThread().Breakpoint(); bp.ID == bp2.ID {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
				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)
		}
	})
}
1065

1066
func TestBreakpointOnFunctionEntry(t *testing.T) {
1067
	protest.AllowRecording(t)
1068
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
1069
		addr, err := proc.FindFunctionLocation(p, "main.main", false, 0)
1070
		assertNoError(err, t, "FindFunctionLocation()")
1071
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1072
		assertNoError(err, t, "SetBreakpoint()")
1073
		assertNoError(proc.Continue(p), t, "Continue()")
1074 1075 1076 1077 1078 1079
		_, ln := currentLineNumber(p, t)
		if ln != 17 {
			t.Fatalf("Wrong line number: %d (expected: 17)\n", ln)
		}
	})
}
1080 1081

func TestProcessReceivesSIGCHLD(t *testing.T) {
1082
	protest.AllowRecording(t)
1083
	withTestProcess("sigchldprog", t, func(p proc.Process, fixture protest.Fixture) {
1084 1085
		err := proc.Continue(p)
		_, ok := err.(proc.ProcessExitedError)
1086
		if !ok {
1087
			t.Fatalf("Continue() returned unexpected error type %v", err)
1088 1089 1090
		}
	})
}
1091 1092

func TestIssue239(t *testing.T) {
1093
	withTestProcess("is sue239", t, func(p proc.Process, fixture protest.Fixture) {
1094
		pos, _, err := p.BinInfo().LineToPC(fixture.Source, 17)
1095
		assertNoError(err, t, "LineToPC()")
1096
		_, err = p.SetBreakpoint(pos, proc.UserBreakpoint, nil)
1097
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
1098
		assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue()"))
1099 1100
	})
}
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
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")
}

1116
func evalVariable(p proc.Process, symbol string) (*proc.Variable, error) {
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
	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())
	}
1129

1130 1131 1132
	if err != nil {
		return nil, err
	}
1133
	return scope.EvalVariable(symbol, normalLoadConfig)
1134 1135
}

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

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

1181
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1182
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

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

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

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

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

1279
		// Testing evaluation on frames
1280 1281
		assertNoError(proc.Continue(p), t, "Continue() 2")
		g, err := proc.GetG(p.CurrentThread())
1282 1283 1284
		assertNoError(err, t, "GetG()")

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

		pval := func(n int64) {
			variable, err := evalVariable(p, "p1")
			assertNoError(err, t, "EvalVariable()")
1305 1306 1307
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1308 1309 1310 1311 1312 1313
			}
		}

		pval(1)

		// change p1 to point to i2
1314
		scope, err := proc.GoroutineScope(p.CurrentThread())
1315
		assertNoError(err, t, "Scope()")
1316
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1317 1318
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1319 1320 1321 1322 1323 1324 1325 1326 1327
		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) {
1328
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1329
		err := proc.Continue(p)
1330 1331 1332 1333 1334 1335 1336 1337 1338
		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
1339
		err = proc.Continue(p)
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
		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) {
1353
	protest.AllowRecording(t)
1354
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1355
		assertNoError(proc.Continue(p), t, "Continue()")
1356 1357 1358 1359 1360
		v, err := evalVariable(p, "aas")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("v: %v\n", v)
	})
}
1361 1362 1363

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

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1374
	protest.AllowRecording(t)
1375
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1376
		assertNoError(proc.Continue(p), t, "Continue()")
1377 1378 1379 1380 1381 1382 1383 1384 1385
		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)
	})
}
1386 1387

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

		for {
1396 1397
			if err := proc.Continue(p); err != nil {
				if _, exited := err.(proc.ProcessExitedError); exited {
1398 1399 1400 1401 1402 1403 1404
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

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

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

1434 1435 1436 1437 1438 1439 1440
const doTestBreakpointCountsWithDetection = false

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

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

1497 1498 1499
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
1500
	protest.AllowRecording(b)
1501
	b.SetBytes(int64(64*128 + 64*8))
1502
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1503
		assertNoError(proc.Continue(p), b, "Continue()")
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
		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
1515
	protest.AllowRecording(b)
1516
	b.SetBytes(int64(41 * (2*8 + 9)))
1517
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1518
		assertNoError(proc.Continue(p), b, "Continue()")
1519 1520 1521 1522 1523 1524 1525 1526
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "m1")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1527
	protest.AllowRecording(b)
1528
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1529
		assertNoError(proc.Continue(p), b, "Continue()")
1530
		for i := 0; i < b.N; i++ {
1531 1532 1533 1534 1535
			if p, ok := p.(proc.AllGCache); ok {
				allgcache := p.AllGCache()
				*allgcache = nil
			}
			_, err := proc.GoroutinesInfo(p)
1536 1537 1538 1539 1540
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1541 1542
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
1543
	protest.AllowRecording(t)
1544
	withTestProcess("issue262", t, func(p proc.Process, fixture protest.Fixture) {
1545
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 11)
1546
		assertNoError(err, t, "LineToPC")
1547
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1548 1549
		assertNoError(err, t, "SetBreakpoint()")

1550 1551
		assertNoError(proc.Continue(p), t, "Continue()")
		err = proc.Continue(p)
1552 1553 1554
		if err == nil {
			t.Fatalf("No error on second continue")
		}
1555
		_, exited := err.(proc.ProcessExitedError)
1556 1557 1558 1559 1560
		if !exited {
			t.Fatalf("Process did not exit after second continue: %v", err)
		}
	})
}
1561

1562
func TestIssue305(t *testing.T) {
1563 1564 1565
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1566
	protest.AllowRecording(t)
1567
	withTestProcess("issue305", t, func(p proc.Process, fixture protest.Fixture) {
1568
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 5)
1569
		assertNoError(err, t, "LineToPC()")
1570
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1571 1572
		assertNoError(err, t, "SetBreakpoint()")

1573
		assertNoError(proc.Continue(p), t, "Continue()")
1574

1575 1576 1577 1578 1579
		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")
1580 1581 1582
	})
}

1583 1584 1585
func TestPointerLoops(t *testing.T) {
	// Pointer loops through map entries, pointers and slices
	// Regression test for issue #341
1586
	protest.AllowRecording(t)
1587
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1588
		assertNoError(proc.Continue(p), t, "Continue()")
1589 1590 1591 1592 1593 1594
		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)
		}
1595 1596
	})
}
1597 1598

func BenchmarkLocalVariables(b *testing.B) {
1599
	protest.AllowRecording(b)
1600
	withTestProcess("testvariables", b, func(p proc.Process, fixture protest.Fixture) {
1601 1602
		assertNoError(proc.Continue(p), b, "Continue() returned an error")
		scope, err := proc.GoroutineScope(p.CurrentThread())
1603 1604
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
1605
			_, err := scope.LocalVariables(normalLoadConfig)
1606 1607 1608 1609
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1610 1611

func TestCondBreakpoint(t *testing.T) {
1612
	protest.AllowRecording(t)
1613
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1614
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1615
		assertNoError(err, t, "LineToPC")
1616
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1617 1618 1619 1620 1621 1622 1623
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1624
		assertNoError(proc.Continue(p), t, "Continue()")
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636

		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) {
1637
	protest.AllowRecording(t)
1638
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1639
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1640
		assertNoError(err, t, "LineToPC")
1641
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1642 1643 1644 1645 1646 1647 1648
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1649
		err = proc.Continue(p)
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
		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"},
		}

1664
		err = proc.Continue(p)
1665
		if err != nil {
1666
			if _, exited := err.(proc.ProcessExitedError); !exited {
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
				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)
			}
		}
	})
}
1680 1681 1682

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1683
	protest.AllowRecording(t)
1684
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1685
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1686 1687 1688 1689 1690 1691 1692
		mmvar, err := evalVariable(p, "mainMenu")
		assertNoError(err, t, "EvalVariable()")
		if mmvar.Kind != reflect.Slice {
			t.Fatalf("Wrong kind for mainMenu: %v\n", mmvar.Kind)
		}
	})
}
1693 1694

func TestStepIntoFunction(t *testing.T) {
1695
	withTestProcess("teststep", t, func(p proc.Process, fixture protest.Fixture) {
1696
		// Continue until breakpoint
1697
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1698
		// Step into function
1699
		assertNoError(proc.Step(p), t, "Step() returned an error")
1700
		// We should now be inside the function.
1701
		loc, err := p.CurrentThread().Location()
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
		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)
		}
	})
}
1716 1717 1718

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
1719
	protest.AllowRecording(t)
1720
	withTestProcess("issue384", t, func(p proc.Process, fixture protest.Fixture) {
1721
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 13)
1722
		assertNoError(err, t, "LineToPC()")
1723
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1724
		assertNoError(err, t, "SetBreakpoint()")
1725
		assertNoError(proc.Continue(p), t, "Continue()")
1726 1727 1728 1729
		_, err = evalVariable(p, "st")
		assertNoError(err, t, "EvalVariable()")
	})
}
A
aarzilli 已提交
1730 1731 1732

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

		// step until we enter changeMe
		for {
1770 1771
			assertNoError(proc.Step(p), t, "Step()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1772 1773 1774 1775 1776 1777 1778 1779 1780
			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
			}
		}

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

1797 1798 1799 1800 1801
		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 已提交
1802 1803 1804 1805
			assertNoError(err, t, "final Continue()")
		}
	})
}
1806 1807

func TestIssue396(t *testing.T) {
1808
	withTestProcess("callme", t, func(p proc.Process, fixture protest.Fixture) {
1809
		_, err := proc.FindFunctionLocation(p, "main.init", true, -1)
1810 1811 1812
		assertNoError(err, t, "FindFunctionLocation()")
	})
}
1813 1814 1815

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

func TestPackageVariables(t *testing.T) {
1836
	protest.AllowRecording(t)
1837
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1838
		err := proc.Continue(p)
1839
		assertNoError(err, t, "Continue()")
1840
		scope, err := proc.GoroutineScope(p.CurrentThread())
1841
		assertNoError(err, t, "Scope()")
1842
		vars, err := scope.PackageVariables(normalLoadConfig)
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
		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")
		}
	})
}
1856 1857

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

func TestPanicBreakpoint(t *testing.T) {
1870
	protest.AllowRecording(t)
1871
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
1872
		assertNoError(proc.Continue(p), t, "Continue()")
1873
		bp, _, _ := p.CurrentThread().Breakpoint()
1874
		if bp == nil || bp.Name != "unrecovered-panic" {
1875
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1876 1877 1878
		}
	})
}
1879

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

1897
	expectPanic := func(p proc.Process, fixture protest.Fixture) {
1898
		proc.Continue(p)
1899
		bp, _, _ := p.CurrentThread().Breakpoint()
1900
		if bp == nil || bp.Name != "unrecovered-panic" {
1901
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1902 1903 1904 1905
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
E
Evgeny L 已提交
1906
	withTestProcessArgs("testargs", t, ".", expectSuccess, []string{"test"})
1907
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"-test"})
E
Evgeny L 已提交
1908
	withTestProcessArgs("testargs", t, ".", expectSuccess, []string{"test", "pass flag"})
1909
	// check that arguments with spaces are *only* passed correctly when correctly called
E
Evgeny L 已提交
1910 1911 1912
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test pass", "flag"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test", "pass", "flag"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test pass flag"})
1913 1914
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
E
Evgeny L 已提交
1915 1916 1917
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"invalid"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test", "invalid"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"invalid", "pass flag"})
1918 1919
}

1920 1921 1922 1923 1924
func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
1925
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
		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()
		}()

1940 1941
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
1942 1943 1944
		assertNoError(err, t, "Stacktrace()")
	})
}
1945

1946
func TestNextParked(t *testing.T) {
1947
	protest.AllowRecording(t)
1948
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1949 1950 1951 1952
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1953
		var parkedg *proc.G
1954
		for parkedg == nil {
1955 1956
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
1957 1958 1959 1960 1961
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1962
			gs, err := proc.GoroutinesInfo(p)
1963 1964
			assertNoError(err, t, "GoroutinesInfo()")

1965 1966 1967 1968
			// 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
1969
			for _, g := range gs {
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
				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
1983 1984 1985 1986 1987 1988
				}
			}
		}

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

1991 1992
		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)
1993 1994 1995
		}
	})
}
1996 1997

func TestStepParked(t *testing.T) {
1998
	protest.AllowRecording(t)
1999
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
2000 2001 2002 2003
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
2004
		var parkedg *proc.G
2005 2006
	LookForParkedG:
		for {
2007 2008
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
2009 2010 2011 2012 2013
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

2014
			gs, err := proc.GoroutinesInfo(p)
2015 2016 2017
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
2018
				if g.Thread == nil && g.CurrentLoc.Fn != nil && g.CurrentLoc.Fn.Name == "main.sayhi" {
2019 2020 2021 2022 2023 2024
					parkedg = g
					break LookForParkedG
				}
			}
		}

A
aarzilli 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
		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)
		}

2035 2036
		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
2037
		assertNoError(proc.Step(p), t, "Step()")
2038

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

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")
2052
	_, err := native.Launch([]string{exepath}, ".")
2053 2054 2055
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
2056 2057
	if err != proc.NotExecutableErr {
		t.Fatalf("expected error \"%v\" got \"%v\"", proc.NotExecutableErr, err)
2058 2059 2060 2061 2062
	}
	os.Remove(exepath)
}

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

2069 2070 2071
	fixturesDir := protest.FindFixturesDir()
	infile := filepath.Join(fixturesDir, "math.go")
	outfile := filepath.Join(fixturesDir, "_math_debug_386")
2072

2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
	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)
2085

2086
	p, err := native.Launch([]string{outfile}, ".")
2087
	switch err {
2088
	case proc.UnsupportedLinuxArchErr, proc.UnsupportedWindowsArchErr, proc.UnsupportedDarwinArchErr:
2089 2090 2091 2092 2093 2094 2095 2096 2097
		// all good
	case nil:
		p.Halt()
		p.Kill()
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
2098

2099
func TestIssue573(t *testing.T) {
2100
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
2101
	// of the function and the internal breakpoint set by StepInto may be missed.
2102
	protest.AllowRecording(t)
2103
	withTestProcess("issue573", t, func(p proc.Process, fixture protest.Fixture) {
2104
		fentry, _ := proc.FindFunctionLocation(p, "main.foo", false, 0)
2105
		_, err := p.SetBreakpoint(fentry, proc.UserBreakpoint, nil)
2106
		assertNoError(err, t, "SetBreakpoint()")
2107 2108 2109 2110
		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.
2111 2112
	})
}
2113 2114

func TestTestvariables2Prologue(t *testing.T) {
2115
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2116
		addrEntry, err := proc.FindFunctionLocation(p, "main.main", false, 0)
2117
		assertNoError(err, t, "FindFunctionLocation - entrypoint")
2118
		addrPrologue, err := proc.FindFunctionLocation(p, "main.main", true, 0)
2119 2120 2121 2122 2123 2124
		assertNoError(err, t, "FindFunctionLocation - postprologue")
		if addrEntry == addrPrologue {
			t.Fatalf("Prologue detection failed on testvariables2.go/main.main")
		}
	})
}
2125 2126 2127 2128 2129

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 已提交
2130
	testseq("defercall", contNext, []nextTest{
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
		{9, 10},
		{10, 11},
		{11, 12},
		{12, 13},
		{13, 5},
		{5, 6},
		{6, 7},
		{7, 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 已提交
2146
	testseq("defercall", contNext, []nextTest{
2147 2148 2149 2150 2151
		{15, 16},
		{16, 17},
		{17, 18},
		{18, 5}}, "main.callAndPanic2", t)
}
A
aarzilli 已提交
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172

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.
2173 2174
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
		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 已提交
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
}

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)
2216
	ver, _ := goversion.Parse(runtime.Version())
A
aarzilli 已提交
2217

2218
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
A
aarzilli 已提交
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
		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.
2239
	protest.AllowRecording(t)
2240
	withTestProcess("issue561", t, func(p proc.Process, fixture protest.Fixture) {
2241
		setFileBreakpoint(p, t, fixture, 10)
2242 2243
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2244 2245 2246 2247 2248 2249 2250
		_, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number after Step, expected 5 got %d", ln)
		}
	})
}

A
aarzilli 已提交
2251
func TestStepOut(t *testing.T) {
2252
	protest.AllowRecording(t)
2253
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2254 2255
		bp, err := setFunctionBreakpoint(p, "main.helloworld")
		assertNoError(err, t, "SetBreakpoint()")
2256
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2257 2258 2259 2260 2261 2262 2263
		p.ClearBreakpoint(bp.Addr)

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

2264
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2265 2266 2267

		f, lno = currentLineNumber(p, t)
		if lno != 35 {
2268
			t.Fatalf("wrong line number %s:%d, expected %d", f, lno, 35)
A
aarzilli 已提交
2269 2270 2271 2272
		}
	})
}

A
aarzilli 已提交
2273
func TestStepConcurrentDirect(t *testing.T) {
2274
	protest.AllowRecording(t)
2275
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2276
		pc, err := proc.FindFileLocation(p, fixture.Source, 37)
A
aarzilli 已提交
2277
		assertNoError(err, t, "FindFileLocation()")
2278
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2279 2280
		assertNoError(err, t, "SetBreakpoint()")

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

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

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

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

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

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

2339
func nextInProgress(p proc.Process) bool {
2340
	for _, bp := range p.Breakpoints() {
2341
		if bp.Internal() {
A
aarzilli 已提交
2342 2343 2344 2345 2346 2347 2348
			return true
		}
	}
	return false
}

func TestStepConcurrentPtr(t *testing.T) {
2349
	protest.AllowRecording(t)
2350
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2351
		pc, err := proc.FindFileLocation(p, fixture.Source, 24)
A
aarzilli 已提交
2352
		assertNoError(err, t, "FindFileLocation()")
2353
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2354 2355
		assertNoError(err, t, "SetBreakpoint()")

A
aarzilli 已提交
2356 2357 2358 2359 2360 2361 2362 2363
		for _, b := range p.Breakpoints() {
			if b.Name == "unrecovered-panic" {
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2364 2365 2366
		kvals := map[int]int64{}
		count := 0
		for {
2367 2368
			err := proc.Continue(p)
			_, exited := err.(proc.ProcessExitedError)
A
aarzilli 已提交
2369 2370 2371 2372 2373 2374 2375
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
2376 2377 2378
				for _, th := range p.ThreadList() {
					bp, bpactive, bperr := th.Breakpoint()
					t.Logf("thread %d stopped on breakpoint %v %v %v", th.ThreadID(), bp, bpactive, bperr)
A
aarzilli 已提交
2379
				}
2380 2381
				curbp, _, _ := p.CurrentThread().Breakpoint()
				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 已提交
2382 2383
			}

2384
			gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2385 2386 2387 2388 2389 2390 2391

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

			if oldk, ok := kvals[gid]; ok {
				if oldk >= k {
2392
					t.Fatalf("Goroutine %d did not make progress?", gid)
A
aarzilli 已提交
2393 2394 2395 2396
				}
			}
			kvals[gid] = k

2397
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2398
			for nextInProgress(p) {
2399 2400
				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 已提交
2401
				}
2402
				assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2403 2404
			}

2405 2406
			if p.SelectedGoroutine().ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2407 2408
			}

2409 2410 2411
			f, ln = currentLineNumber(p, t)
			if ln != 13 {
				t.Fatalf("Step did not step into function call (13): %s:%d", f, ln)
A
aarzilli 已提交
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
			}

			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 已提交
2428
func TestStepOutDefer(t *testing.T) {
2429
	protest.AllowRecording(t)
2430
	withTestProcess("testnextdefer", t, func(p proc.Process, fixture protest.Fixture) {
2431
		pc, err := proc.FindFileLocation(p, fixture.Source, 9)
A
aarzilli 已提交
2432
		assertNoError(err, t, "FindFileLocation()")
2433
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2434
		assertNoError(err, t, "SetBreakpoint()")
2435
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2436 2437 2438 2439 2440 2441 2442
		p.ClearBreakpoint(bp.Addr)

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

2443
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2444

2445
		f, l, _ := p.BinInfo().PCToLine(currentPC(p, t))
A
aarzilli 已提交
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
		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
2456
	protest.AllowRecording(t)
2457
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2458
		bp := setFileBreakpoint(p, t, fixture, 11)
2459
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2460 2461
		p.ClearBreakpoint(bp.Addr)

2462
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2463 2464 2465 2466 2467 2468 2469 2470

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

2471 2472
const maxInstructionLength uint64 = 15

A
aarzilli 已提交
2473
func TestStepOnCallPtrInstr(t *testing.T) {
2474
	protest.AllowRecording(t)
2475
	withTestProcess("teststepprog", t, func(p proc.Process, fixture protest.Fixture) {
2476
		pc, err := proc.FindFileLocation(p, fixture.Source, 10)
A
aarzilli 已提交
2477
		assertNoError(err, t, "FindFileLocation()")
2478
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2479 2480
		assertNoError(err, t, "SetBreakpoint()")

2481
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2482 2483 2484 2485 2486 2487 2488 2489

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
2490
			regs, err := p.CurrentThread().Registers(false)
2491
			assertNoError(err, t, "Registers()")
2492
			pc := regs.PC()
2493
			text, err := proc.Disassemble(p, nil, pc, pc+maxInstructionLength)
A
aarzilli 已提交
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
			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")
		}

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

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

func TestIssue594(t *testing.T) {
2516 2517 2518 2519 2520 2521 2522 2523
	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
	}
2524 2525 2526 2527
	// 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.
2528
	protest.AllowRecording(t)
2529
	withTestProcess("issue594", t, func(p proc.Process, fixture protest.Fixture) {
2530
		assertNoError(proc.Continue(p), t, "Continue()")
2531 2532 2533 2534 2535 2536 2537 2538 2539
		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)
		}
2540 2541 2542 2543 2544
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2545 2546 2547 2548 2549

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
2550
	protest.AllowRecording(t)
2551
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2552
		bp := setFileBreakpoint(p, t, fixture, 17)
2553
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2554 2555
		p.ClearBreakpoint(bp.Addr)

2556
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2557 2558 2559 2560 2561 2562 2563

		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number, expected %d got %s:%d", 5, f, ln)
		}
	})
}
E
Evgeny L 已提交
2564 2565 2566 2567 2568 2569 2570

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"
	}
2571
	protest.AllowRecording(t)
2572
	withTestProcessArgs("workdir", t, wd, func(p proc.Process, fixture protest.Fixture) {
2573
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 14)
E
Evgeny L 已提交
2574
		assertNoError(err, t, "LineToPC")
2575 2576
		p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
		proc.Continue(p)
E
Evgeny L 已提交
2577 2578 2579 2580 2581 2582 2583 2584
		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)
		}
	}, []string{})
}
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595

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)},
	}
2596
	protest.AllowRecording(t)
2597
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2598
		assertNoError(proc.Continue(p), t, "Continue()")
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
		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)
			}
		}
	})
}
2611 2612 2613

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
2614
	protest.AllowRecording(t)
2615
	withTestProcess("issue683", t, func(p proc.Process, fixture protest.Fixture) {
2616 2617
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
2618
		assertNoError(proc.Continue(p), t, "First Continue()")
2619 2620 2621
		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
2622
			err := proc.Step(p)
2623 2624 2625 2626
			if err != nil {
				break
			}
		}
2627 2628 2629 2630
	})
}

func TestIssue664(t *testing.T) {
2631
	protest.AllowRecording(t)
2632
	withTestProcess("issue664", t, func(p proc.Process, fixture protest.Fixture) {
2633
		setFileBreakpoint(p, t, fixture, 4)
2634 2635
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
2636 2637 2638
		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("Did not continue to line 5: %s:%d", f, ln)
2639 2640 2641
		}
	})
}
A
Alessandro Arzilli 已提交
2642 2643 2644

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

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.
2666
	protest.AllowRecording(t)
2667
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2668 2669
		_, err := setFunctionBreakpoint(p, "runtime.deferreturn")
		assertNoError(err, t, "setFunctionBreakpoint()")
2670
		assertNoError(proc.Continue(p), t, "First Continue()")
A
Alessandro Arzilli 已提交
2671
		for i := 0; i < 20; i++ {
2672
			assertNoError(proc.Next(p), t, fmt.Sprintf("Next() %d", i))
A
Alessandro Arzilli 已提交
2673 2674 2675 2676
		}
	})
}

2677
func getg(goid int, gs []*proc.G) *proc.G {
A
Alessandro Arzilli 已提交
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691
	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.
2692

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

2698 2699 2700 2701 2702
	// 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")

2703
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2704 2705 2706 2707 2708
		// 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 {
2709 2710
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
2711 2712 2713 2714
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
2715
			gs, err := proc.GoroutinesInfo(p)
A
Alessandro Arzilli 已提交
2716
			assertNoError(err, t, "GoroutinesInfo()")
2717 2718
			for _, th := range p.ThreadList() {
				if bp, _, _ := th.Breakpoint(); bp == nil {
A
Alessandro Arzilli 已提交
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
					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)

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

2747
		gs, err := proc.GoroutinesInfo(p)
A
Alessandro Arzilli 已提交
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
		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
				}
				t.Logf("\t%s [CFA: %x Ret: %x] at %s:%d", name, frame.CFA, frame.Ret, frame.Current.File, frame.Current.Line)
			}

			if !found {
2780
				t.Logf("Truncated stacktrace for %d\n", goid)
A
Alessandro Arzilli 已提交
2781 2782 2783 2784
			}
		}
	})
}
2785 2786

func TestAttachDetach(t *testing.T) {
2787 2788 2789 2790 2791 2792
	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
		}
2793
	}
2794 2795 2796
	if testBackend == "rr" {
		return
	}
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
	fixture := protest.BuildFixture("testnextnethttp")
	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")
		}
	}

2817
	var p proc.Process
2818 2819 2820 2821
	var err error

	switch testBackend {
	case "native":
2822
		p, err = native.Attach(cmd.Process.Pid)
2823 2824 2825 2826 2827
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
2828
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path)
2829 2830 2831 2832
	default:
		err = fmt.Errorf("unknown backend %q", testBackend)
	}

2833 2834 2835 2836 2837 2838
	assertNoError(err, t, "Attach")
	go func() {
		time.Sleep(1 * time.Second)
		http.Get("http://localhost:9191")
	}()

2839
	assertNoError(proc.Continue(p), t, "Continue")
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851

	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")
2852
	if out := string(bs); !strings.Contains(out, "hello, world!") {
2853 2854 2855 2856 2857
		t.Fatalf("/nobp page does not contain \"hello, world!\": %q", out)
	}

	cmd.Process.Kill()
}
2858 2859

func TestVarSum(t *testing.T) {
2860
	protest.AllowRecording(t)
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
	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) {
2876
	protest.AllowRecording(t)
2877 2878 2879 2880 2881 2882 2883 2884
	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)")
	})
}
2885 2886

func TestEnvironment(t *testing.T) {
2887
	protest.AllowRecording(t)
2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
	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)
		}
	})
}
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952

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)
		}
	})
}
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972

// 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)
		}
	})
}
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986

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
		}
2987 2988 2989
		if _, ok := err.(proc.ThreadBlockedError); ok {
			return
		}
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001
		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")
	})
}
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 3042 3043 3044 3045 3046 3047

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 已提交
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

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