proc_test.go 72.7 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
	"os/exec"
13
	"path/filepath"
14
	"reflect"
15
	"runtime"
16
	"strings"
D
Derek Parker 已提交
17
	"testing"
D
Derek Parker 已提交
18
	"time"
D
Dan Mace 已提交
19

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

23 24
var normalLoadConfig = LoadConfig{true, 1, 64, 64, -1}

25
func init() {
26 27
	runtime.GOMAXPROCS(4)
	os.Setenv("GOMAXPROCS", "4")
28 29
}

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

34
func withTestProcess(name string, t testing.TB, fn func(p *Process, fixture protest.Fixture)) {
35
	fixture := protest.BuildFixture(name)
E
Evgeny L 已提交
36
	p, err := Launch([]string{fixture.Path}, ".")
37 38 39 40
	if err != nil {
		t.Fatal("Launch():", err)
	}

41 42
	defer func() {
		p.Halt()
43
		p.Kill()
44
	}()
45

D
Dan Mace 已提交
46
	fn(p, fixture)
47 48
}

E
Evgeny L 已提交
49
func withTestProcessArgs(name string, t testing.TB, wd string, fn func(p *Process, fixture protest.Fixture), args []string) {
50
	fixture := protest.BuildFixture(name)
E
Evgeny L 已提交
51
	p, err := Launch(append([]string{fixture.Path}, args...), wd)
52 53 54 55 56 57 58 59 60 61 62 63
	if err != nil {
		t.Fatal("Launch():", err)
	}

	defer func() {
		p.Halt()
		p.Kill()
	}()

	fn(p, fixture)
}

D
Derek Parker 已提交
64
func getRegisters(p *Process, t *testing.T) Registers {
65 66 67 68 69 70 71 72
	regs, err := p.Registers()
	if err != nil {
		t.Fatal("Registers():", err)
	}

	return regs
}

D
Derek Parker 已提交
73
func dataAtAddr(thread *Thread, addr uint64) ([]byte, error) {
D
Derek Parker 已提交
74
	return thread.readMemory(uintptr(addr), 1)
75 76
}

77
func assertNoError(err error, t testing.TB, s string) {
78
	if err != nil {
79 80
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
81
		t.Fatalf("failed assertion at %s:%d: %s - %s\n", fname, line, s, err)
82 83 84
	}
}

D
Derek Parker 已提交
85
func currentPC(p *Process, t *testing.T) uint64 {
D
Derek Parker 已提交
86
	pc, err := p.PC()
87 88 89 90 91 92 93
	if err != nil {
		t.Fatal(err)
	}

	return pc
}

D
Derek Parker 已提交
94
func currentLineNumber(p *Process, t *testing.T) (string, int) {
95
	pc := currentPC(p, t)
96
	f, l, _ := p.goSymTable.PCToLine(pc)
97

D
Derek Parker 已提交
98
	return f, l
99 100
}

101
func TestExit(t *testing.T) {
D
Derek Parker 已提交
102
	withTestProcess("continuetestprog", t, func(p *Process, fixture protest.Fixture) {
103 104 105
		err := p.Continue()
		pe, ok := err.(ProcessExitedError)
		if !ok {
106
			t.Fatalf("Continue() returned unexpected error type %s", err)
107 108 109 110
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
D
Derek Parker 已提交
111
		if pe.Pid != p.pid {
112 113 114 115 116
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

117 118 119 120 121 122 123 124
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 已提交
125
			t.Fatalf("Continue() returned unexpected error type %s", pe)
126 127 128 129
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
D
Derek Parker 已提交
130
		if pe.Pid != p.pid {
131 132 133 134 135
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

136 137 138 139 140
func setFunctionBreakpoint(p *Process, fname string) (*Breakpoint, error) {
	addr, err := p.FindFunctionLocation(fname, true, 0)
	if err != nil {
		return nil, err
	}
141
	return p.SetBreakpoint(addr, UserBreakpoint, nil)
142 143
}

A
aarzilli 已提交
144 145 146 147 148 149 150 151 152 153 154 155
func setFileBreakpoint(p *Process, t *testing.T, fixture protest.Fixture, lineno int) *Breakpoint {
	addr, err := p.FindFileLocation(fixture.Source, lineno)
	if err != nil {
		t.Fatalf("FindFileLocation: %v", err)
	}
	bp, err := p.SetBreakpoint(addr, UserBreakpoint, nil)
	if err != nil {
		t.Fatalf("SetBreakpoint: %v", err)
	}
	return bp
}

D
Derek Parker 已提交
156
func TestHalt(t *testing.T) {
157 158
	stopChan := make(chan interface{})
	withTestProcess("loopprog", t, func(p *Process, fixture protest.Fixture) {
159
		_, err := setFunctionBreakpoint(p, "main.loop")
160 161
		assertNoError(err, t, "SetBreakpoint")
		assertNoError(p.Continue(), t, "Continue")
D
Derek Parker 已提交
162
		for _, th := range p.threads {
163
			if th.running != false {
D
Derek Parker 已提交
164
				t.Fatal("expected running = false for thread", th.ID)
165
			}
A
aarzilli 已提交
166
			_, err := th.Registers(false)
167 168
			assertNoError(err, t, "Registers")
		}
D
Derek Parker 已提交
169
		go func() {
D
Dan Mace 已提交
170 171
			for {
				if p.Running() {
172
					if err := p.RequestManualStop(); err != nil {
D
Dan Mace 已提交
173 174
						t.Fatal(err)
					}
175
					stopChan <- nil
D
Dan Mace 已提交
176 177
					return
				}
D
Derek Parker 已提交
178 179
			}
		}()
180 181
		assertNoError(p.Continue(), t, "Continue")
		<-stopChan
D
Derek Parker 已提交
182 183 184
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
D
Derek Parker 已提交
185
		for _, th := range p.threads {
186 187 188
			if !th.Stopped() {
				t.Fatal("expected thread to be stopped, but was not")
			}
189
			if th.running != false {
D
Derek Parker 已提交
190
				t.Fatal("expected running = false for thread", th.ID)
D
Derek Parker 已提交
191
			}
A
aarzilli 已提交
192
			_, err := th.Registers(false)
193
			assertNoError(err, t, "Registers")
D
Derek Parker 已提交
194 195 196 197
		}
	})
}

198
func TestStep(t *testing.T) {
D
Derek Parker 已提交
199
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
200
		helloworldfunc := p.goSymTable.LookupFunc("main.helloworld")
201 202
		helloworldaddr := helloworldfunc.Entry

203
		_, err := p.SetBreakpoint(helloworldaddr, UserBreakpoint, nil)
204
		assertNoError(err, t, "SetBreakpoint()")
205 206
		assertNoError(p.Continue(), t, "Continue()")

207
		regs := getRegisters(p, t)
208
		rip := regs.PC()
209

D
Derek Parker 已提交
210
		err = p.currentThread.StepInstruction()
D
Derek Parker 已提交
211
		assertNoError(err, t, "Step()")
212

213
		regs = getRegisters(p, t)
214 215 216 217 218
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
219

D
Derek Parker 已提交
220
func TestBreakpoint(t *testing.T) {
D
Derek Parker 已提交
221
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
222
		helloworldfunc := p.goSymTable.LookupFunc("main.helloworld")
D
Derek Parker 已提交
223
		helloworldaddr := helloworldfunc.Entry
224

225
		bp, err := p.SetBreakpoint(helloworldaddr, UserBreakpoint, nil)
226
		assertNoError(err, t, "SetBreakpoint()")
D
Derek Parker 已提交
227
		assertNoError(p.Continue(), t, "Continue()")
228

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

234 235 236 237
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
238
		if pc-1 != bp.Addr && pc != bp.Addr {
239
			f, l, _ := p.goSymTable.PCToLine(pc)
D
Derek Parker 已提交
240
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
241 242
		}
	})
243
}
244

D
Derek Parker 已提交
245
func TestBreakpointInSeperateGoRoutine(t *testing.T) {
D
Derek Parker 已提交
246
	withTestProcess("testthreads", t, func(p *Process, fixture protest.Fixture) {
247
		fn := p.goSymTable.LookupFunc("main.anotherthread")
248 249 250 251
		if fn == nil {
			t.Fatal("No fn exists")
		}

252
		_, err := p.SetBreakpoint(fn.Entry, UserBreakpoint, nil)
253 254 255 256 257 258 259 260 261
		if err != nil {
			t.Fatal(err)
		}

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

D
Derek Parker 已提交
262
		pc, err := p.PC()
263 264 265 266
		if err != nil {
			t.Fatal(err)
		}

267
		f, l, _ := p.goSymTable.PCToLine(pc)
268 269 270 271 272 273
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
274
func TestBreakpointWithNonExistantFunction(t *testing.T) {
D
Derek Parker 已提交
275
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
276
		_, err := p.SetBreakpoint(0, UserBreakpoint, nil)
277 278 279 280
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
281
}
282

283
func TestClearBreakpointBreakpoint(t *testing.T) {
D
Derek Parker 已提交
284
	withTestProcess("testprog", t, func(p *Process, fixture protest.Fixture) {
285
		fn := p.goSymTable.LookupFunc("main.sleepytime")
286
		bp, err := p.SetBreakpoint(fn.Entry, UserBreakpoint, nil)
287
		assertNoError(err, t, "SetBreakpoint()")
288

289 290
		bp, err = p.ClearBreakpoint(fn.Entry)
		assertNoError(err, t, "ClearBreakpoint()")
291

D
Derek Parker 已提交
292
		data, err := dataAtAddr(p.currentThread, bp.Addr)
293 294 295 296
		if err != nil {
			t.Fatal(err)
		}

297
		int3 := []byte{0xcc}
298 299 300 301
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

302
		if countBreakpoints(p) != 0 {
303 304 305
			t.Fatal("Breakpoint not removed internally")
		}
	})
306
}
307

308 309 310
type nextTest struct {
	begin, end int
}
311

312 313
func countBreakpoints(p *Process) int {
	bpcount := 0
D
Derek Parker 已提交
314
	for _, bp := range p.breakpoints {
315 316 317 318 319 320 321
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

A
aarzilli 已提交
322 323 324 325 326 327 328 329
type contFunc int

const (
	contNext contFunc = iota
	contStep
)

func testseq(program string, contFunc contFunc, testcases []nextTest, initialLocation string, t *testing.T) {
D
Derek Parker 已提交
330
	withTestProcess(program, t, func(p *Process, fixture protest.Fixture) {
A
aarzilli 已提交
331 332 333 334 335 336 337 338
		var bp *Breakpoint
		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()")
339
			bp, err = p.SetBreakpoint(pc, UserBreakpoint, nil)
A
aarzilli 已提交
340
		}
341
		assertNoError(err, t, "SetBreakpoint()")
342
		assertNoError(p.Continue(), t, "Continue()")
343
		p.ClearBreakpoint(bp.Addr)
D
Derek Parker 已提交
344
		p.currentThread.SetPC(bp.Addr)
345

D
Derek Parker 已提交
346
		f, ln := currentLineNumber(p, t)
347
		for _, tc := range testcases {
D
Derek Parker 已提交
348
			pc, _ := p.currentThread.PC()
349
			if ln != tc.begin {
D
Derek Parker 已提交
350
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
351 352
			}

A
aarzilli 已提交
353 354 355 356 357 358
			switch contFunc {
			case contNext:
				assertNoError(p.Next(), t, "Next() returned an error")
			case contStep:
				assertNoError(p.Step(), t, "Step() returned an error")
			}
359

D
Derek Parker 已提交
360
			f, ln = currentLineNumber(p, t)
D
Derek Parker 已提交
361
			pc, _ = p.currentThread.PC()
362
			if ln != tc.end {
A
aarzilli 已提交
363
				t.Fatalf("Program did not continue to correct next location expected %d was %s:%d (%#x)", tc.end, filepath.Base(f), ln, pc)
364 365
			}
		}
366

367
		if countBreakpoints(p) != 0 {
D
Derek Parker 已提交
368
			t.Fatal("Not all breakpoints were cleaned up", len(p.breakpoints))
369
		}
370 371
	})
}
372

373
func TestNextGeneral(t *testing.T) {
374 375 376 377
	var testcases []nextTest

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

378
	if ver.Major < 0 || ver.AfterOrEqual(GoVersion{1, 7, -1, 0, 0}) {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
		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},
		}
415
	}
416

A
aarzilli 已提交
417
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
418 419
}

420 421
func TestNextConcurrent(t *testing.T) {
	testcases := []nextTest{
422
		{8, 9},
423 424 425 426
		{9, 10},
		{10, 11},
	}
	withTestProcess("parallel_next", t, func(p *Process, fixture protest.Fixture) {
427
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
428 429 430
		assertNoError(err, t, "SetBreakpoint")
		assertNoError(p.Continue(), t, "Continue")
		f, ln := currentLineNumber(p, t)
431
		initV, err := evalVariable(p, "n")
432
		initVval, _ := constant.Int64Val(initV.Value)
433
		assertNoError(err, t, "EvalVariable")
434 435
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")
436
		for _, tc := range testcases {
D
Derek Parker 已提交
437
			g, err := p.currentThread.GetG()
438
			assertNoError(err, t, "GetG()")
D
Derek Parker 已提交
439 440
			if p.selectedGoroutine.ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.selectedGoroutine.ID)
441
			}
442 443 444 445 446 447 448 449
			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)
			}
450
			v, err := evalVariable(p, "n")
451
			assertNoError(err, t, "EvalVariable")
452 453
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
454 455 456 457 458 459
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

460 461 462
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{
463
		{8, 9},
464 465 466 467 468 469 470 471 472 473 474 475
		{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 {
D
Derek Parker 已提交
476
			g, err := p.currentThread.GetG()
477
			assertNoError(err, t, "GetG()")
D
Derek Parker 已提交
478 479
			if p.selectedGoroutine.ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.selectedGoroutine.ID)
480 481 482 483 484 485 486 487 488 489
			}
			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)
D
Derek Parker 已提交
490
				if p.currentThread.CurrentBreakpoint == nil {
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
					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)
			}
		}
	})
}

510 511
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
512
		{13, 14},
D
Derek Parker 已提交
513 514
		{14, 15},
		{15, 35},
515
	}
A
aarzilli 已提交
516
	testseq("testnextprog", contNext, testcases, "main.helloworld", t)
517 518 519 520
}

func TestNextFunctionReturnDefer(t *testing.T) {
	testcases := []nextTest{
521
		{5, 8},
D
Derek Parker 已提交
522 523
		{8, 9},
		{9, 10},
524 525
		{10, 6},
		{6, 7},
D
Derek Parker 已提交
526
		{7, 8},
527
	}
A
aarzilli 已提交
528
	testseq("testnextdefer", contNext, testcases, "main.main", t)
529 530
}

D
Derek Parker 已提交
531 532 533 534 535 536 537 538 539 540 541 542
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 已提交
543
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
544 545 546 547 548 549
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
550
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
		}()
		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 已提交
571
func TestRuntimeBreakpoint(t *testing.T) {
D
Derek Parker 已提交
572
	withTestProcess("testruntimebreakpoint", t, func(p *Process, fixture protest.Fixture) {
D
Derek Parker 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
		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")
		}
	})
}

588
func TestFindReturnAddress(t *testing.T) {
D
Derek Parker 已提交
589
	withTestProcess("testnextprog", t, func(p *Process, fixture protest.Fixture) {
590
		start, _, err := p.goSymTable.LineToPC(fixture.Source, 24)
591 592 593
		if err != nil {
			t.Fatal(err)
		}
594
		_, err = p.SetBreakpoint(start, UserBreakpoint, nil)
595 596 597 598 599 600 601
		if err != nil {
			t.Fatal(err)
		}
		err = p.Continue()
		if err != nil {
			t.Fatal(err)
		}
D
Derek Parker 已提交
602
		addr, err := p.currentThread.ReturnAddress()
603 604 605
		if err != nil {
			t.Fatal(err)
		}
606 607 608
		_, l, _ := p.goSymTable.PCToLine(addr)
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
609
		}
610 611
	})
}
612

613 614 615 616 617 618 619
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)
		}
620
		if _, err := p.SetBreakpoint(fn.Entry, UserBreakpoint, nil); err != nil {
621 622
			t.Fatal(err)
		}
623
		if err := p.Continue(); err != nil {
D
Derek Parker 已提交
624 625
			t.Fatal(err)
		}
D
Derek Parker 已提交
626
		if _, err := p.currentThread.ReturnAddress(); err == nil {
627
			t.Fatal("expected error to be returned")
628 629 630
		}
	})
}
D
Derek Parker 已提交
631 632

func TestSwitchThread(t *testing.T) {
D
Derek Parker 已提交
633
	withTestProcess("testnextprog", t, func(p *Process, fixture protest.Fixture) {
D
Derek Parker 已提交
634 635 636 637 638
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
639
		pc, err := p.FindFunctionLocation("main.main", true, 0)
D
Derek Parker 已提交
640 641 642
		if err != nil {
			t.Fatal(err)
		}
643
		_, err = p.SetBreakpoint(pc, UserBreakpoint, nil)
D
Derek Parker 已提交
644 645 646 647 648 649 650 651
		if err != nil {
			t.Fatal(err)
		}
		err = p.Continue()
		if err != nil {
			t.Fatal(err)
		}
		var nt int
D
Derek Parker 已提交
652 653
		ct := p.currentThread.ID
		for tid := range p.threads {
D
Derek Parker 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666
			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 已提交
667
		if p.currentThread.ID != nt {
D
Derek Parker 已提交
668 669 670 671
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
672

673 674 675 676 677 678
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 已提交
679 680 681
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
682 683 684 685 686 687

	withTestProcess("cgotest", t, func(p *Process, fixture protest.Fixture) {
		pc, err := p.FindFunctionLocation("main.main", true, 0)
		if err != nil {
			t.Fatal(err)
		}
688
		_, err = p.SetBreakpoint(pc, UserBreakpoint, nil)
689 690 691 692 693 694 695 696 697 698 699 700 701 702
		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 已提交
703 704 705 706 707
type loc struct {
	line int
	fn   string
}

708
func (l1 *loc) match(l2 Stackframe) bool {
A
aarzilli 已提交
709
	if l1.line >= 0 {
710
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
711 712 713
			return false
		}
	}
714
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
715 716 717 718
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
719 720
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
721
	}
D
Derek Parker 已提交
722
	withTestProcess("stacktraceprog", t, func(p *Process, fixture protest.Fixture) {
723
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
724 725 726 727
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
			assertNoError(p.Continue(), t, "Continue()")
D
Derek Parker 已提交
728
			locations, err := p.currentThread.Stacktrace(40)
A
aarzilli 已提交
729 730 731 732 733 734
			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)
			}

735 736 737 738
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
739

A
aarzilli 已提交
740 741 742 743 744 745 746
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

747
		p.ClearBreakpoint(bp.Addr)
A
aarzilli 已提交
748 749 750 751
		p.Continue()
	})
}

752 753 754 755
func TestStacktrace2(t *testing.T) {
	withTestProcess("retstack", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue()")

D
Derek Parker 已提交
756
		locations, err := p.currentThread.Stacktrace(40)
757
		assertNoError(err, t, "Stacktrace()")
758
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
759 760 761
			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 已提交
762
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
763 764 765
		}

		assertNoError(p.Continue(), t, "Continue()")
D
Derek Parker 已提交
766
		locations, err = p.currentThread.Stacktrace(40)
767
		assertNoError(err, t, "Stacktrace()")
768
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
769 770 771
			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 已提交
772
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
773 774 775 776 777
		}
	})

}

778
func stackMatch(stack []loc, locations []Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
779 780 781
	if len(stack) > len(locations) {
		return false
	}
782 783 784 785 786 787 788 789 790 791 792
	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 已提交
793 794
			return false
		}
795
		i++
A
aarzilli 已提交
796
	}
797
	return i >= len(stack)
A
aarzilli 已提交
798 799 800
}

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

D
Derek Parker 已提交
805
	withTestProcess("goroutinestackprog", t, func(p *Process, fixture protest.Fixture) {
806
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
807 808 809 810 811 812 813 814 815 816
		assertNoError(err, t, "BreakByLocation()")

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

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

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
817
		for i, g := range gs {
A
aarzilli 已提交
818
			locations, err := g.Stacktrace(40)
819 820
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
821
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
822 823
				continue
			}
A
aarzilli 已提交
824

825
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
826 827 828
				mainCount++
			}

829 830 831
			if stackMatch(agoroutineStackA, locations, true) {
				agoroutineCount++
			} else if stackMatch(agoroutineStackB, locations, true) {
A
aarzilli 已提交
832 833
				agoroutineCount++
			} else {
D
Derek Parker 已提交
834
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
835 836
				for i := range locations {
					name := ""
837 838
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
839
					}
840
					t.Logf("\t%s:%d %s\n", locations[i].Call.File, locations[i].Call.Line, name)
A
aarzilli 已提交
841 842 843 844 845
				}
			}
		}

		if mainCount != 1 {
846
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
847 848 849 850 851 852
		}

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

853
		p.ClearBreakpoint(bp.Addr)
A
aarzilli 已提交
854 855 856
		p.Continue()
	})
}
857 858 859 860 861 862 863 864 865 866

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" {
D
Derek Parker 已提交
867
			_, err := os.Open(fmt.Sprintf("/proc/%d/", p.pid))
868
			if err == nil {
D
Derek Parker 已提交
869
				t.Fatal("process has not exited", p.pid)
870 871 872 873
			}
		}
	})
}
874 875

func testGSupportFunc(name string, t *testing.T, p *Process, fixture protest.Fixture) {
876
	bp, err := setFunctionBreakpoint(p, "main.main")
877 878 879 880
	assertNoError(err, t, name+": BreakByLocation()")

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

D
Derek Parker 已提交
881
	g, err := p.currentThread.GetG()
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
	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)
	})

898 899 900 901
	// 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 已提交
902 903 904
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
905

906 907 908 909
	withTestProcess("cgotest", t, func(p *Process, fixture protest.Fixture) {
		testGSupportFunc("cgo", t, p, fixture)
	})
}
910 911 912

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

916
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
917 918 919 920 921 922
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
			err := p.Continue()
923
			if p.Exited() {
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
				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)
		}
	})
}
946

947
func versionAfterOrEqual(t *testing.T, verStr string, ver GoVersion) {
948
	pver, ok := ParseVersionString(verStr)
949 950 951
	if !ok {
		t.Fatalf("Could not parse version string <%s>", verStr)
	}
952
	if !pver.AfterOrEqual(ver) {
953 954 955 956 957 958
		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 已提交
959
	versionAfterOrEqual(t, "go1.4", GoVersion{1, 4, 0, 0, 0})
D
Derek Parker 已提交
960 961 962 963
	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})
964
	versionAfterOrEqual(t, "go1.6.1 (appengine-1.9.37)", GoVersion{1, 6, 1, 0, 0})
965
	ver, ok := ParseVersionString("devel +17efbfc Tue Jul 28 17:39:19 2015 +0000 linux/amd64")
966 967 968 969 970 971 972
	if !ok {
		t.Fatalf("Could not parse devel version string")
	}
	if !ver.IsDevel() {
		t.Fatalf("Devel version string not correctly recognized")
	}
}
973 974 975 976 977

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()")
978
		_, err = p.SetBreakpoint(addr, UserBreakpoint, nil)
979 980 981 982 983 984 985 986
		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)
		}
	})
}
987 988 989 990 991 992 993 994 995 996

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)
		}
	})
}
997 998 999 1000 1001

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()")
1002
		_, err = p.SetBreakpoint(pos, UserBreakpoint, nil)
1003 1004 1005 1006
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
		assertNoError(p.Continue(), t, fmt.Sprintf("Continue()"))
	})
}
1007 1008

func evalVariable(p *Process, symbol string) (*Variable, error) {
D
Derek Parker 已提交
1009
	scope, err := p.currentThread.Scope()
1010 1011 1012
	if err != nil {
		return nil, err
	}
1013
	return scope.EvalVariable(symbol, normalLoadConfig)
1014 1015 1016
}

func setVariable(p *Process, symbol, value string) error {
D
Derek Parker 已提交
1017
	scope, err := p.currentThread.Scope()
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
	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 已提交
1047 1048
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
		{"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 {
1073 1074 1075
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1076 1077 1078
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1079 1080
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1081 1082 1083
					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 已提交
1084 1085 1086 1087 1088 1089
				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)
					}
1090 1091
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
						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()")

1115
		// Testing evaluation on goroutines
1116 1117 1118 1119 1120
		gs, err := p.GoroutinesInfo()
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
A
aarzilli 已提交
1121
			frames, err := g.Stacktrace(10)
1122 1123 1124 1125 1126 1127 1128 1129 1130
			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 已提交
1131
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1132 1133 1134
				continue
			}

D
Derek Parker 已提交
1135
			scope, err := p.ConvertEvalScope(g.ID, frame)
1136 1137
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
1138
			v, err := scope.EvalVariable("i", normalLoadConfig)
1139 1140
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1141
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1142 1143
				continue
			}
1144 1145
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1146 1147 1148 1149 1150 1151 1152 1153
		}

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

1154
		// Testing evaluation on frames
1155
		assertNoError(p.Continue(), t, "Continue() 2")
D
Derek Parker 已提交
1156
		g, err := p.currentThread.GetG()
1157 1158 1159
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
D
Derek Parker 已提交
1160
			scope, err := p.ConvertEvalScope(g.ID, i+1)
1161
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
1162
			v, err := scope.EvalVariable("n", normalLoadConfig)
1163
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1164
			n, _ := constant.Int64Val(v.Value)
1165 1166 1167 1168 1169 1170 1171 1172 1173
			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) {
1174
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1175 1176 1177 1178 1179
		assertNoError(p.Continue(), t, "Continue() returned an error")

		pval := func(n int64) {
			variable, err := evalVariable(p, "p1")
			assertNoError(err, t, "EvalVariable()")
1180 1181 1182
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1183 1184 1185 1186 1187 1188
			}
		}

		pval(1)

		// change p1 to point to i2
D
Derek Parker 已提交
1189
		scope, err := p.currentThread.Scope()
1190
		assertNoError(err, t, "Scope()")
1191
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1192 1193
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
		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)
	})
}
1235 1236 1237

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1238
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1239 1240 1241 1242 1243
		assertNoError(p.Continue(), t, "Continue()")
		_, err := evalVariable(p, "iface5")
		assertNoError(err, t, "EvalVariable()")
	})
}
1244 1245 1246

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1247
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
		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)
	})
}
1258 1259 1260 1261 1262

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")
1263
		bp, err := p.SetBreakpoint(addr, UserBreakpoint, nil)
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
		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)
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
		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)
			}
		}
	})
}

1292 1293 1294
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
	b.SetBytes(int64(64 * 128))
1295
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1296 1297 1298 1299 1300 1301 1302 1303
		assertNoError(p.Continue(), b, "Continue()")
		for i := 0; i < b.N; i++ {
			_, err := evalVariable(p, "bencharr")
			assertNoError(err, b, "EvalVariable()")
		}
	})
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
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")
1314
		bp, err := p.SetBreakpoint(addr, UserBreakpoint, nil)
1315 1316 1317 1318 1319 1320 1321 1322 1323
		assertNoError(err, t, "SetBreakpoint()")

		for {
			if err := p.Continue(); err != nil {
				if _, exited := err.(ProcessExitedError); exited {
					break
				}
				assertNoError(err, t, "Continue()")
			}
D
Derek Parker 已提交
1324
			for _, th := range p.threads {
1325 1326 1327 1328 1329
				if th.CurrentBreakpoint == nil {
					continue
				}
				scope, err := th.Scope()
				assertNoError(err, t, "Scope()")
1330
				v, err := scope.EvalVariable("i", normalLoadConfig)
1331 1332
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
1333
				v, err = scope.EvalVariable("id", normalLoadConfig)
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
				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)
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
		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)
			}
		}
	})
}
1365

1366 1367 1368 1369
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))
1370
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
		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)))
1384
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1385 1386 1387 1388 1389 1390 1391 1392 1393
		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) {
1394
	withTestProcess("testvariables2", b, func(p *Process, fixture protest.Fixture) {
1395 1396 1397 1398 1399 1400 1401 1402 1403
		assertNoError(p.Continue(), b, "Continue()")
		for i := 0; i < b.N; i++ {
			p.allGCache = nil
			_, err := p.GoroutinesInfo()
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1404 1405 1406 1407 1408
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")
1409
		_, err = p.SetBreakpoint(addr, UserBreakpoint, nil)
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
		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)
		}
	})
}
1423

1424
func TestIssue305(t *testing.T) {
1425 1426 1427
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1428 1429 1430
	withTestProcess("issue305", t, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 5)
		assertNoError(err, t, "LineToPC()")
1431
		_, err = p.SetBreakpoint(addr, UserBreakpoint, nil)
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
		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")
	})
}

1444 1445 1446
func TestPointerLoops(t *testing.T) {
	// Pointer loops through map entries, pointers and slices
	// Regression test for issue #341
1447
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1448
		assertNoError(p.Continue(), t, "Continue()")
1449 1450 1451 1452 1453 1454
		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)
		}
1455 1456
	})
}
1457 1458 1459 1460

func BenchmarkLocalVariables(b *testing.B) {
	withTestProcess("testvariables", b, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), b, "Continue() returned an error")
D
Derek Parker 已提交
1461
		scope, err := p.currentThread.Scope()
1462 1463
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
1464
			_, err := scope.LocalVariables(normalLoadConfig)
1465 1466 1467 1468
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1469 1470 1471 1472 1473

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")
1474
		bp, err := p.SetBreakpoint(addr, UserBreakpoint, nil)
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
		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")
1498
		bp, err := p.SetBreakpoint(addr, UserBreakpoint, nil)
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
		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)
			}
		}
	})
}
1537 1538 1539

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1540
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
1541 1542 1543 1544 1545 1546 1547 1548
		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)
		}
	})
}
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

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)
		}
	})
}
1572 1573 1574 1575 1576 1577

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()")
1578
		_, err = p.SetBreakpoint(start, UserBreakpoint, nil)
1579 1580 1581 1582 1583 1584
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		_, err = evalVariable(p, "st")
		assertNoError(err, t, "EvalVariable()")
	})
}
A
aarzilli 已提交
1585 1586 1587 1588 1589 1590

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()")
1591
		_, err = p.SetBreakpoint(start, UserBreakpoint, nil)
A
aarzilli 已提交
1592 1593 1594
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		assertNoError(p.Next(), t, "first Next()")
D
Derek Parker 已提交
1595
		locations, err := p.currentThread.Stacktrace(2)
A
aarzilli 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
		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()")
1617
		_, err = p.SetBreakpoint(start, UserBreakpoint, nil)
A
aarzilli 已提交
1618 1619 1620 1621 1622 1623
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")

		// step until we enter changeMe
		for {
			assertNoError(p.Step(), t, "Step()")
D
Derek Parker 已提交
1624
			locations, err := p.currentThread.Stacktrace(2)
A
aarzilli 已提交
1625 1626 1627 1628 1629 1630 1631 1632 1633
			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
			}
		}

D
Derek Parker 已提交
1634
		pc, err := p.currentThread.PC()
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
		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 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654
		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()")
		}
	})
}
1655 1656 1657 1658 1659 1660 1661

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()")
	})
}
1662 1663 1664 1665 1666 1667

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()")
1668
		_, err = p.SetBreakpoint(start, UserBreakpoint, nil)
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
		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()")
		}
	})
}
1682 1683 1684 1685 1686

func TestPackageVariables(t *testing.T) {
	withTestProcess("testvariables", t, func(p *Process, fixture protest.Fixture) {
		err := p.Continue()
		assertNoError(err, t, "Continue()")
D
Derek Parker 已提交
1687
		scope, err := p.currentThread.Scope()
1688
		assertNoError(err, t, "Scope()")
1689
		vars, err := scope.PackageVariables(normalLoadConfig)
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
		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")
		}
	})
}
1703 1704 1705

func TestIssue149(t *testing.T) {
	ver, _ := ParseVersionString(runtime.Version())
1706
	if ver.Major > 0 && !ver.AfterOrEqual(GoVersion{1, 7, -1, 0, 0}) {
1707 1708 1709 1710 1711 1712 1713 1714
		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()")
	})
}
1715 1716 1717 1718 1719 1720

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" {
D
Derek Parker 已提交
1721
			t.Fatalf("not on unrecovered-panic breakpoint: %v", p.CurrentBreakpoint())
1722 1723 1724
		}
	})
}
1725

1726 1727 1728 1729 1730
func TestCmdLineArgs(t *testing.T) {
	expectSuccess := func(p *Process, fixture protest.Fixture) {
		err := p.Continue()
		bp := p.CurrentBreakpoint()
		if bp != nil && bp.Name == "unrecovered-panic" {
D
Derek Parker 已提交
1731
			t.Fatalf("testing args failed on unrecovered-panic breakpoint: %v", p.CurrentBreakpoint())
1732 1733 1734
		}
		exit, exited := err.(ProcessExitedError)
		if !exited {
1735
			t.Fatalf("Process did not exit: %v", err)
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
		} else {
			if exit.Status != 0 {
				t.Fatalf("process exited with invalid status", exit.Status)
			}
		}
	}

	expectPanic := func(p *Process, fixture protest.Fixture) {
		p.Continue()
		bp := p.CurrentBreakpoint()
		if bp == nil || bp.Name != "unrecovered-panic" {
D
Derek Parker 已提交
1747
			t.Fatalf("not on unrecovered-panic breakpoint: %v", p.CurrentBreakpoint())
1748 1749 1750 1751
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
E
Evgeny L 已提交
1752 1753
	withTestProcessArgs("testargs", t, ".", expectSuccess, []string{"test"})
	withTestProcessArgs("testargs", t, ".", expectSuccess, []string{"test", "pass flag"})
1754
	// check that arguments with spaces are *only* passed correctly when correctly called
E
Evgeny L 已提交
1755 1756 1757
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test pass", "flag"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test", "pass", "flag"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test pass flag"})
1758 1759
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
E
Evgeny L 已提交
1760 1761 1762
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"invalid"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"test", "invalid"})
	withTestProcessArgs("testargs", t, ".", expectPanic, []string{"invalid", "pass flag"})
1763 1764
}

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
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()")
D
Derek Parker 已提交
1790
		_, err := p.currentThread.Stacktrace(40)
1791 1792 1793
		assertNoError(err, t, "Stacktrace()")
	})
}
1794 1795 1796 1797 1798 1799 1800 1801 1802

func TestIssue554(t *testing.T) {
	// unsigned integer overflow in proc.(*memCache).contains was
	// causing it to always return true for address 0xffffffffffffffff
	mem := memCache{0x20, make([]byte, 100), nil}
	if mem.contains(0xffffffffffffffff, 40) {
		t.Fatalf("should be false")
	}
}
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834

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

		// continue until a parked goroutine exists
		var parkedg *G
	LookForParkedG:
		for {
			err := p.Continue()
			if _, exited := err.(ProcessExitedError); exited {
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

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

			for _, g := range gs {
				if g.thread == nil {
					parkedg = g
					break LookForParkedG
				}
			}
		}

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

D
Derek Parker 已提交
1835 1836
		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)
1837 1838 1839
		}
	})
}
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871

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

		// continue until a parked goroutine exists
		var parkedg *G
	LookForParkedG:
		for {
			err := p.Continue()
			if _, exited := err.(ProcessExitedError); exited {
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

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

			for _, g := range gs {
				if g.thread == nil {
					parkedg = g
					break LookForParkedG
				}
			}
		}

		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
		assertNoError(p.Step(), t, "Step()")

D
Derek Parker 已提交
1872 1873
		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)
1874 1875 1876
		}
	})
}
1877 1878 1879 1880 1881 1882 1883 1884

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")
E
Evgeny L 已提交
1885
	_, err := Launch([]string{exepath}, ".")
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
	if err != NotExecutableErr {
		t.Fatalf("expected error \"%v\" got \"%v\"", NotExecutableErr, err)
	}
	os.Remove(exepath)
}

func TestUnsupportedArch(t *testing.T) {
	ver, _ := ParseVersionString(runtime.Version())
1897
	if ver.Major < 0 || !ver.AfterOrEqual(GoVersion{1, 6, -1, 0, 0}) || ver.AfterOrEqual(GoVersion{1, 7, -1, 0, 0}) {
1898 1899 1900
		// cross compile (with -N?) works only on select versions of go
		return
	}
1901

1902 1903 1904
	fixturesDir := protest.FindFixturesDir()
	infile := filepath.Join(fixturesDir, "math.go")
	outfile := filepath.Join(fixturesDir, "_math_debug_386")
1905

1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
	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)
1918

E
Evgeny L 已提交
1919
	p, err := Launch([]string{outfile}, ".")
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
	switch err {
	case UnsupportedArchErr:
		// all good
	case nil:
		p.Halt()
		p.Kill()
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
1931

1932
func TestIssue573(t *testing.T) {
1933
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
1934
	// of the function and the internal breakpoint set by StepInto may be missed.
1935 1936
	withTestProcess("issue573", t, func(p *Process, fixture protest.Fixture) {
		f := p.goSymTable.LookupFunc("main.foo")
1937
		_, err := p.SetBreakpoint(f.Entry, UserBreakpoint, nil)
1938 1939 1940 1941 1942 1943 1944
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		assertNoError(p.Step(), t, "Step() #1")
		assertNoError(p.Step(), t, "Step() #2") // Bug exits here.
		assertNoError(p.Step(), t, "Step() #3") // Third step ought to be possible; program ought not have exited.
	})
}
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956

func TestTestvariables2Prologue(t *testing.T) {
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
		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")
		}
	})
}
1957 1958 1959 1960 1961

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 已提交
1962
	testseq("defercall", contNext, []nextTest{
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
		{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 已提交
1978
	testseq("defercall", contNext, []nextTest{
1979 1980 1981 1982 1983
		{15, 16},
		{16, 17},
		{17, 18},
		{18, 5}}, "main.callAndPanic2", t)
}
A
aarzilli 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057

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)
	ver, _ := ParseVersionString(runtime.Version())

	if ver.Major < 0 || ver.AfterOrEqual(GoVersion{1, 7, -1, 0, 0}) {
		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.
	withTestProcess("issue561", t, func(p *Process, fixture protest.Fixture) {
2058
		setFileBreakpoint(p, t, fixture, 10)
A
aarzilli 已提交
2059 2060 2061 2062 2063 2064 2065 2066 2067
		assertNoError(p.Continue(), t, "Continue()")
		assertNoError(p.Step(), t, "Step()")
		_, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number after Step, expected 5 got %d", ln)
		}
	})
}

A
aarzilli 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
func TestStepOut(t *testing.T) {
	withTestProcess("testnextprog", t, func(p *Process, fixture protest.Fixture) {
		bp, err := setFunctionBreakpoint(p, "main.helloworld")
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		p.ClearBreakpoint(bp.Addr)

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

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

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

A
aarzilli 已提交
2089 2090 2091 2092
func TestStepConcurrentDirect(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p *Process, fixture protest.Fixture) {
		pc, err := p.FindFileLocation(fixture.Source, 37)
		assertNoError(err, t, "FindFileLocation()")
2093
		bp, err := p.SetBreakpoint(pc, UserBreakpoint, nil)
A
aarzilli 已提交
2094 2095 2096 2097 2098 2099
		assertNoError(err, t, "SetBreakpoint()")

		assertNoError(p.Continue(), t, "Continue()")
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")

A
aarzilli 已提交
2100 2101 2102 2103 2104 2105 2106 2107
		for _, b := range p.Breakpoints() {
			if b.Name == "unrecovered-panic" {
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

D
Derek Parker 已提交
2108
		gid := p.selectedGoroutine.ID
A
aarzilli 已提交
2109 2110 2111 2112 2113 2114

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

		i := 0
		count := 0
		for {
A
aarzilli 已提交
2115 2116 2117 2118 2119
			anyerr := false
			if p.selectedGoroutine.ID != gid {
				t.Errorf("Step switched to different goroutine %d %d\n", gid, p.selectedGoroutine.ID)
				anyerr = true
			}
A
aarzilli 已提交
2120 2121 2122 2123 2124 2125
			f, ln := currentLineNumber(p, t)
			if ln != seq[i] {
				if i == 1 && ln == 40 {
					// loop exited
					break
				}
A
aarzilli 已提交
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
				frames, err := p.currentThread.Stacktrace(20)
				if err != nil {
					t.Errorf("Could not get stacktrace of goroutine %d\n", p.selectedGoroutine.ID)
				} else {
					t.Logf("Goroutine %d (thread: %d):", p.selectedGoroutine.ID, p.currentThread.ID)
					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 已提交
2137
			}
A
aarzilli 已提交
2138 2139
			if anyerr {
				t.FailNow()
A
aarzilli 已提交
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
			}
			i = (i + 1) % len(seq)
			if i == 0 {
				count++
			}
			assertNoError(p.Step(), t, "Step()")
		}

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

func nextInProgress(p *Process) bool {
D
Derek Parker 已提交
2155
	for _, bp := range p.breakpoints {
2156
		if bp.Internal() {
A
aarzilli 已提交
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
			return true
		}
	}
	return false
}

func TestStepConcurrentPtr(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p *Process, fixture protest.Fixture) {
		pc, err := p.FindFileLocation(fixture.Source, 24)
		assertNoError(err, t, "FindFileLocation()")
2167
		_, err = p.SetBreakpoint(pc, UserBreakpoint, nil)
A
aarzilli 已提交
2168 2169
		assertNoError(err, t, "SetBreakpoint()")

A
aarzilli 已提交
2170 2171 2172 2173 2174 2175 2176 2177
		for _, b := range p.Breakpoints() {
			if b.Name == "unrecovered-panic" {
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
		kvals := map[int]int64{}
		count := 0
		for {
			err := p.Continue()
			_, exited := err.(ProcessExitedError)
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
A
aarzilli 已提交
2190 2191 2192 2193
				for _, th := range p.threads {
					t.Logf("thread %d stopped on breakpoint %v", th.ID, th.CurrentBreakpoint)
				}
				t.Fatalf("Program did not continue at expected location (24): %s:%d %#x [%v] (gid %d count %d)", f, ln, currentPC(p, t), p.currentThread.CurrentBreakpoint, p.selectedGoroutine.ID, count)
A
aarzilli 已提交
2194 2195
			}

D
Derek Parker 已提交
2196
			gid := p.selectedGoroutine.ID
A
aarzilli 已提交
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210

			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

			assertNoError(p.Step(), t, "Step()")
			for nextInProgress(p) {
D
Derek Parker 已提交
2211 2212
				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 已提交
2213 2214 2215 2216
				}
				assertNoError(p.Continue(), t, "Continue()")
			}

D
Derek Parker 已提交
2217 2218
			if p.selectedGoroutine.ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.selectedGoroutine.ID)
A
aarzilli 已提交
2219 2220
			}

2221 2222 2223
			f, ln = currentLineNumber(p, t)
			if ln != 13 {
				t.Fatalf("Step did not step into function call (13): %s:%d", f, ln)
A
aarzilli 已提交
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
			}

			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 已提交
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
func TestStepOutDefer(t *testing.T) {
	withTestProcess("testnextdefer", t, func(p *Process, fixture protest.Fixture) {
		pc, err := p.FindFileLocation(fixture.Source, 9)
		assertNoError(err, t, "FindFileLocation()")
		bp, err := p.SetBreakpoint(pc, UserBreakpoint, nil)
		assertNoError(err, t, "SetBreakpoint()")
		assertNoError(p.Continue(), t, "Continue()")
		p.ClearBreakpoint(bp.Addr)

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

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

		f, l, _ := p.goSymTable.PCToLine(currentPC(p, t))
		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
	withTestProcess("defercall", t, func(p *Process, fixture protest.Fixture) {
		bp := setFileBreakpoint(p, t, fixture, 11)
		assertNoError(p.Continue(), t, "Continue()")
		p.ClearBreakpoint(bp.Addr)

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

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

A
aarzilli 已提交
2281 2282 2283 2284
func TestStepOnCallPtrInstr(t *testing.T) {
	withTestProcess("teststepprog", t, func(p *Process, fixture protest.Fixture) {
		pc, err := p.FindFileLocation(fixture.Source, 10)
		assertNoError(err, t, "FindFileLocation()")
2285
		_, err = p.SetBreakpoint(pc, UserBreakpoint, nil)
A
aarzilli 已提交
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
		assertNoError(err, t, "SetBreakpoint()")

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

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
D
Derek Parker 已提交
2297
			pc, err := p.currentThread.PC()
A
aarzilli 已提交
2298
			assertNoError(err, t, "PC()")
D
Derek Parker 已提交
2299
			text, err := p.currentThread.Disassemble(pc, pc+maxInstructionLength, true)
A
aarzilli 已提交
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
			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")
		}

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

		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("Step continued to wrong line, expected 5 was %s:%d", f, ln)
		}
	})
}
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

func TestIssue594(t *testing.T) {
	// 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.
	withTestProcess("issue594", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue()")
		f, ln := currentLineNumber(p, t)
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351

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
	withTestProcess("defercall", t, func(p *Process, fixture protest.Fixture) {
		bp := setFileBreakpoint(p, t, fixture, 17)
		assertNoError(p.Continue(), t, "Continue()")
		p.ClearBreakpoint(bp.Addr)

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

		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("wrong line number, expected %d got %s:%d", 5, f, ln)
		}
	})
}
E
Evgeny L 已提交
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371

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"
	}
	withTestProcessArgs("workdir", t, wd, func(p *Process, fixture protest.Fixture) {
		addr, _, err := p.goSymTable.LineToPC(fixture.Source, 14)
		assertNoError(err, t, "LineToPC")
		p.SetBreakpoint(addr, UserBreakpoint, nil)
		p.Continue()
		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{})
}
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396

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)},
	}
	withTestProcess("testvariables2", t, func(p *Process, fixture protest.Fixture) {
		assertNoError(p.Continue(), t, "Continue()")
		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)
			}
		}
	})
}
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
	withTestProcess("issue683", t, func(p *Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(p.Continue(), t, "First Continue()")
		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
			err := p.Step()
			if err != nil {
				break
			}
		}
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
	})
}

func TestIssue664(t *testing.T) {
	withTestProcess("issue664", t, func(p *Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 4)
		assertNoError(p.Continue(), t, "Continue()")
		assertNoError(p.Next(), t, "Next()")
		f, ln := currentLineNumber(p, t)
		if ln != 5 {
			t.Fatalf("Did not continue to line 5: %s:%d", f, ln)
2423 2424 2425
		}
	})
}
A
Alessandro Arzilli 已提交
2426 2427 2428 2429 2430 2431 2432 2433 2434

// Benchmarks (*Processs).Continue + (*Scope).FunctionArguments
func BenchmarkTrace(b *testing.B) {
	withTestProcess("traceperf", b, func(p *Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.PerfCheck")
		assertNoError(err, b, "setFunctionBreakpoint()")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			assertNoError(p.Continue(), b, "Continue()")
D
Derek Parker 已提交
2435
			s, err := p.currentThread.Scope()
A
Alessandro Arzilli 已提交
2436 2437 2438 2439 2440 2441 2442
			assertNoError(err, b, "Scope()")
			_, err = s.FunctionArguments(LoadConfig{false, 0, 64, 0, 3})
			assertNoError(err, b, "FunctionArguments()")
		}
		b.StopTimer()
	})
}
A
Alessandro Arzilli 已提交
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473

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.
	withTestProcess("defercall", t, func(p *Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "runtime.deferreturn")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(p.Continue(), t, "First Continue()")
		for i := 0; i < 20; i++ {
			assertNoError(p.Next(), t, fmt.Sprintf("Next() %d", i))
		}
	})
}

func getg(goid int, gs []*G) *G {
	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.
2474 2475 2476 2477 2478 2479 2480 2481 2482

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

	// TODO(aarzilli): in Go 1.9 stack barriers will be removed completely, therefore
	// this test will have to be disabled

A
Alessandro Arzilli 已提交
2483 2484 2485 2486 2487 2488
	withTestProcess("binarytrees", t, func(p *Process, fixture protest.Fixture) {
		// 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 {
2489 2490 2491 2492 2493 2494
			err := p.Continue()
			if _, exited := err.(ProcessExitedError); exited {
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
A
Alessandro Arzilli 已提交
2495 2496
			gs, err := p.GoroutinesInfo()
			assertNoError(err, t, "GoroutinesInfo()")
D
Derek Parker 已提交
2497
			for _, th := range p.threads {
A
Alessandro Arzilli 已提交
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
				if th.CurrentBreakpoint == nil {
					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)

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

		gs, err := p.GoroutinesInfo()
		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)
			}
		}
	})
}