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

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

22 23 24
	"github.com/derekparker/delve/pkg/proc"
	"github.com/derekparker/delve/pkg/proc/gdbserial"
	"github.com/derekparker/delve/pkg/proc/native"
D
Derek Parker 已提交
25
	protest "github.com/derekparker/delve/pkg/proc/test"
D
Derek Parker 已提交
26
)
27

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

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

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

48
func withTestProcess(name string, t testing.TB, fn func(p proc.Process, fixture protest.Fixture)) {
49
	fixture := protest.BuildFixture(name)
50
	var p proc.Process
51 52 53
	var err error
	switch testBackend {
	case "native":
54
		p, err = native.Launch([]string{fixture.Path}, ".")
55
	case "lldb":
56
		p, err = gdbserial.LLDBLaunch([]string{fixture.Path}, ".")
57 58 59
	default:
		t.Fatalf("unknown backend %q", testBackend)
	}
60 61 62 63
	if err != nil {
		t.Fatal("Launch():", err)
	}

64 65
	defer func() {
		p.Halt()
66
		p.Detach(true)
67
	}()
68

D
Dan Mace 已提交
69
	fn(p, fixture)
70 71
}

72
func withTestProcessArgs(name string, t testing.TB, wd string, fn func(p proc.Process, fixture protest.Fixture), args []string) {
73
	fixture := protest.BuildFixture(name)
74
	var p proc.Process
75 76 77 78
	var err error

	switch testBackend {
	case "native":
79
		p, err = native.Launch(append([]string{fixture.Path}, args...), wd)
80
	case "lldb":
81
		p, err = gdbserial.LLDBLaunch(append([]string{fixture.Path}, args...), wd)
82 83 84
	default:
		t.Fatal("unknown backend")
	}
85 86 87 88 89 90
	if err != nil {
		t.Fatal("Launch():", err)
	}

	defer func() {
		p.Halt()
91
		p.Detach(true)
92 93 94 95 96
	}()

	fn(p, fixture)
}

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

	return regs
}

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

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

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

126
	return regs.PC()
127 128
}

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

135
func TestExit(t *testing.T) {
136
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
137 138
		err := proc.Continue(p)
		pe, ok := err.(proc.ProcessExitedError)
139
		if !ok {
140
			t.Fatalf("Continue() returned unexpected error type %s", err)
141 142 143 144
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
145
		if pe.Pid != p.Pid() {
146 147 148 149 150
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

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

170
func setFunctionBreakpoint(p proc.Process, fname string) (*proc.Breakpoint, error) {
171 172 173 174
	addr, err := p.FindFunctionLocation(fname, true, 0)
	if err != nil {
		return nil, err
	}
175
	return p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
176 177
}

178
func setFileBreakpoint(p proc.Process, t *testing.T, fixture protest.Fixture, lineno int) *proc.Breakpoint {
A
aarzilli 已提交
179 180 181 182
	addr, err := p.FindFileLocation(fixture.Source, lineno)
	if err != nil {
		t.Fatalf("FindFileLocation: %v", err)
	}
183
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
A
aarzilli 已提交
184 185 186 187 188 189
	if err != nil {
		t.Fatalf("SetBreakpoint: %v", err)
	}
	return bp
}

D
Derek Parker 已提交
190
func TestHalt(t *testing.T) {
191
	stopChan := make(chan interface{})
192
	withTestProcess("loopprog", t, func(p proc.Process, fixture protest.Fixture) {
193
		_, err := setFunctionBreakpoint(p, "main.loop")
194
		assertNoError(err, t, "SetBreakpoint")
195
		assertNoError(proc.Continue(p), t, "Continue")
196 197 198
		if p.Running() {
			t.Fatal("process still running")
		}
199 200
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
201 202
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
203 204
			}
		}
D
Derek Parker 已提交
205
		go func() {
D
Dan Mace 已提交
206
			for {
207
				time.Sleep(100 * time.Millisecond)
D
Dan Mace 已提交
208
				if p.Running() {
209
					if err := p.RequestManualStop(); err != nil {
D
Dan Mace 已提交
210 211
						t.Fatal(err)
					}
212
					stopChan <- nil
D
Dan Mace 已提交
213 214
					return
				}
D
Derek Parker 已提交
215 216
			}
		}()
217
		assertNoError(proc.Continue(p), t, "Continue")
218
		<-stopChan
D
Derek Parker 已提交
219 220 221
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
222 223 224 225 226 227
		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")
					}
228 229 230
				}
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
D
Derek Parker 已提交
231 232 233 234 235
			}
		}
	})
}

236
func TestStep(t *testing.T) {
237
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
238 239
		helloworldaddr, err := p.FindFunctionLocation("main.helloworld", false, 0)
		assertNoError(err, t, "FindFunctionLocation")
240

241
		_, err = p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
242
		assertNoError(err, t, "SetBreakpoint()")
243
		assertNoError(proc.Continue(p), t, "Continue()")
244

245
		regs := getRegisters(p, t)
246
		rip := regs.PC()
247

248
		err = p.CurrentThread().StepInstruction()
D
Derek Parker 已提交
249
		assertNoError(err, t, "Step()")
250

251
		regs = getRegisters(p, t)
252 253 254 255 256
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
257

D
Derek Parker 已提交
258
func TestBreakpoint(t *testing.T) {
259
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
260 261
		helloworldaddr, err := p.FindFunctionLocation("main.helloworld", false, 0)
		assertNoError(err, t, "FindFunctionLocation")
262

263
		bp, err := p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
264
		assertNoError(err, t, "SetBreakpoint()")
265
		assertNoError(proc.Continue(p), t, "Continue()")
266

267 268 269
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
270

271 272 273 274
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
275
		if pc-1 != bp.Addr && pc != bp.Addr {
276
			f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
277
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
278 279
		}
	})
280
}
281

D
Derek Parker 已提交
282
func TestBreakpointInSeperateGoRoutine(t *testing.T) {
283
	withTestProcess("testthreads", t, func(p proc.Process, fixture protest.Fixture) {
284 285
		fnentry, err := p.FindFunctionLocation("main.anotherthread", false, 0)
		assertNoError(err, t, "FindFunctionLocation")
286

287
		_, err = p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
288
		assertNoError(err, t, "SetBreakpoint")
289

290
		assertNoError(proc.Continue(p), t, "Continue")
291

292 293 294
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
295

296
		f, l, _ := p.BinInfo().PCToLine(pc)
297 298 299 300 301 302
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
303
func TestBreakpointWithNonExistantFunction(t *testing.T) {
304
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
305
		_, err := p.SetBreakpoint(0, proc.UserBreakpoint, nil)
306 307 308 309
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
310
}
311

312
func TestClearBreakpointBreakpoint(t *testing.T) {
313
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
314 315
		fnentry, err := p.FindFunctionLocation("main.sleepytime", false, 0)
		assertNoError(err, t, "FindFunctionLocation")
316
		bp, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
317
		assertNoError(err, t, "SetBreakpoint()")
318

319
		bp, err = p.ClearBreakpoint(fnentry)
320
		assertNoError(err, t, "ClearBreakpoint()")
321

322 323
		data, err := dataAtAddr(p.CurrentThread(), bp.Addr)
		assertNoError(err, t, "dataAtAddr")
324

325
		int3 := []byte{0xcc}
326 327 328 329
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

330
		if countBreakpoints(p) != 0 {
331 332 333
			t.Fatal("Breakpoint not removed internally")
		}
	})
334
}
335

336 337 338
type nextTest struct {
	begin, end int
}
339

340
func countBreakpoints(p proc.Process) int {
341
	bpcount := 0
342
	for _, bp := range p.Breakpoints() {
343 344 345 346 347 348 349
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

A
aarzilli 已提交
350 351 352 353 354 355 356 357
type contFunc int

const (
	contNext contFunc = iota
	contStep
)

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

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

A
aarzilli 已提交
384 385
			switch contFunc {
			case contNext:
386
				assertNoError(proc.Next(p), t, "Next() returned an error")
A
aarzilli 已提交
387
			case contStep:
388
				assertNoError(proc.Step(p), t, "Step() returned an error")
A
aarzilli 已提交
389
			}
390

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

399
		if countBreakpoints(p) != 0 {
400
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints()))
401
		}
402 403
	})
}
404

405
func TestNextGeneral(t *testing.T) {
406 407
	var testcases []nextTest

408
	ver, _ := proc.ParseVersionString(runtime.Version())
409

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

A
aarzilli 已提交
449
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
450 451
}

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

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

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

func TestNextFunctionReturnDefer(t *testing.T) {
	testcases := []nextTest{
553
		{5, 8},
D
Derek Parker 已提交
554 555
		{8, 9},
		{9, 10},
556 557
		{10, 6},
		{6, 7},
D
Derek Parker 已提交
558
		{7, 8},
559
	}
A
aarzilli 已提交
560
	testseq("testnextdefer", contNext, testcases, "main.main", t)
561 562
}

D
Derek Parker 已提交
563 564 565 566 567
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
568
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
569 570 571 572 573 574
		go func() {
			for !p.Running() {
				time.Sleep(50 * time.Millisecond)
			}
			// Wait for program to start listening.
			for {
L
Luke Hoban 已提交
575
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
576 577 578 579 580 581
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
582
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
583
		}()
584
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
585 586 587 588 589 590 591 592
			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)
			}

593
			assertNoError(proc.Next(p), t, "Next() returned an error")
D
Derek Parker 已提交
594 595 596 597 598 599 600 601 602

			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 已提交
603
func TestRuntimeBreakpoint(t *testing.T) {
604
	withTestProcess("testruntimebreakpoint", t, func(p proc.Process, fixture protest.Fixture) {
605
		err := proc.Continue(p)
D
Derek Parker 已提交
606 607 608
		if err != nil {
			t.Fatal(err)
		}
609 610 611
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
612
		_, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
613 614 615 616 617 618
		if l != 10 {
			t.Fatal("did not respect breakpoint")
		}
	})
}

619
func returnAddress(thread proc.Thread) (uint64, error) {
620
	locations, err := proc.ThreadStacktrace(thread, 2)
621 622 623 624
	if err != nil {
		return 0, err
	}
	if len(locations) < 2 {
625
		return 0, proc.NoReturnAddr{locations[0].Current.Fn.BaseName()}
626 627 628 629
	}
	return locations[1].Current.PC, nil
}

630
func TestFindReturnAddress(t *testing.T) {
631
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
632
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 24)
633 634 635
		if err != nil {
			t.Fatal(err)
		}
636
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
637 638 639
		if err != nil {
			t.Fatal(err)
		}
640
		err = proc.Continue(p)
641 642 643
		if err != nil {
			t.Fatal(err)
		}
644
		addr, err := returnAddress(p.CurrentThread())
645 646 647
		if err != nil {
			t.Fatal(err)
		}
648
		_, l, _ := p.BinInfo().PCToLine(addr)
649 650
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
651
		}
652 653
	})
}
654

655
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
656
	withTestProcess("testreturnaddress", t, func(p proc.Process, fixture protest.Fixture) {
657
		fnName := "runtime.rt0_go"
658 659
		fnentry, err := p.FindFunctionLocation(fnName, false, 0)
		assertNoError(err, t, "FindFunctionLocation")
660
		if _, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil); err != nil {
661 662
			t.Fatal(err)
		}
663
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
664 665
			t.Fatal(err)
		}
666
		if _, err := returnAddress(p.CurrentThread()); err == nil {
667
			t.Fatal("expected error to be returned")
668 669 670
		}
	})
}
D
Derek Parker 已提交
671 672

func TestSwitchThread(t *testing.T) {
673
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
674 675 676 677 678
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
679
		pc, err := p.FindFunctionLocation("main.main", true, 0)
D
Derek Parker 已提交
680 681 682
		if err != nil {
			t.Fatal(err)
		}
683
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
D
Derek Parker 已提交
684 685 686
		if err != nil {
			t.Fatal(err)
		}
687
		err = proc.Continue(p)
D
Derek Parker 已提交
688 689 690 691
		if err != nil {
			t.Fatal(err)
		}
		var nt int
692 693 694 695
		ct := p.CurrentThread().ThreadID()
		for _, thread := range p.ThreadList() {
			if thread.ThreadID() != ct {
				nt = thread.ThreadID()
D
Derek Parker 已提交
696 697 698 699 700 701 702 703 704 705 706
				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)
		}
707
		if p.CurrentThread().ThreadID() != nt {
D
Derek Parker 已提交
708 709 710 711
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
712

713 714 715 716 717 718
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 已提交
719 720 721
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
722

723
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
724 725 726 727
		pc, err := p.FindFunctionLocation("main.main", true, 0)
		if err != nil {
			t.Fatal(err)
		}
728
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
729 730 731
		if err != nil {
			t.Fatal(err)
		}
732
		err = proc.Continue(p)
733 734 735
		if err != nil {
			t.Fatal(err)
		}
736
		err = proc.Next(p)
737 738 739 740 741 742
		if err != nil {
			t.Fatal(err)
		}
	})
}

A
aarzilli 已提交
743 744 745 746 747
type loc struct {
	line int
	fn   string
}

748
func (l1 *loc) match(l2 proc.Stackframe) bool {
A
aarzilli 已提交
749
	if l1.line >= 0 {
750
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
751 752 753
			return false
		}
	}
754
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
755 756 757 758
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
759 760
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
761
	}
762
	withTestProcess("stacktraceprog", t, func(p proc.Process, fixture protest.Fixture) {
763
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
764 765 766
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
767 768
			assertNoError(proc.Continue(p), t, "Continue()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
A
aarzilli 已提交
769 770 771 772 773 774
			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)
			}

775 776 777 778
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
779

A
aarzilli 已提交
780 781 782 783 784 785 786
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

787
		p.ClearBreakpoint(bp.Addr)
788
		proc.Continue(p)
A
aarzilli 已提交
789 790 791
	})
}

792
func TestStacktrace2(t *testing.T) {
793
	withTestProcess("retstack", t, func(p proc.Process, fixture protest.Fixture) {
794
		assertNoError(proc.Continue(p), t, "Continue()")
795

796
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
797
		assertNoError(err, t, "Stacktrace()")
798
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
799 800 801
			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 已提交
802
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
803 804
		}

805 806
		assertNoError(proc.Continue(p), t, "Continue()")
		locations, err = proc.ThreadStacktrace(p.CurrentThread(), 40)
807
		assertNoError(err, t, "Stacktrace()")
808
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
809 810 811
			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 已提交
812
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
813 814 815 816 817
		}
	})

}

818
func stackMatch(stack []loc, locations []proc.Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
819 820 821
	if len(stack) > len(locations) {
		return false
	}
822 823 824 825 826 827 828 829 830 831 832
	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 已提交
833 834
			return false
		}
835
		i++
A
aarzilli 已提交
836
	}
837
	return i >= len(stack)
A
aarzilli 已提交
838 839 840
}

func TestStacktraceGoroutine(t *testing.T) {
841
	mainStack := []loc{{13, "main.stacktraceme"}, {26, "main.main"}}
842
	agoroutineStacks := [][]loc{[]loc{{8, "main.agoroutine"}}, []loc{{9, "main.agoroutine"}}, []loc{{10, "main.agoroutine"}}}
A
aarzilli 已提交
843

844
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
845
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
846 847
		assertNoError(err, t, "BreakByLocation()")

848
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
849

850
		gs, err := proc.GoroutinesInfo(p)
A
aarzilli 已提交
851 852 853 854 855
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
856
		for i, g := range gs {
A
aarzilli 已提交
857
			locations, err := g.Stacktrace(40)
858 859
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
860
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
861 862
				continue
			}
A
aarzilli 已提交
863

864
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
865 866 867
				mainCount++
			}

868 869 870 871 872 873 874 875
			found := false
			for _, agoroutineStack := range agoroutineStacks {
				if stackMatch(agoroutineStack, locations, true) {
					found = true
				}
			}

			if found {
A
aarzilli 已提交
876 877
				agoroutineCount++
			} else {
D
Derek Parker 已提交
878
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
879 880
				for i := range locations {
					name := ""
881 882
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
883
					}
884
					t.Logf("\t%s:%d %s\n", locations[i].Call.File, locations[i].Call.Line, name)
A
aarzilli 已提交
885 886 887 888 889
				}
			}
		}

		if mainCount != 1 {
890
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
891 892 893 894 895 896
		}

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

897
		p.ClearBreakpoint(bp.Addr)
898
		proc.Continue(p)
A
aarzilli 已提交
899 900
	})
}
901 902

func TestKill(t *testing.T) {
903 904 905 906
	if testBackend == "lldb" {
		// k command presumably works but leaves the process around?
		return
	}
907
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
908 909 910 911 912 913 914
		if err := p.Kill(); err != nil {
			t.Fatal(err)
		}
		if p.Exited() != true {
			t.Fatal("expected process to have exited")
		}
		if runtime.GOOS == "linux" {
915
			_, err := os.Open(fmt.Sprintf("/proc/%d/", p.Pid()))
916
			if err == nil {
917
				t.Fatal("process has not exited", p.Pid())
918 919 920 921
			}
		}
	})
}
922

923
func testGSupportFunc(name string, t *testing.T, p proc.Process, fixture protest.Fixture) {
924
	bp, err := setFunctionBreakpoint(p, "main.main")
925 926
	assertNoError(err, t, name+": BreakByLocation()")

927
	assertNoError(proc.Continue(p), t, name+": Continue()")
928

929
	g, err := proc.GetG(p.CurrentThread())
930 931 932 933 934 935 936 937 938 939 940 941
	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) {
942
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
943 944 945
		testGSupportFunc("nocgo", t, p, fixture)
	})

946 947 948 949
	// 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 已提交
950 951 952
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
953

954
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
955 956 957
		testGSupportFunc("cgo", t, p, fixture)
	})
}
958 959

func TestContinueMulti(t *testing.T) {
960
	withTestProcess("integrationprog", t, func(p proc.Process, fixture protest.Fixture) {
961
		bp1, err := setFunctionBreakpoint(p, "main.main")
962 963
		assertNoError(err, t, "BreakByLocation()")

964
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
965 966 967 968 969
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
970
			err := proc.Continue(p)
971
			if p.Exited() {
972 973 974 975
				break
			}
			assertNoError(err, t, "Continue()")

976
			if bp, _, _ := p.CurrentThread().Breakpoint(); bp.ID == bp1.ID {
977 978 979
				mainCount++
			}

980
			if bp, _, _ := p.CurrentThread().Breakpoint(); bp.ID == bp2.ID {
981 982 983 984 985 986 987 988 989 990 991 992 993
				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)
		}
	})
}
994

995 996
func versionAfterOrEqual(t *testing.T, verStr string, ver proc.GoVersion) {
	pver, ok := proc.ParseVersionString(verStr)
997 998 999
	if !ok {
		t.Fatalf("Could not parse version string <%s>", verStr)
	}
1000
	if !pver.AfterOrEqual(ver) {
1001 1002 1003 1004 1005 1006
		t.Fatalf("Version <%s> parsed as %v not after %v", verStr, pver, ver)
	}
	t.Logf("version string <%s> → %v", verStr, ver)
}

func TestParseVersionString(t *testing.T) {
1007 1008 1009 1010 1011 1012 1013
	versionAfterOrEqual(t, "go1.4", proc.GoVersion{1, 4, 0, 0, 0})
	versionAfterOrEqual(t, "go1.5.0", proc.GoVersion{1, 5, 0, 0, 0})
	versionAfterOrEqual(t, "go1.4.2", proc.GoVersion{1, 4, 2, 0, 0})
	versionAfterOrEqual(t, "go1.5beta2", proc.GoVersion{1, 5, -1, 2, 0})
	versionAfterOrEqual(t, "go1.5rc2", proc.GoVersion{1, 5, -1, 0, 2})
	versionAfterOrEqual(t, "go1.6.1 (appengine-1.9.37)", proc.GoVersion{1, 6, 1, 0, 0})
	ver, ok := proc.ParseVersionString("devel +17efbfc Tue Jul 28 17:39:19 2015 +0000 linux/amd64")
1014 1015 1016 1017 1018 1019 1020
	if !ok {
		t.Fatalf("Could not parse devel version string")
	}
	if !ver.IsDevel() {
		t.Fatalf("Devel version string not correctly recognized")
	}
}
1021 1022

func TestBreakpointOnFunctionEntry(t *testing.T) {
1023
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
1024 1025
		addr, err := p.FindFunctionLocation("main.main", false, 0)
		assertNoError(err, t, "FindFunctionLocation()")
1026
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1027
		assertNoError(err, t, "SetBreakpoint()")
1028
		assertNoError(proc.Continue(p), t, "Continue()")
1029 1030 1031 1032 1033 1034
		_, ln := currentLineNumber(p, t)
		if ln != 17 {
			t.Fatalf("Wrong line number: %d (expected: 17)\n", ln)
		}
	})
}
1035 1036

func TestProcessReceivesSIGCHLD(t *testing.T) {
1037
	withTestProcess("sigchldprog", t, func(p proc.Process, fixture protest.Fixture) {
1038 1039
		err := proc.Continue(p)
		_, ok := err.(proc.ProcessExitedError)
1040
		if !ok {
1041
			t.Fatalf("Continue() returned unexpected error type %v", err)
1042 1043 1044
		}
	})
}
1045 1046

func TestIssue239(t *testing.T) {
1047
	withTestProcess("is sue239", t, func(p proc.Process, fixture protest.Fixture) {
1048
		pos, _, err := p.BinInfo().LineToPC(fixture.Source, 17)
1049
		assertNoError(err, t, "LineToPC()")
1050
		_, err = p.SetBreakpoint(pos, proc.UserBreakpoint, nil)
1051
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
1052
		assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue()"))
1053 1054
	})
}
1055

1056
func evalVariable(p proc.Process, symbol string) (*proc.Variable, error) {
1057
	scope, err := proc.GoroutineScope(p.CurrentThread())
1058

1059 1060 1061
	if err != nil {
		return nil, err
	}
1062
	return scope.EvalVariable(symbol, normalLoadConfig)
1063 1064
}

1065
func setVariable(p proc.Process, symbol, value string) error {
1066
	scope, err := proc.GoroutineScope(p.CurrentThread())
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
	if err != nil {
		return err
	}
	return scope.SetVariable(symbol, value)
}

func TestVariableEvaluation(t *testing.T) {
	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 已提交
1096 1097
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
		{"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},
	}

1109
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1110
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

		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 {
1122 1123 1124
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1125 1126 1127
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1128 1129
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1130 1131 1132
					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 已提交
1133 1134 1135 1136 1137 1138
				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)
					}
1139 1140
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
						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) {
1159
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
1160 1161
		_, err := setFunctionBreakpoint(p, "main.stacktraceme")
		assertNoError(err, t, "setFunctionBreakpoint")
1162
		assertNoError(proc.Continue(p), t, "Continue()")
1163

1164
		// Testing evaluation on goroutines
1165
		gs, err := proc.GoroutinesInfo(p)
1166 1167 1168 1169
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
A
aarzilli 已提交
1170
			frames, err := g.Stacktrace(10)
1171 1172 1173 1174
			if err != nil {
				t.Logf("could not stacktrace goroutine %d: %v\n", g.ID, err)
				continue
			}
1175 1176 1177 1178 1179 1180 1181 1182
			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 已提交
1183
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1184 1185 1186
				continue
			}

1187
			scope, err := proc.ConvertEvalScope(p, g.ID, frame)
1188 1189
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
1190
			v, err := scope.EvalVariable("i", normalLoadConfig)
1191 1192
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1193
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1194 1195
				continue
			}
1196 1197
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1198 1199 1200 1201 1202 1203 1204 1205
		}

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

1206
		// Testing evaluation on frames
1207 1208
		assertNoError(proc.Continue(p), t, "Continue() 2")
		g, err := proc.GetG(p.CurrentThread())
1209 1210 1211
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
1212
			scope, err := proc.ConvertEvalScope(p, g.ID, i+1)
1213
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
1214
			v, err := scope.EvalVariable("n", normalLoadConfig)
1215
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1216
			n, _ := constant.Int64Val(v.Value)
1217 1218 1219 1220 1221 1222 1223 1224 1225
			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) {
1226
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1227
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1228 1229 1230 1231

		pval := func(n int64) {
			variable, err := evalVariable(p, "p1")
			assertNoError(err, t, "EvalVariable()")
1232 1233 1234
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1235 1236 1237 1238 1239 1240
			}
		}

		pval(1)

		// change p1 to point to i2
1241
		scope, err := proc.GoroutineScope(p.CurrentThread())
1242
		assertNoError(err, t, "Scope()")
1243
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1244 1245
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1246 1247 1248 1249 1250 1251 1252 1253 1254
		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) {
1255
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1256
		err := proc.Continue(p)
1257 1258 1259 1260 1261 1262 1263 1264 1265
		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
1266
		err = proc.Continue(p)
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
		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) {
1280
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1281
		assertNoError(proc.Continue(p), t, "Continue()")
1282 1283 1284 1285 1286
		v, err := evalVariable(p, "aas")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("v: %v\n", v)
	})
}
1287 1288 1289

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1290
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1291
		assertNoError(proc.Continue(p), t, "Continue()")
1292 1293 1294 1295
		_, err := evalVariable(p, "iface5")
		assertNoError(err, t, "EvalVariable()")
	})
}
1296 1297 1298

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1299
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1300
		assertNoError(proc.Continue(p), t, "Continue()")
1301 1302 1303 1304 1305 1306 1307 1308 1309
		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)
	})
}
1310 1311

func TestBreakpointCounts(t *testing.T) {
1312
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1313
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1314
		assertNoError(err, t, "LineToPC")
1315
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1316 1317 1318
		assertNoError(err, t, "SetBreakpoint()")

		for {
1319 1320
			if err := proc.Continue(p); err != nil {
				if _, exited := err.(proc.ProcessExitedError); exited {
1321 1322 1323 1324 1325 1326 1327
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
		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)
			}
		}
	})
}

1344 1345 1346
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
	b.SetBytes(int64(64 * 128))
1347
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1348
		assertNoError(proc.Continue(p), b, "Continue()")
1349 1350 1351 1352 1353 1354 1355
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "bencharr")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

1356 1357 1358 1359 1360 1361 1362
const doTestBreakpointCountsWithDetection = false

func TestBreakpointCountsWithDetection(t *testing.T) {
	if !doTestBreakpointCountsWithDetection {
		return
	}
	m := map[int64]int64{}
1363
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1364
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1365
		assertNoError(err, t, "LineToPC")
1366
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1367 1368 1369
		assertNoError(err, t, "SetBreakpoint()")

		for {
1370 1371
			if err := proc.Continue(p); err != nil {
				if _, exited := err.(proc.ProcessExitedError); exited {
1372 1373 1374 1375
					break
				}
				assertNoError(err, t, "Continue()")
			}
1376 1377
			for _, th := range p.ThreadList() {
				if bp, _, _ := th.Breakpoint(); bp == nil {
1378 1379
					continue
				}
1380
				scope, err := proc.GoroutineScope(th)
1381
				assertNoError(err, t, "Scope()")
1382
				v, err := scope.EvalVariable("i", normalLoadConfig)
1383 1384
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
1385
				v, err = scope.EvalVariable("id", normalLoadConfig)
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
				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)
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
		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)
			}
		}
	})
}
1417

1418 1419 1420 1421
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
	b.SetBytes(int64(64*128 + 64*8))
1422
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1423
		assertNoError(proc.Continue(p), b, "Continue()")
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
		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
	b.SetBytes(int64(41 * (2*8 + 9)))
1436
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1437
		assertNoError(proc.Continue(p), b, "Continue()")
1438 1439 1440 1441 1442 1443 1444 1445
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "m1")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1446
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1447
		assertNoError(proc.Continue(p), b, "Continue()")
1448
		for i := 0; i < b.N; i++ {
1449 1450 1451 1452 1453
			if p, ok := p.(proc.AllGCache); ok {
				allgcache := p.AllGCache()
				*allgcache = nil
			}
			_, err := proc.GoroutinesInfo(p)
1454 1455 1456 1457 1458
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1459 1460
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
1461
	withTestProcess("issue262", t, func(p proc.Process, fixture protest.Fixture) {
1462
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 11)
1463
		assertNoError(err, t, "LineToPC")
1464
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1465 1466
		assertNoError(err, t, "SetBreakpoint()")

1467 1468
		assertNoError(proc.Continue(p), t, "Continue()")
		err = proc.Continue(p)
1469 1470 1471
		if err == nil {
			t.Fatalf("No error on second continue")
		}
1472
		_, exited := err.(proc.ProcessExitedError)
1473 1474 1475 1476 1477
		if !exited {
			t.Fatalf("Process did not exit after second continue: %v", err)
		}
	})
}
1478

1479
func TestIssue305(t *testing.T) {
1480 1481 1482
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1483
	withTestProcess("issue305", t, func(p proc.Process, fixture protest.Fixture) {
1484
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 5)
1485
		assertNoError(err, t, "LineToPC()")
1486
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1487 1488
		assertNoError(err, t, "SetBreakpoint()")

1489
		assertNoError(proc.Continue(p), t, "Continue()")
1490

1491 1492 1493 1494 1495
		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")
1496 1497 1498
	})
}

1499 1500 1501
func TestPointerLoops(t *testing.T) {
	// Pointer loops through map entries, pointers and slices
	// Regression test for issue #341
1502
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1503
		assertNoError(proc.Continue(p), t, "Continue()")
1504 1505 1506 1507 1508 1509
		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)
		}
1510 1511
	})
}
1512 1513

func BenchmarkLocalVariables(b *testing.B) {
1514
	withTestProcess("testvariables", b, func(p proc.Process, fixture protest.Fixture) {
1515 1516
		assertNoError(proc.Continue(p), b, "Continue() returned an error")
		scope, err := proc.GoroutineScope(p.CurrentThread())
1517 1518
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
1519
			_, err := scope.LocalVariables(normalLoadConfig)
1520 1521 1522 1523
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1524 1525

func TestCondBreakpoint(t *testing.T) {
1526
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1527
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1528
		assertNoError(err, t, "LineToPC")
1529
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1530 1531 1532 1533 1534 1535 1536
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1537
		assertNoError(proc.Continue(p), t, "Continue()")
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549

		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) {
1550
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1551
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1552
		assertNoError(err, t, "LineToPC")
1553
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1554 1555 1556 1557 1558 1559 1560
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1561
		err = proc.Continue(p)
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
		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"},
		}

1576
		err = proc.Continue(p)
1577
		if err != nil {
1578
			if _, exited := err.(proc.ProcessExitedError); !exited {
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
				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)
			}
		}
	})
}
1592 1593 1594

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1595
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1596
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1597 1598 1599 1600 1601 1602 1603
		mmvar, err := evalVariable(p, "mainMenu")
		assertNoError(err, t, "EvalVariable()")
		if mmvar.Kind != reflect.Slice {
			t.Fatalf("Wrong kind for mainMenu: %v\n", mmvar.Kind)
		}
	})
}
1604 1605

func TestStepIntoFunction(t *testing.T) {
1606
	withTestProcess("teststep", t, func(p proc.Process, fixture protest.Fixture) {
1607
		// Continue until breakpoint
1608
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1609
		// Step into function
1610
		assertNoError(proc.Step(p), t, "Step() returned an error")
1611
		// We should now be inside the function.
1612
		loc, err := p.CurrentThread().Location()
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
		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)
		}
	})
}
1627 1628 1629

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
1630
	withTestProcess("issue384", t, func(p proc.Process, fixture protest.Fixture) {
1631
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 13)
1632
		assertNoError(err, t, "LineToPC()")
1633
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1634
		assertNoError(err, t, "SetBreakpoint()")
1635
		assertNoError(proc.Continue(p), t, "Continue()")
1636 1637 1638 1639
		_, err = evalVariable(p, "st")
		assertNoError(err, t, "EvalVariable()")
	})
}
A
aarzilli 已提交
1640 1641 1642

func TestIssue332_Part1(t *testing.T) {
	// Next shouldn't step inside a function call
1643
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1644
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1645
		assertNoError(err, t, "LineToPC()")
1646
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1647
		assertNoError(err, t, "SetBreakpoint()")
1648 1649 1650
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "first Next()")
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
		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
1669
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1670
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1671
		assertNoError(err, t, "LineToPC()")
1672
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1673
		assertNoError(err, t, "SetBreakpoint()")
1674
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
1675 1676 1677

		// step until we enter changeMe
		for {
1678 1679
			assertNoError(proc.Step(p), t, "Step()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688
			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
			}
		}

1689 1690 1691
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers()")
		pc := regs.PC()
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
		pcAfterPrologue, err := p.FindFunctionLocation("main.changeMe", true, -1)
		assertNoError(err, t, "FindFunctionLocation()")
		pcEntry, err := p.FindFunctionLocation("main.changeMe", false, 0)
		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)
		}

1702 1703 1704 1705 1706
		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 已提交
1707 1708 1709 1710
			assertNoError(err, t, "final Continue()")
		}
	})
}
1711 1712

func TestIssue396(t *testing.T) {
1713
	withTestProcess("callme", t, func(p proc.Process, fixture protest.Fixture) {
1714 1715 1716 1717
		_, err := p.FindFunctionLocation("main.init", true, -1)
		assertNoError(err, t, "FindFunctionLocation()")
	})
}
1718 1719 1720

func TestIssue414(t *testing.T) {
	// Stepping until the program exits
1721
	withTestProcess("math", t, func(p proc.Process, fixture protest.Fixture) {
1722
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1723
		assertNoError(err, t, "LineToPC()")
1724
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1725
		assertNoError(err, t, "SetBreakpoint()")
1726
		assertNoError(proc.Continue(p), t, "Continue()")
1727
		for {
1728
			err := proc.Step(p)
1729
			if err != nil {
1730
				if _, exited := err.(proc.ProcessExitedError); exited {
1731 1732 1733 1734 1735 1736 1737
					break
				}
			}
			assertNoError(err, t, "Step()")
		}
	})
}
1738 1739

func TestPackageVariables(t *testing.T) {
1740
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1741
		err := proc.Continue(p)
1742
		assertNoError(err, t, "Continue()")
1743
		scope, err := proc.GoroutineScope(p.CurrentThread())
1744
		assertNoError(err, t, "Scope()")
1745
		vars, err := scope.PackageVariables(normalLoadConfig)
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
		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")
		}
	})
}
1759 1760

func TestIssue149(t *testing.T) {
1761 1762
	ver, _ := proc.ParseVersionString(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(proc.GoVersion{1, 7, -1, 0, 0}) {
1763 1764 1765
		return
	}
	// setting breakpoint on break statement
1766
	withTestProcess("break", t, func(p proc.Process, fixture protest.Fixture) {
1767 1768 1769 1770
		_, err := p.FindFileLocation(fixture.Source, 8)
		assertNoError(err, t, "FindFileLocation()")
	})
}
1771 1772

func TestPanicBreakpoint(t *testing.T) {
1773
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
1774
		assertNoError(proc.Continue(p), t, "Continue()")
1775
		bp, _, _ := p.CurrentThread().Breakpoint()
1776
		if bp == nil || bp.Name != "unrecovered-panic" {
1777
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1778 1779 1780
		}
	})
}
1781

1782
func TestCmdLineArgs(t *testing.T) {
1783
	expectSuccess := func(p proc.Process, fixture protest.Fixture) {
1784
		err := proc.Continue(p)
1785
		bp, _, _ := p.CurrentThread().Breakpoint()
1786
		if bp != nil && bp.Name == "unrecovered-panic" {
1787
			t.Fatalf("testing args failed on unrecovered-panic breakpoint: %v", bp)
1788
		}
1789
		exit, exited := err.(proc.ProcessExitedError)
1790
		if !exited {
1791
			t.Fatalf("Process did not exit: %v", err)
1792 1793 1794 1795 1796 1797 1798
		} else {
			if exit.Status != 0 {
				t.Fatalf("process exited with invalid status", exit.Status)
			}
		}
	}

1799
	expectPanic := func(p proc.Process, fixture protest.Fixture) {
1800
		proc.Continue(p)
1801
		bp, _, _ := p.CurrentThread().Breakpoint()
1802
		if bp == nil || bp.Name != "unrecovered-panic" {
1803
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1804 1805 1806 1807
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
E
Evgeny L 已提交
1808 1809
	withTestProcessArgs("testargs", t, ".", expectSuccess, []string{"test"})
	withTestProcessArgs("testargs", t, ".", expectSuccess, []string{"test", "pass flag"})
1810
	// check that arguments with spaces are *only* passed correctly when correctly called
E
Evgeny L 已提交
1811 1812 1813
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test pass", "flag"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test", "pass", "flag"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test pass flag"})
1814 1815
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
E
Evgeny L 已提交
1816 1817 1818
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"invalid"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test", "invalid"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"invalid", "pass flag"})
1819 1820
}

1821 1822 1823 1824 1825
func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
1826
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
		go func() {
			for !p.Running() {
				time.Sleep(50 * time.Millisecond)
			}

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

1845 1846
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
1847 1848 1849
		assertNoError(err, t, "Stacktrace()")
	})
}
1850

1851
func TestNextParked(t *testing.T) {
1852
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1853 1854 1855 1856
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1857
		var parkedg *proc.G
1858 1859
	LookForParkedG:
		for {
1860 1861
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
1862 1863 1864 1865 1866
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1867
			gs, err := proc.GoroutinesInfo(p)
1868 1869 1870
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
1871
				if g.Thread == nil {
1872 1873 1874 1875 1876 1877 1878 1879
					parkedg = g
					break LookForParkedG
				}
			}
		}

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

1882 1883
		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)
1884 1885 1886
		}
	})
}
1887 1888

func TestStepParked(t *testing.T) {
1889
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1890 1891 1892 1893
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1894
		var parkedg *proc.G
1895 1896
	LookForParkedG:
		for {
1897 1898
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
1899 1900 1901 1902 1903
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1904
			gs, err := proc.GoroutinesInfo(p)
1905 1906 1907
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
1908
				if g.Thread == nil && g.CurrentLoc.Fn != nil && g.CurrentLoc.Fn.Name == "main.sayhi" {
1909 1910 1911 1912 1913 1914
					parkedg = g
					break LookForParkedG
				}
			}
		}

A
aarzilli 已提交
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
		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)
		}

1925 1926
		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
1927
		assertNoError(proc.Step(p), t, "Step()")
1928

1929 1930
		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)
1931 1932 1933
		}
	})
}
1934 1935 1936 1937 1938 1939 1940 1941

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")
1942
	_, err := native.Launch([]string{exepath}, ".")
1943 1944 1945
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
1946 1947
	if err != proc.NotExecutableErr {
		t.Fatalf("expected error \"%v\" got \"%v\"", proc.NotExecutableErr, err)
1948 1949 1950 1951 1952
	}
	os.Remove(exepath)
}

func TestUnsupportedArch(t *testing.T) {
1953 1954
	ver, _ := proc.ParseVersionString(runtime.Version())
	if ver.Major < 0 || !ver.AfterOrEqual(proc.GoVersion{1, 6, -1, 0, 0}) || ver.AfterOrEqual(proc.GoVersion{1, 7, -1, 0, 0}) {
1955 1956 1957
		// cross compile (with -N?) works only on select versions of go
		return
	}
1958

1959 1960 1961
	fixturesDir := protest.FindFixturesDir()
	infile := filepath.Join(fixturesDir, "math.go")
	outfile := filepath.Join(fixturesDir, "_math_debug_386")
1962

1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
	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)
1975

1976
	p, err := native.Launch([]string{outfile}, ".")
1977
	switch err {
1978
	case proc.UnsupportedLinuxArchErr, proc.UnsupportedWindowsArchErr, proc.UnsupportedDarwinArchErr:
1979 1980 1981 1982 1983 1984 1985 1986 1987
		// all good
	case nil:
		p.Halt()
		p.Kill()
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
1988

1989
func TestIssue573(t *testing.T) {
1990
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
1991
	// of the function and the internal breakpoint set by StepInto may be missed.
1992
	withTestProcess("issue573", t, func(p proc.Process, fixture protest.Fixture) {
1993
		fentry, _ := p.FindFunctionLocation("main.foo", false, 0)
1994
		_, err := p.SetBreakpoint(fentry, proc.UserBreakpoint, nil)
1995
		assertNoError(err, t, "SetBreakpoint()")
1996 1997 1998 1999
		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.
2000 2001
	})
}
2002 2003

func TestTestvariables2Prologue(t *testing.T) {
2004
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2005 2006 2007 2008 2009 2010 2011 2012 2013
		addrEntry, err := p.FindFunctionLocation("main.main", false, 0)
		assertNoError(err, t, "FindFunctionLocation - entrypoint")
		addrPrologue, err := p.FindFunctionLocation("main.main", true, 0)
		assertNoError(err, t, "FindFunctionLocation - postprologue")
		if addrEntry == addrPrologue {
			t.Fatalf("Prologue detection failed on testvariables2.go/main.main")
		}
	})
}
2014 2015 2016 2017 2018

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 已提交
2019
	testseq("defercall", contNext, []nextTest{
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
		{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 已提交
2035
	testseq("defercall", contNext, []nextTest{
2036 2037 2038 2039 2040
		{15, 16},
		{16, 17},
		{17, 18},
		{18, 5}}, "main.callAndPanic2", t)
}
A
aarzilli 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090

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.
	testseq("defercall", contStep, []nextTest{
		{17, 5},
		{5, 6},
		{6, 7},
		{7, 18},
		{18, 5},
		{5, 6},
		{6, 7}}, "", t)
}

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)
2091
	ver, _ := proc.ParseVersionString(runtime.Version())
A
aarzilli 已提交
2092

2093
	if ver.Major < 0 || ver.AfterOrEqual(proc.GoVersion{1, 7, -1, 0, 0}) {
A
aarzilli 已提交
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
		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.
2114
	withTestProcess("issue561", t, func(p proc.Process, fixture protest.Fixture) {
2115
		setFileBreakpoint(p, t, fixture, 10)
2116 2117
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2118 2119 2120 2121 2122 2123 2124
		_, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number after Step, expected 5 got %d", ln)
		}
	})
}

A
aarzilli 已提交
2125
func TestStepOut(t *testing.T) {
2126
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2127 2128
		bp, err := setFunctionBreakpoint(p, "main.helloworld")
		assertNoError(err, t, "SetBreakpoint()")
2129
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2130 2131 2132 2133 2134 2135 2136
		p.ClearBreakpoint(bp.Addr)

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

2137
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2138 2139 2140 2141 2142 2143 2144 2145

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

A
aarzilli 已提交
2146
func TestStepConcurrentDirect(t *testing.T) {
2147
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2148 2149
		pc, err := p.FindFileLocation(fixture.Source, 37)
		assertNoError(err, t, "FindFileLocation()")
2150
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2151 2152
		assertNoError(err, t, "SetBreakpoint()")

2153
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2154 2155 2156
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")

A
aarzilli 已提交
2157 2158 2159 2160 2161 2162 2163 2164
		for _, b := range p.Breakpoints() {
			if b.Name == "unrecovered-panic" {
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

2165
		gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2166 2167 2168 2169 2170 2171

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

		i := 0
		count := 0
		for {
A
aarzilli 已提交
2172
			anyerr := false
2173 2174
			if p.SelectedGoroutine().ID != gid {
				t.Errorf("Step switched to different goroutine %d %d\n", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2175 2176
				anyerr = true
			}
A
aarzilli 已提交
2177 2178 2179 2180 2181 2182
			f, ln := currentLineNumber(p, t)
			if ln != seq[i] {
				if i == 1 && ln == 40 {
					// loop exited
					break
				}
2183
				frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
A
aarzilli 已提交
2184
				if err != nil {
2185
					t.Errorf("Could not get stacktrace of goroutine %d\n", p.SelectedGoroutine().ID)
A
aarzilli 已提交
2186
				} else {
2187
					t.Logf("Goroutine %d (thread: %d):", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
A
aarzilli 已提交
2188 2189 2190 2191 2192 2193
					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 已提交
2194
			}
A
aarzilli 已提交
2195 2196
			if anyerr {
				t.FailNow()
A
aarzilli 已提交
2197 2198 2199 2200 2201
			}
			i = (i + 1) % len(seq)
			if i == 0 {
				count++
			}
2202
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2203 2204 2205 2206 2207 2208 2209 2210
		}

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

2211
func nextInProgress(p proc.Process) bool {
2212
	for _, bp := range p.Breakpoints() {
2213
		if bp.Internal() {
A
aarzilli 已提交
2214 2215 2216 2217 2218 2219 2220
			return true
		}
	}
	return false
}

func TestStepConcurrentPtr(t *testing.T) {
2221
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2222 2223
		pc, err := p.FindFileLocation(fixture.Source, 24)
		assertNoError(err, t, "FindFileLocation()")
2224
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2225 2226
		assertNoError(err, t, "SetBreakpoint()")

A
aarzilli 已提交
2227 2228 2229 2230 2231 2232 2233 2234
		for _, b := range p.Breakpoints() {
			if b.Name == "unrecovered-panic" {
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2235 2236 2237
		kvals := map[int]int64{}
		count := 0
		for {
2238 2239
			err := proc.Continue(p)
			_, exited := err.(proc.ProcessExitedError)
A
aarzilli 已提交
2240 2241 2242 2243 2244 2245 2246
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
2247 2248 2249
				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 已提交
2250
				}
2251 2252
				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 已提交
2253 2254
			}

2255
			gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267

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

			if oldk, ok := kvals[gid]; ok {
				if oldk >= k {
					t.Fatalf("Goroutine %d did not make progress?")
				}
			}
			kvals[gid] = k

2268
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2269
			for nextInProgress(p) {
2270 2271
				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 已提交
2272
				}
2273
				assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2274 2275
			}

2276 2277
			if p.SelectedGoroutine().ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2278 2279
			}

2280 2281 2282
			f, ln = currentLineNumber(p, t)
			if ln != 13 {
				t.Fatalf("Step did not step into function call (13): %s:%d", f, ln)
A
aarzilli 已提交
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
			}

			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 已提交
2299
func TestStepOutDefer(t *testing.T) {
2300
	withTestProcess("testnextdefer", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2301 2302
		pc, err := p.FindFileLocation(fixture.Source, 9)
		assertNoError(err, t, "FindFileLocation()")
2303
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2304
		assertNoError(err, t, "SetBreakpoint()")
2305
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2306 2307 2308 2309 2310 2311 2312
		p.ClearBreakpoint(bp.Addr)

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

2313
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2314

2315
		f, l, _ := p.BinInfo().PCToLine(currentPC(p, t))
A
aarzilli 已提交
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
		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
2326
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2327
		bp := setFileBreakpoint(p, t, fixture, 11)
2328
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2329 2330
		p.ClearBreakpoint(bp.Addr)

2331
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2332 2333 2334 2335 2336 2337 2338 2339

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

2340 2341
const maxInstructionLength uint64 = 15

A
aarzilli 已提交
2342
func TestStepOnCallPtrInstr(t *testing.T) {
2343
	withTestProcess("teststepprog", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2344 2345
		pc, err := p.FindFileLocation(fixture.Source, 10)
		assertNoError(err, t, "FindFileLocation()")
2346
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2347 2348
		assertNoError(err, t, "SetBreakpoint()")

2349
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2350 2351 2352 2353 2354 2355 2356 2357

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
2358
			regs, err := p.CurrentThread().Registers(false)
2359
			assertNoError(err, t, "Registers()")
2360
			pc := regs.PC()
2361
			text, err := proc.Disassemble(p, nil, pc, pc+maxInstructionLength)
A
aarzilli 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
			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")
		}

2374
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2375 2376 2377 2378 2379 2380 2381

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

func TestIssue594(t *testing.T) {
2384 2385 2386 2387 2388 2389 2390 2391
	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
	}
2392 2393 2394 2395
	// 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.
2396
	withTestProcess("issue594", t, func(p proc.Process, fixture protest.Fixture) {
2397
		assertNoError(proc.Continue(p), t, "Continue()")
2398 2399 2400 2401 2402 2403
		f, ln := currentLineNumber(p, t)
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2404 2405 2406 2407 2408

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
2409
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
aarzilli 已提交
2410
		bp := setFileBreakpoint(p, t, fixture, 17)
2411
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2412 2413
		p.ClearBreakpoint(bp.Addr)

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

		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number, expected %d got %s:%d", 5, f, ln)
		}
	})
}
E
Evgeny L 已提交
2422 2423 2424 2425 2426 2427 2428

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"
	}
2429
	withTestProcessArgs("workdir", t, wd, func(p proc.Process, fixture protest.Fixture) {
2430
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 14)
E
Evgeny L 已提交
2431
		assertNoError(err, t, "LineToPC")
2432 2433
		p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
		proc.Continue(p)
E
Evgeny L 已提交
2434 2435 2436 2437 2438 2439 2440 2441
		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{})
}
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452

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)},
	}
2453
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2454
		assertNoError(proc.Continue(p), t, "Continue()")
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
		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)
			}
		}
	})
}
2467 2468 2469

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
2470
	withTestProcess("issue683", t, func(p proc.Process, fixture protest.Fixture) {
2471 2472
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
2473
		assertNoError(proc.Continue(p), t, "First Continue()")
2474 2475 2476
		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
2477
			err := proc.Step(p)
2478 2479 2480 2481
			if err != nil {
				break
			}
		}
2482 2483 2484 2485
	})
}

func TestIssue664(t *testing.T) {
2486
	withTestProcess("issue664", t, func(p proc.Process, fixture protest.Fixture) {
2487
		setFileBreakpoint(p, t, fixture, 4)
2488 2489
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
2490 2491 2492
		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("Did not continue to line 5: %s:%d", f, ln)
2493 2494 2495
		}
	})
}
A
Alessandro Arzilli 已提交
2496 2497 2498

// Benchmarks (*Processs).Continue + (*Scope).FunctionArguments
func BenchmarkTrace(b *testing.B) {
2499
	withTestProcess("traceperf", b, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2500 2501 2502 2503
		_, err := setFunctionBreakpoint(p, "main.PerfCheck")
		assertNoError(err, b, "setFunctionBreakpoint()")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
2504 2505
			assertNoError(proc.Continue(p), b, "Continue()")
			s, err := proc.GoroutineScope(p.CurrentThread())
A
Alessandro Arzilli 已提交
2506
			assertNoError(err, b, "Scope()")
2507
			_, err = s.FunctionArguments(proc.LoadConfig{false, 0, 64, 0, 3})
A
Alessandro Arzilli 已提交
2508 2509 2510 2511 2512
			assertNoError(err, b, "FunctionArguments()")
		}
		b.StopTimer()
	})
}
A
Alessandro Arzilli 已提交
2513 2514 2515 2516 2517 2518

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.
2519
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2520 2521
		_, err := setFunctionBreakpoint(p, "runtime.deferreturn")
		assertNoError(err, t, "setFunctionBreakpoint()")
2522
		assertNoError(proc.Continue(p), t, "First Continue()")
A
Alessandro Arzilli 已提交
2523
		for i := 0; i < 20; i++ {
2524
			assertNoError(proc.Next(p), t, fmt.Sprintf("Next() %d", i))
A
Alessandro Arzilli 已提交
2525 2526 2527 2528
		}
	})
}

2529
func getg(goid int, gs []*proc.G) *proc.G {
A
Alessandro Arzilli 已提交
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
	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.
2544

2545
	// In Go 1.9 stack barriers have been removed and this test must be disabled.
2546
	if ver, _ := proc.ParseVersionString(runtime.Version()); ver.Major < 0 || ver.AfterOrEqual(proc.GoVersion{1, 9, -1, 0, 0}) {
2547 2548 2549
		return
	}

2550 2551 2552 2553 2554
	// 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")

2555
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2556 2557 2558 2559 2560
		// 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 {
2561 2562
			err := proc.Continue(p)
			if _, exited := err.(proc.ProcessExitedError); exited {
2563 2564 2565 2566
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
2567
			gs, err := proc.GoroutinesInfo(p)
A
Alessandro Arzilli 已提交
2568
			assertNoError(err, t, "GoroutinesInfo()")
2569 2570
			for _, th := range p.ThreadList() {
				if bp, _, _ := th.Breakpoint(); bp == nil {
A
Alessandro Arzilli 已提交
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
					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)

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

2599
		gs, err := proc.GoroutinesInfo(p)
A
Alessandro Arzilli 已提交
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
		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 {
				t.Log("Truncated stacktrace for %d\n", goid)
			}
		}
	})
}
2637 2638

func TestAttachDetach(t *testing.T) {
2639 2640 2641 2642 2643 2644
	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
		}
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665
	}
	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")
		}
	}

2666
	var p proc.Process
2667 2668 2669 2670
	var err error

	switch testBackend {
	case "native":
2671
		p, err = native.Attach(cmd.Process.Pid)
2672 2673 2674 2675 2676
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
2677
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path)
2678 2679 2680 2681
	default:
		err = fmt.Errorf("unknown backend %q", testBackend)
	}

2682 2683 2684 2685 2686 2687
	assertNoError(err, t, "Attach")
	go func() {
		time.Sleep(1 * time.Second)
		http.Get("http://localhost:9191")
	}()

2688
	assertNoError(proc.Continue(p), t, "Continue")
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706

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

	cmd.Process.Kill()
}