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

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

D
Derek Parker 已提交
19
	protest "github.com/derekparker/delve/proc/test"
D
Derek Parker 已提交
20
)
21

22
func init() {
23 24
	runtime.GOMAXPROCS(4)
	os.Setenv("GOMAXPROCS", "4")
25 26
}

D
Dan Mace 已提交
27
func TestMain(m *testing.M) {
D
Derek Parker 已提交
28
	os.Exit(protest.RunTestsWithFixtures(m))
D
Dan Mace 已提交
29 30
}

31
func withTestProcess(name string, t testing.TB, fn func(p *Process, fixture protest.Fixture)) {
32
	fixture := protest.BuildFixture(name)
D
Dan Mace 已提交
33
	p, err := Launch([]string{fixture.Path})
34 35 36 37
	if err != nil {
		t.Fatal("Launch():", err)
	}

38 39
	defer func() {
		p.Halt()
40
		p.Kill()
41
	}()
42

D
Dan Mace 已提交
43
	fn(p, fixture)
44 45
}

D
Derek Parker 已提交
46
func getRegisters(p *Process, t *testing.T) Registers {
47 48 49 50 51 52 53 54
	regs, err := p.Registers()
	if err != nil {
		t.Fatal("Registers():", err)
	}

	return regs
}

D
Derek Parker 已提交
55
func dataAtAddr(thread *Thread, addr uint64) ([]byte, error) {
D
Derek Parker 已提交
56
	return thread.readMemory(uintptr(addr), 1)
57 58
}

59
func assertNoError(err error, t testing.TB, s string) {
60
	if err != nil {
61 62
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
63
		t.Fatalf("failed assertion at %s:%d: %s - %s\n", fname, line, s, err)
64 65 66
	}
}

D
Derek Parker 已提交
67
func currentPC(p *Process, t *testing.T) uint64 {
D
Derek Parker 已提交
68
	pc, err := p.PC()
69 70 71 72 73 74 75
	if err != nil {
		t.Fatal(err)
	}

	return pc
}

D
Derek Parker 已提交
76
func currentLineNumber(p *Process, t *testing.T) (string, int) {
77
	pc := currentPC(p, t)
78
	f, l, _ := p.goSymTable.PCToLine(pc)
79

D
Derek Parker 已提交
80
	return f, l
81 82
}

83
func TestExit(t *testing.T) {
D
Derek Parker 已提交
84
	withTestProcess("continuetestprog", t, func(p *Process, fixture protest.Fixture) {
85 86 87
		err := p.Continue()
		pe, ok := err.(ProcessExitedError)
		if !ok {
88
			t.Fatalf("Continue() returned unexpected error type %s", err)
89 90 91 92 93 94 95 96 97 98
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
		if pe.Pid != p.Pid {
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

99 100 101 102 103 104 105 106
func TestExitAfterContinue(t *testing.T) {
	withTestProcess("continuetestprog", t, func(p *Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(p.Continue(), t, "First Continue()")
		err = p.Continue()
		pe, ok := err.(ProcessExitedError)
		if !ok {
L
Luke Hoban 已提交
107
			t.Fatalf("Continue() returned unexpected error type %s", pe)
108 109 110 111 112 113 114 115 116 117
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
		if pe.Pid != p.Pid {
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

118 119 120 121 122 123 124 125
func setFunctionBreakpoint(p *Process, fname string) (*Breakpoint, error) {
	addr, err := p.FindFunctionLocation(fname, true, 0)
	if err != nil {
		return nil, err
	}
	return p.SetBreakpoint(addr)
}

D
Derek Parker 已提交
126
func TestHalt(t *testing.T) {
127 128
	stopChan := make(chan interface{})
	withTestProcess("loopprog", t, func(p *Process, fixture protest.Fixture) {
129
		_, err := setFunctionBreakpoint(p, "main.loop")
130 131 132 133
		assertNoError(err, t, "SetBreakpoint")
		assertNoError(p.Continue(), t, "Continue")
		for _, th := range p.Threads {
			if th.running != false {
D
Derek Parker 已提交
134
				t.Fatal("expected running = false for thread", th.ID)
135 136 137 138
			}
			_, err := th.Registers()
			assertNoError(err, t, "Registers")
		}
D
Derek Parker 已提交
139
		go func() {
D
Dan Mace 已提交
140 141
			for {
				if p.Running() {
142
					if err := p.RequestManualStop(); err != nil {
D
Dan Mace 已提交
143 144
						t.Fatal(err)
					}
145
					stopChan <- nil
D
Dan Mace 已提交
146 147
					return
				}
D
Derek Parker 已提交
148 149
			}
		}()
150 151
		assertNoError(p.Continue(), t, "Continue")
		<-stopChan
D
Derek Parker 已提交
152 153 154 155
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
		for _, th := range p.Threads {
156 157 158
			if !th.Stopped() {
				t.Fatal("expected thread to be stopped, but was not")
			}
159
			if th.running != false {
D
Derek Parker 已提交
160
				t.Fatal("expected running = false for thread", th.ID)
D
Derek Parker 已提交
161
			}
162 163
			_, err := th.Registers()
			assertNoError(err, t, "Registers")
D
Derek Parker 已提交
164 165 166 167
		}
	})
}

168
func TestStep(t *testing.T) {
D
Derek Parker 已提交
169
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
170
		helloworldfunc := p.goSymTable.LookupFunc("main.helloworld")
171 172
		helloworldaddr := helloworldfunc.Entry

173 174
		_, err := p.SetBreakpoint(helloworldaddr)
		assertNoError(err, t, "SetBreakpoint()")
175 176
		assertNoError(p.Continue(), t, "Continue()")

177
		regs := getRegisters(p, t)
178
		rip := regs.PC()
179

180
		err = p.CurrentThread.StepInstruction()
D
Derek Parker 已提交
181
		assertNoError(err, t, "Step()")
182

183
		regs = getRegisters(p, t)
184 185 186 187 188
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
189

D
Derek Parker 已提交
190
func TestBreakpoint(t *testing.T) {
D
Derek Parker 已提交
191
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
192
		helloworldfunc := p.goSymTable.LookupFunc("main.helloworld")
D
Derek Parker 已提交
193
		helloworldaddr := helloworldfunc.Entry
194

195 196
		bp, err := p.SetBreakpoint(helloworldaddr)
		assertNoError(err, t, "SetBreakpoint()")
D
Derek Parker 已提交
197
		assertNoError(p.Continue(), t, "Continue()")
198

D
Derek Parker 已提交
199
		pc, err := p.PC()
200 201 202
		if err != nil {
			t.Fatal(err)
		}
203

204 205 206 207
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
208
		if pc-1 != bp.Addr && pc != bp.Addr {
209
			f, l, _ := p.goSymTable.PCToLine(pc)
D
Derek Parker 已提交
210
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
211 212
		}
	})
213
}
214

D
Derek Parker 已提交
215
func TestBreakpointInSeperateGoRoutine(t *testing.T) {
D
Derek Parker 已提交
216
	withTestProcess("testthreads", t, func(p *Process, fixture protest.Fixture) {
217
		fn := p.goSymTable.LookupFunc("main.anotherthread")
218 219 220 221
		if fn == nil {
			t.Fatal("No fn exists")
		}

222
		_, err := p.SetBreakpoint(fn.Entry)
223 224 225 226 227 228 229 230 231
		if err != nil {
			t.Fatal(err)
		}

		err = p.Continue()
		if err != nil {
			t.Fatal(err)
		}

D
Derek Parker 已提交
232
		pc, err := p.PC()
233 234 235 236
		if err != nil {
			t.Fatal(err)
		}

237
		f, l, _ := p.goSymTable.PCToLine(pc)
238 239 240 241 242 243
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
244
func TestBreakpointWithNonExistantFunction(t *testing.T) {
D
Derek Parker 已提交
245
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
246
		_, err := p.SetBreakpoint(0)
247 248 249 250
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
251
}
252

253
func TestClearBreakpointBreakpoint(t *testing.T) {
D
Derek Parker 已提交
254
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
255
		fn := p.goSymTable.LookupFunc("main.sleepytime")
256 257
		bp, err := p.SetBreakpoint(fn.Entry)
		assertNoError(err, t, "SetBreakpoint()")
258

259 260
		bp, err = p.ClearBreakpoint(fn.Entry)
		assertNoError(err, t, "ClearBreakpoint()")
261

D
Derek Parker 已提交
262
		data, err := dataAtAddr(p.CurrentThread, bp.Addr)
263 264 265 266
		if err != nil {
			t.Fatal(err)
		}

267
		int3 := []byte{0xcc}
268 269 270 271
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

272
		if countBreakpoints(p) != 0 {
273 274 275
			t.Fatal("Breakpoint not removed internally")
		}
	})
276
}
277

278 279 280
type nextTest struct {
	begin, end int
}
281

282 283 284 285 286 287 288 289 290 291
func countBreakpoints(p *Process) int {
	bpcount := 0
	for _, bp := range p.Breakpoints {
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

292
func testnext(program string, testcases []nextTest, initialLocation string, t *testing.T) {
D
Derek Parker 已提交
293
	withTestProcess(program, t, func(p *Process, fixture protest.Fixture) {
294
		bp, err := setFunctionBreakpoint(p, initialLocation)
295
		assertNoError(err, t, "SetBreakpoint()")
296
		assertNoError(p.Continue(), t, "Continue()")
297
		p.ClearBreakpoint(bp.Addr)
298
		p.CurrentThread.SetPC(bp.Addr)
299

D
Derek Parker 已提交
300
		f, ln := currentLineNumber(p, t)
301 302
		for _, tc := range testcases {
			if ln != tc.begin {
D
Derek Parker 已提交
303
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
304 305 306 307
			}

			assertNoError(p.Next(), t, "Next() returned an error")

D
Derek Parker 已提交
308
			f, ln = currentLineNumber(p, t)
309
			if ln != tc.end {
D
Derek Parker 已提交
310
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d", tc.end, filepath.Base(f), ln)
311 312
			}
		}
313

314
		if countBreakpoints(p) != 0 {
D
Derek Parker 已提交
315
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints))
316
		}
317 318
	})
}
319

320
func TestNextGeneral(t *testing.T) {
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	var testcases []nextTest

	ver, _ := ParseVersionString(runtime.Version())

	if ver.Major < 0 || ver.AfterOrEqual(GoVersion{1, 7, 0, 0, 0}) {
		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},
		}
362
	}
363

364
	testnext("testnextprog", testcases, "main.testnext", t)
365 366
}

367 368
func TestNextConcurrent(t *testing.T) {
	testcases := []nextTest{
369
		{8, 9},
370 371 372 373
		{9, 10},
		{10, 11},
	}
	withTestProcess("parallel_next", t, func(p *Process, fixture protest.Fixture) {
374
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
375 376 377
		assertNoError(err, t, "SetBreakpoint")
		assertNoError(p.Continue(), t, "Continue")
		f, ln := currentLineNumber(p, t)
378
		initV, err := evalVariable(p, "n")
379
		initVval, _ := constant.Int64Val(initV.Value)
380
		assertNoError(err, t, "EvalVariable")
381 382
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")
383
		for _, tc := range testcases {
384 385
			g, err := p.CurrentThread.GetG()
			assertNoError(err, t, "GetG()")
D
Derek Parker 已提交
386 387
			if p.SelectedGoroutine.ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine.ID)
388
			}
389 390 391 392 393 394 395 396
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
			assertNoError(p.Next(), t, "Next() returned an error")
			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)
			}
397
			v, err := evalVariable(p, "n")
398
			assertNoError(err, t, "EvalVariable")
399 400
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
401 402 403 404 405 406
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

407 408 409
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{
410
		{8, 9},
411 412 413 414 415 416 417 418 419 420 421 422 423 424
		{9, 10},
		{10, 11},
	}
	withTestProcess("parallel_next", t, func(p *Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint")
		assertNoError(p.Continue(), t, "Continue")
		f, ln := currentLineNumber(p, t)
		initV, err := evalVariable(p, "n")
		initVval, _ := constant.Int64Val(initV.Value)
		assertNoError(err, t, "EvalVariable")
		for _, tc := range testcases {
			g, err := p.CurrentThread.GetG()
			assertNoError(err, t, "GetG()")
D
Derek Parker 已提交
425 426
			if p.SelectedGoroutine.ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine.ID)
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
			}
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
			assertNoError(p.Next(), t, "Next() returned an error")
			var vval int64
			for {
				v, err := evalVariable(p, "n")
				assertNoError(err, t, "EvalVariable")
				vval, _ = constant.Int64Val(v.Value)
				if p.CurrentThread.CurrentBreakpoint == nil {
					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")
					}
					assertNoError(p.Continue(), t, "Continue 2")
				}
			}
			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)
			}
		}
	})
}

457 458
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
459
		{13, 14},
D
Derek Parker 已提交
460 461
		{14, 15},
		{15, 35},
462
	}
463 464 465 466 467
	testnext("testnextprog", testcases, "main.helloworld", t)
}

func TestNextFunctionReturnDefer(t *testing.T) {
	testcases := []nextTest{
468
		{5, 8},
D
Derek Parker 已提交
469 470 471 472
		{8, 9},
		{9, 10},
		{10, 7},
		{7, 8},
473 474
	}
	testnext("testnextdefer", testcases, "main.main", t)
475 476
}

D
Derek Parker 已提交
477 478 479 480 481 482 483 484 485 486 487 488
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
	withTestProcess("testnextnethttp", t, func(p *Process, fixture protest.Fixture) {
		go func() {
			for !p.Running() {
				time.Sleep(50 * time.Millisecond)
			}
			// Wait for program to start listening.
			for {
L
Luke Hoban 已提交
489
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
490 491 492 493 494 495
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
496
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
		}()
		if err := p.Continue(); err != nil {
			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)
			}

			assertNoError(p.Next(), t, "Next() returned an error")

			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 已提交
517
func TestRuntimeBreakpoint(t *testing.T) {
D
Derek Parker 已提交
518
	withTestProcess("testruntimebreakpoint", t, func(p *Process, fixture protest.Fixture) {
D
Derek Parker 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
		err := p.Continue()
		if err != nil {
			t.Fatal(err)
		}
		pc, err := p.PC()
		if err != nil {
			t.Fatal(err)
		}
		_, l, _ := p.PCToLine(pc)
		if l != 10 {
			t.Fatal("did not respect breakpoint")
		}
	})
}

534
func TestFindReturnAddress(t *testing.T) {
D
Derek Parker 已提交
535
	withTestProcess("testnextprog", t, func(p *Process, fixture protest.Fixture) {
536
		start, _, err := p.goSymTable.LineToPC(fixture.Source, 24)
537 538 539
		if err != nil {
			t.Fatal(err)
		}
540
		_, err = p.SetBreakpoint(start)
541 542 543 544 545 546 547
		if err != nil {
			t.Fatal(err)
		}
		err = p.Continue()
		if err != nil {
			t.Fatal(err)
		}
548
		addr, err := p.CurrentThread.ReturnAddress()
549 550 551
		if err != nil {
			t.Fatal(err)
		}
552 553 554
		_, l, _ := p.goSymTable.PCToLine(addr)
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
555
		}
556 557
	})
}
558

559 560 561 562 563 564 565 566
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
	withTestProcess("testreturnaddress", t, func(p *Process, fixture protest.Fixture) {
		fnName := "runtime.rt0_go"
		fn := p.goSymTable.LookupFunc(fnName)
		if fn == nil {
			t.Fatalf("could not find function %s", fnName)
		}
		if _, err := p.SetBreakpoint(fn.Entry); err != nil {
567 568
			t.Fatal(err)
		}
569
		if err := p.Continue(); err != nil {
D
Derek Parker 已提交
570 571
			t.Fatal(err)
		}
572 573
		if _, err := p.CurrentThread.ReturnAddress(); err == nil {
			t.Fatal("expected error to be returned")
574 575 576
		}
	})
}
D
Derek Parker 已提交
577 578

func TestSwitchThread(t *testing.T) {
D
Derek Parker 已提交
579
	withTestProcess("testnextprog", t, func(p *Process, fixture protest.Fixture) {
D
Derek Parker 已提交
580 581 582 583 584
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
585
		pc, err := p.FindFunctionLocation("main.main", true, 0)
D
Derek Parker 已提交
586 587 588
		if err != nil {
			t.Fatal(err)
		}
589
		_, err = p.SetBreakpoint(pc)
D
Derek Parker 已提交
590 591 592 593 594 595 596 597
		if err != nil {
			t.Fatal(err)
		}
		err = p.Continue()
		if err != nil {
			t.Fatal(err)
		}
		var nt int
D
Derek Parker 已提交
598
		ct := p.CurrentThread.ID
D
Dan Mace 已提交
599
		for tid := range p.Threads {
D
Derek Parker 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612
			if tid != ct {
				nt = tid
				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)
		}
D
Derek Parker 已提交
613
		if p.CurrentThread.ID != nt {
D
Derek Parker 已提交
614 615 616 617
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
618

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
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
	}

	withTestProcess("cgotest", t, func(p *Process, fixture protest.Fixture) {
		pc, err := p.FindFunctionLocation("main.main", true, 0)
		if err != nil {
			t.Fatal(err)
		}
		_, err = p.SetBreakpoint(pc)
		if err != nil {
			t.Fatal(err)
		}
		err = p.Continue()
		if err != nil {
			t.Fatal(err)
		}
		err = p.Next()
		if err != nil {
			t.Fatal(err)
		}
	})
}

A
aarzilli 已提交
646 647 648 649 650
type loc struct {
	line int
	fn   string
}

651
func (l1 *loc) match(l2 Stackframe) bool {
A
aarzilli 已提交
652
	if l1.line >= 0 {
653
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
654 655 656
			return false
		}
	}
657
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
658 659 660 661
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
662 663
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
664
	}
D
Derek Parker 已提交
665
	withTestProcess("stacktraceprog", t, func(p *Process, fixture protest.Fixture) {
666
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
667 668 669 670
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
			assertNoError(p.Continue(), t, "Continue()")
D
Derek Parker 已提交
671
			locations, err := p.CurrentThread.Stacktrace(40)
A
aarzilli 已提交
672 673 674 675 676 677
			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)
			}

678 679 680 681
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
682

A
aarzilli 已提交
683 684 685 686 687 688 689
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

690
		p.ClearBreakpoint(bp.Addr)
A
aarzilli 已提交
691 692 693 694
		p.Continue()
	})
}

695 696 697 698 699 700
func TestStacktrace2(t *testing.T) {
	withTestProcess("retstack", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue()")

		locations, err := p.CurrentThread.Stacktrace(40)
		assertNoError(err, t, "Stacktrace()")
701
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
702 703 704
			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 已提交
705
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
706 707 708 709 710
		}

		assertNoError(p.Continue(), t, "Continue()")
		locations, err = p.CurrentThread.Stacktrace(40)
		assertNoError(err, t, "Stacktrace()")
711
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
712 713 714
			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 已提交
715
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
716 717 718 719 720
		}
	})

}

721
func stackMatch(stack []loc, locations []Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
722 723 724
	if len(stack) > len(locations) {
		return false
	}
725 726 727 728 729 730 731 732 733 734 735
	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 已提交
736 737
			return false
		}
738
		i++
A
aarzilli 已提交
739
	}
740
	return i >= len(stack)
A
aarzilli 已提交
741 742 743
}

func TestStacktraceGoroutine(t *testing.T) {
744 745 746
	mainStack := []loc{{13, "main.stacktraceme"}, {26, "main.main"}}
	agoroutineStackA := []loc{{9, "main.agoroutine"}}
	agoroutineStackB := []loc{{10, "main.agoroutine"}}
A
aarzilli 已提交
747

D
Derek Parker 已提交
748
	withTestProcess("goroutinestackprog", t, func(p *Process, fixture protest.Fixture) {
749
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
750 751 752 753 754 755 756 757 758 759
		assertNoError(err, t, "BreakByLocation()")

		assertNoError(p.Continue(), t, "Continue()")

		gs, err := p.GoroutinesInfo()
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
760
		for i, g := range gs {
A
aarzilli 已提交
761
			locations, err := g.Stacktrace(40)
A
aarzilli 已提交
762 763
			assertNoError(err, t, "GoroutineStacktrace()")

764
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
765 766 767
				mainCount++
			}

768 769 770
			if stackMatch(agoroutineStackA, locations, true) {
				agoroutineCount++
			} else if stackMatch(agoroutineStackB, locations, true) {
A
aarzilli 已提交
771 772
				agoroutineCount++
			} else {
D
Derek Parker 已提交
773
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
774 775
				for i := range locations {
					name := ""
776 777
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
778
					}
779
					t.Logf("\t%s:%d %s\n", locations[i].Call.File, locations[i].Call.Line, name)
A
aarzilli 已提交
780 781 782 783 784
				}
			}
		}

		if mainCount != 1 {
785
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
786 787 788 789 790 791
		}

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

792
		p.ClearBreakpoint(bp.Addr)
A
aarzilli 已提交
793 794 795
		p.Continue()
	})
}
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

func TestKill(t *testing.T) {
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
		if err := p.Kill(); err != nil {
			t.Fatal(err)
		}
		if p.Exited() != true {
			t.Fatal("expected process to have exited")
		}
		if runtime.GOOS == "linux" {
			_, err := os.Open(fmt.Sprintf("/proc/%d/", p.Pid))
			if err == nil {
				t.Fatal("process has not exited", p.Pid)
			}
		}
	})
}
813 814

func testGSupportFunc(name string, t *testing.T, p *Process, fixture protest.Fixture) {
815
	bp, err := setFunctionBreakpoint(p, "main.main")
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
	assertNoError(err, t, name+": BreakByLocation()")

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

	g, err := p.CurrentThread.GetG()
	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) {
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
		testGSupportFunc("nocgo", t, p, fixture)
	})

837 838 839 840 841
	// 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
	}

842 843 844 845
	withTestProcess("cgotest", t, func(p *Process, fixture protest.Fixture) {
		testGSupportFunc("cgo", t, p, fixture)
	})
}
846 847 848

func TestContinueMulti(t *testing.T) {
	withTestProcess("integrationprog", t, func(p *Process, fixture protest.Fixture) {
849
		bp1, err := setFunctionBreakpoint(p, "main.main")
850 851
		assertNoError(err, t, "BreakByLocation()")

852
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
853 854 855 856 857 858
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
			err := p.Continue()
859
			if p.Exited() {
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
				break
			}
			assertNoError(err, t, "Continue()")

			if p.CurrentBreakpoint().ID == bp1.ID {
				mainCount++
			}

			if p.CurrentBreakpoint().ID == bp2.ID {
				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)
		}
	})
}
882

883
func versionAfterOrEqual(t *testing.T, verStr string, ver GoVersion) {
884
	pver, ok := ParseVersionString(verStr)
885 886 887
	if !ok {
		t.Fatalf("Could not parse version string <%s>", verStr)
	}
888
	if !pver.AfterOrEqual(ver) {
889 890 891 892 893 894
		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) {
A
aarzilli 已提交
895
	versionAfterOrEqual(t, "go1.4", GoVersion{1, 4, 0, 0, 0})
D
Derek Parker 已提交
896 897 898 899
	versionAfterOrEqual(t, "go1.5.0", GoVersion{1, 5, 0, 0, 0})
	versionAfterOrEqual(t, "go1.4.2", GoVersion{1, 4, 2, 0, 0})
	versionAfterOrEqual(t, "go1.5beta2", GoVersion{1, 5, -1, 2, 0})
	versionAfterOrEqual(t, "go1.5rc2", GoVersion{1, 5, -1, 0, 2})
900
	ver, ok := ParseVersionString("devel +17efbfc Tue Jul 28 17:39:19 2015 +0000 linux/amd64")
901 902 903 904 905 906 907
	if !ok {
		t.Fatalf("Could not parse devel version string")
	}
	if !ver.IsDevel() {
		t.Fatalf("Devel version string not correctly recognized")
	}
}
908 909 910 911 912 913 914 915 916 917 918 919 920 921

func TestBreakpointOnFunctionEntry(t *testing.T) {
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
		addr, err := p.FindFunctionLocation("main.main", false, 0)
		assertNoError(err, t, "FindFunctionLocation()")
		_, err = p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		_, ln := currentLineNumber(p, t)
		if ln != 17 {
			t.Fatalf("Wrong line number: %d (expected: 17)\n", ln)
		}
	})
}
922 923 924 925 926 927 928 929 930 931

func TestProcessReceivesSIGCHLD(t *testing.T) {
	withTestProcess("sigchldprog", t, func(p *Process, fixture protest.Fixture) {
		err := p.Continue()
		_, ok := err.(ProcessExitedError)
		if !ok {
			t.Fatalf("Continue() returned unexpected error type %s", err)
		}
	})
}
932 933 934 935 936 937 938 939 940 941

func TestIssue239(t *testing.T) {
	withTestProcess("is sue239", t, func(p *Process, fixture protest.Fixture) {
		pos, _, err := p.goSymTable.LineToPC(fixture.Source, 17)
		assertNoError(err, t, "LineToPC()")
		_, err = p.SetBreakpoint(pos)
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
		assertNoError(p.Continue(), t, fmt.Sprintf("Continue()"))
	})
}
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981

func evalVariable(p *Process, symbol string) (*Variable, error) {
	scope, err := p.CurrentThread.Scope()
	if err != nil {
		return nil, err
	}
	return scope.EvalVariable(symbol)
}

func setVariable(p *Process, symbol, value string) error {
	scope, err := p.CurrentThread.Scope()
	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 已提交
982 983
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
		{"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},
	}

	withTestProcess("testvariables", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue() returned an error")

		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 {
1008 1009 1010
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1011 1012 1013
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1014 1015
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1016 1017 1018
					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 已提交
1019 1020 1021 1022 1023 1024
				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)
					}
1025 1026
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
						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) {
	withTestProcess("goroutinestackprog", t, func(p *Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.stacktraceme")
		assertNoError(err, t, "setFunctionBreakpoint")
		assertNoError(p.Continue(), t, "Continue()")

1050
		// Testing evaluation on goroutines
1051 1052 1053 1054 1055
		gs, err := p.GoroutinesInfo()
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
A
aarzilli 已提交
1056
			frames, err := g.Stacktrace(10)
1057 1058 1059 1060 1061 1062 1063 1064 1065
			assertNoError(err, t, "GoroutineStacktrace()")
			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 已提交
1066
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1067 1068 1069
				continue
			}

D
Derek Parker 已提交
1070
			scope, err := p.ConvertEvalScope(g.ID, frame)
1071 1072 1073 1074 1075
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
			v, err := scope.EvalVariable("i")
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1076
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1077 1078
				continue
			}
1079 1080
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1081 1082 1083 1084 1085 1086 1087 1088
		}

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

1089
		// Testing evaluation on frames
1090 1091 1092 1093 1094
		assertNoError(p.Continue(), t, "Continue() 2")
		g, err := p.CurrentThread.GetG()
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
D
Derek Parker 已提交
1095
			scope, err := p.ConvertEvalScope(g.ID, i+1)
1096 1097 1098
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
			v, err := scope.EvalVariable("n")
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1099
			n, _ := constant.Int64Val(v.Value)
1100 1101 1102 1103 1104 1105 1106 1107 1108
			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) {
1109
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1110 1111 1112 1113 1114
		assertNoError(p.Continue(), t, "Continue() returned an error")

		pval := func(n int64) {
			variable, err := evalVariable(p, "p1")
			assertNoError(err, t, "EvalVariable()")
1115 1116 1117
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1118 1119 1120 1121 1122 1123 1124 1125
			}
		}

		pval(1)

		// change p1 to point to i2
		scope, err := p.CurrentThread.Scope()
		assertNoError(err, t, "Scope()")
A
aarzilli 已提交
1126 1127 1128
		i2addr, err := scope.EvalExpression("i2")
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
		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) {
	withTestProcess("testvariables", t, func(p *Process, fixture protest.Fixture) {
		err := p.Continue()
		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
		err = p.Continue()
		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) {
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue()")
		v, err := evalVariable(p, "aas")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("v: %v\n", v)
	})
}
1170 1171 1172

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1173
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1174 1175 1176 1177 1178
		assertNoError(p.Continue(), t, "Continue()")
		_, err := evalVariable(p, "iface5")
		assertNoError(err, t, "EvalVariable()")
	})
}
1179 1180 1181

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1182
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
		assertNoError(p.Continue(), t, "Continue()")
		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)
	})
}
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

func TestBreakpointCounts(t *testing.T) {
	withTestProcess("bpcountstest", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 12)
		assertNoError(err, t, "LineToPC")
		bp, err := p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")

		for {
			if err := p.Continue(); err != nil {
				if _, exited := err.(ProcessExitedError); exited {
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
		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)
			}
		}
	})
}

1227 1228 1229
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
	b.SetBytes(int64(64 * 128))
1230
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1231 1232 1233 1234 1235 1236 1237 1238
		assertNoError(p.Continue(), b, "Continue()")
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "bencharr")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
const doTestBreakpointCountsWithDetection = false

func TestBreakpointCountsWithDetection(t *testing.T) {
	if !doTestBreakpointCountsWithDetection {
		return
	}
	m := map[int64]int64{}
	withTestProcess("bpcountstest", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 12)
		assertNoError(err, t, "LineToPC")
		bp, err := p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")

		for {
			if err := p.Continue(); err != nil {
				if _, exited := err.(ProcessExitedError); exited {
					break
				}
				assertNoError(err, t, "Continue()")
			}
			fmt.Printf("Continue returned %d\n", bp.TotalHitCount)
			for _, th := range p.Threads {
				if th.CurrentBreakpoint == nil {
					continue
				}
				scope, err := th.Scope()
				assertNoError(err, t, "Scope()")
				v, err := scope.EvalVariable("i")
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
				v, err = scope.EvalVariable("id")
				assertNoError(err, t, "evalVariable")
				id, _ := constant.Int64Val(v.Value)
				m[id] = i
D
Derek Parker 已提交
1273
				fmt.Printf("\tgoroutine (%d) %d: %d\n", th.ID, id, i)
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
			}

			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)
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		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)
			}
		}
	})
}
1302

1303 1304 1305 1306
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))
1307
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
		assertNoError(p.Continue(), b, "Continue()")
		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)))
1321
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1322 1323 1324 1325 1326 1327 1328 1329 1330
		assertNoError(p.Continue(), b, "Continue()")
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "m1")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1331
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1332 1333 1334 1335 1336 1337 1338 1339 1340
		assertNoError(p.Continue(), b, "Continue()")
		for i := 0; i < b.N; i++ {
			p.allGCache = nil
			_, err := p.GoroutinesInfo()
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
	withTestProcess("issue262", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 11)
		assertNoError(err, t, "LineToPC")
		_, err = p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")

		assertNoError(p.Continue(), t, "Continue()")
		err = p.Continue()
		if err == nil {
			t.Fatalf("No error on second continue")
		}
		_, exited := err.(ProcessExitedError)
		if !exited {
			t.Fatalf("Process did not exit after second continue: %v", err)
		}
	})
}
1360

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
func TestIssue305(t *testing.T) {
	// If 'next' hits a breakpoint on the goroutine it's stepping through the temp breakpoints aren't cleared
	// preventing further use of 'next' command
	withTestProcess("issue305", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 5)
		assertNoError(err, t, "LineToPC()")
		_, err = p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")

		assertNoError(p.Continue(), t, "Continue()")

		assertNoError(p.Next(), t, "Next() 1")
		assertNoError(p.Next(), t, "Next() 2")
		assertNoError(p.Next(), t, "Next() 3")
		assertNoError(p.Next(), t, "Next() 4")
		assertNoError(p.Next(), t, "Next() 5")
	})
}

1380 1381
func TestIssue341(t *testing.T) {
	// pointer loop through map entries
1382
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1383 1384 1385 1386 1387 1388 1389
		assertNoError(p.Continue(), t, "Continue()")
		t.Logf("requesting mapinf")
		mapinf, err := evalVariable(p, "mapinf")
		assertNoError(err, t, "EvalVariable()")
		t.Logf("mapinf: %v\n", mapinf)
	})
}
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

func BenchmarkLocalVariables(b *testing.B) {
	withTestProcess("testvariables", b, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), b, "Continue() returned an error")
		scope, err := p.CurrentThread.Scope()
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
			_, err := scope.LocalVariables()
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

func TestCondBreakpoint(t *testing.T) {
	withTestProcess("parallel_next", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 9)
		assertNoError(err, t, "LineToPC")
		bp, err := p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

		assertNoError(p.Continue(), t, "Continue()")

		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) {
	withTestProcess("parallel_next", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 9)
		assertNoError(err, t, "LineToPC")
		bp, err := p.SetBreakpoint(addr)
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

		err = p.Continue()
		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"},
		}

		err = p.Continue()
		if err != nil {
			if _, exited := err.(ProcessExitedError); !exited {
				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)
			}
		}
	})
}
1470 1471 1472

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1473
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1474 1475 1476 1477 1478 1479 1480 1481
		assertNoError(p.Continue(), t, "Continue() returned an error")
		mmvar, err := evalVariable(p, "mainMenu")
		assertNoError(err, t, "EvalVariable()")
		if mmvar.Kind != reflect.Slice {
			t.Fatalf("Wrong kind for mainMenu: %v\n", mmvar.Kind)
		}
	})
}
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504

func TestStepIntoFunction(t *testing.T) {
	withTestProcess("teststep", t, func(p *Process, fixture protest.Fixture) {
		// Continue until breakpoint
		assertNoError(p.Continue(), t, "Continue() returned an error")
		// Step into function
		assertNoError(p.Step(), t, "Step() returned an error")
		// We should now be inside the function.
		loc, err := p.CurrentLocation()
		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)
		}
	})
}
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
	withTestProcess("issue384", t, func(p *Process, fixture protest.Fixture) {
		start, _, err := p.goSymTable.LineToPC(fixture.Source, 13)
		assertNoError(err, t, "LineToPC()")
		_, err = p.SetBreakpoint(start)
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		_, err = evalVariable(p, "st")
		assertNoError(err, t, "EvalVariable()")
	})
}
A
aarzilli 已提交
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

func TestIssue332_Part1(t *testing.T) {
	// Next shouldn't step inside a function call
	withTestProcess("issue332", t, func(p *Process, fixture protest.Fixture) {
		start, _, err := p.goSymTable.LineToPC(fixture.Source, 8)
		assertNoError(err, t, "LineToPC()")
		_, err = p.SetBreakpoint(start)
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		assertNoError(p.Next(), t, "first Next()")
		locations, err := p.CurrentThread.Stacktrace(2)
		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
	withTestProcess("issue332", t, func(p *Process, fixture protest.Fixture) {
		start, _, err := p.goSymTable.LineToPC(fixture.Source, 8)
		assertNoError(err, t, "LineToPC()")
		_, err = p.SetBreakpoint(start)
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")

		// step until we enter changeMe
		for {
			assertNoError(p.Step(), t, "Step()")
			locations, err := p.CurrentThread.Stacktrace(2)
			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
			}
		}

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
		pc, err := p.CurrentThread.PC()
		assertNoError(err, t, "PC()")
		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)
		}

A
aarzilli 已提交
1579 1580 1581 1582 1583 1584 1585 1586 1587
		assertNoError(p.Next(), t, "first Next()")
		assertNoError(p.Next(), t, "second Next()")
		assertNoError(p.Next(), t, "third Next()")
		err = p.Continue()
		if _, exited := err.(ProcessExitedError); !exited {
			assertNoError(err, t, "final Continue()")
		}
	})
}
1588 1589 1590 1591 1592 1593 1594

func TestIssue396(t *testing.T) {
	withTestProcess("callme", t, func(p *Process, fixture protest.Fixture) {
		_, err := p.FindFunctionLocation("main.init", true, -1)
		assertNoError(err, t, "FindFunctionLocation()")
	})
}
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614

func TestIssue414(t *testing.T) {
	// Stepping until the program exits
	withTestProcess("math", t, func(p *Process, fixture protest.Fixture) {
		start, _, err := p.goSymTable.LineToPC(fixture.Source, 9)
		assertNoError(err, t, "LineToPC()")
		_, err = p.SetBreakpoint(start)
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		for {
			err := p.Step()
			if err != nil {
				if _, exited := err.(ProcessExitedError); exited {
					break
				}
			}
			assertNoError(err, t, "Step()")
		}
	})
}
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

func TestPackageVariables(t *testing.T) {
	withTestProcess("testvariables", t, func(p *Process, fixture protest.Fixture) {
		err := p.Continue()
		assertNoError(err, t, "Continue()")
		scope, err := p.CurrentThread.Scope()
		assertNoError(err, t, "Scope()")
		vars, err := scope.PackageVariables()
		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")
		}
	})
}
1636 1637 1638

func TestIssue149(t *testing.T) {
	ver, _ := ParseVersionString(runtime.Version())
A
aarzilli 已提交
1639
	if ver.Major > 0 && !ver.AfterOrEqual(GoVersion{1, 7, 0, 0, 0}) {
1640 1641 1642 1643 1644 1645 1646 1647
		return
	}
	// setting breakpoint on break statement
	withTestProcess("break", t, func(p *Process, fixture protest.Fixture) {
		_, err := p.FindFileLocation(fixture.Source, 8)
		assertNoError(err, t, "FindFileLocation()")
	})
}
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657

func TestPanicBreakpoint(t *testing.T) {
	withTestProcess("panic", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue()")
		bp := p.CurrentBreakpoint()
		if bp == nil || bp.Name != "unrecovered-panic" {
			t.Fatalf("not on unrecovered-panic breakpoint: %v", p.CurrentBreakpoint)
		}
	})
}
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687

func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
	withTestProcess("testnextnethttp", t, func(p *Process, fixture protest.Fixture) {
		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()
		}()

		assertNoError(p.Continue(), t, "Continue()")
		_, err := p.CurrentThread.Stacktrace(40)
		assertNoError(err, t, "Stacktrace()")
	})
}