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

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

23 24 25 26 27 28 29
	"github.com/go-delve/delve/pkg/dwarf/frame"
	"github.com/go-delve/delve/pkg/goversion"
	"github.com/go-delve/delve/pkg/logflags"
	"github.com/go-delve/delve/pkg/proc"
	"github.com/go-delve/delve/pkg/proc/gdbserial"
	"github.com/go-delve/delve/pkg/proc/native"
	protest "github.com/go-delve/delve/pkg/proc/test"
D
Derek Parker 已提交
30
)
31

32
var normalLoadConfig = proc.LoadConfig{true, 1, 64, 64, -1, 0}
33
var testBackend, buildMode string
34

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

D
Dan Mace 已提交
40
func TestMain(m *testing.M) {
41
	flag.StringVar(&testBackend, "backend", "", "selects backend")
42 43 44
	flag.StringVar(&buildMode, "test-buildmode", "", "selects build mode")
	var logConf string
	flag.StringVar(&logConf, "log", "", "configures logging")
45
	flag.Parse()
46
	protest.DefaultTestBackend(&testBackend)
47 48 49 50
	if buildMode != "" && buildMode != "pie" {
		fmt.Fprintf(os.Stderr, "unknown build mode %q", buildMode)
		os.Exit(1)
	}
51
	logflags.Setup(logConf != "", logConf, "")
D
Derek Parker 已提交
52
	os.Exit(protest.RunTestsWithFixtures(m))
D
Dan Mace 已提交
53 54
}

55
func withTestProcess(name string, t testing.TB, fn func(p proc.Process, fixture protest.Fixture)) {
56
	withTestProcessArgs(name, t, ".", []string{}, 0, fn)
57 58
}

59
func withTestProcessArgs(name string, t testing.TB, wd string, args []string, buildFlags protest.BuildFlags, fn func(p proc.Process, fixture protest.Fixture)) {
60 61 62
	if buildMode == "pie" {
		buildFlags |= protest.BuildModePIE
	}
63
	fixture := protest.BuildFixture(name, buildFlags)
64
	var p proc.Process
65
	var err error
66
	var tracedir string
67 68 69

	switch testBackend {
	case "native":
70
		p, err = native.Launch(append([]string{fixture.Path}, args...), wd, false, []string{})
71
	case "lldb":
72
		p, err = gdbserial.LLDBLaunch(append([]string{fixture.Path}, args...), wd, false, []string{})
73 74 75
	case "rr":
		protest.MustHaveRecordingAllowed(t)
		t.Log("recording")
76
		p, tracedir, err = gdbserial.RecordAndReplay(append([]string{fixture.Path}, args...), wd, true, []string{})
77
		t.Logf("replaying %q", tracedir)
78 79 80
	default:
		t.Fatal("unknown backend")
	}
81 82 83 84 85
	if err != nil {
		t.Fatal("Launch():", err)
	}

	defer func() {
86
		p.Detach(true)
87 88 89
		if tracedir != "" {
			protest.SafeRemoveAll(tracedir)
		}
90 91 92 93 94
	}()

	fn(p, fixture)
}

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

	return regs
}

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

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

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

124
	return regs.PC()
125 126
}

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

133 134 135 136 137 138 139 140 141
func assertLineNumber(p proc.Process, t *testing.T, lineno int, descr string) (string, int) {
	f, l := currentLineNumber(p, t)
	if l != lineno {
		_, callerFile, callerLine, _ := runtime.Caller(1)
		t.Fatalf("%s expected line :%d got %s:%d\n\tat %s:%d", descr, lineno, f, l, callerFile, callerLine)
	}
	return f, l
}

142
func TestExit(t *testing.T) {
143
	protest.AllowRecording(t)
144
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
145
		err := proc.Continue(p)
146
		pe, ok := err.(proc.ErrProcessExited)
147
		if !ok {
148
			t.Fatalf("Continue() returned unexpected error type %s", err)
149 150 151 152
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
153
		if pe.Pid != p.Pid() {
154 155 156 157 158
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

159
func TestExitAfterContinue(t *testing.T) {
160
	protest.AllowRecording(t)
161
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
162 163
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "setFunctionBreakpoint()")
164 165
		assertNoError(proc.Continue(p), t, "First Continue()")
		err = proc.Continue(p)
166
		pe, ok := err.(proc.ErrProcessExited)
167
		if !ok {
L
Luke Hoban 已提交
168
			t.Fatalf("Continue() returned unexpected error type %s", pe)
169 170 171 172
		}
		if pe.Status != 0 {
			t.Errorf("Unexpected error status: %d", pe.Status)
		}
173
		if pe.Pid != p.Pid() {
174 175 176 177 178
			t.Errorf("Unexpected process id: %d", pe.Pid)
		}
	})
}

179
func setFunctionBreakpoint(p proc.Process, fname string) (*proc.Breakpoint, error) {
180
	addr, err := proc.FindFunctionLocation(p, fname, 0)
181 182 183
	if err != nil {
		return nil, err
	}
184
	return p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
185 186
}

187
func setFileBreakpoint(p proc.Process, t *testing.T, fixture protest.Fixture, lineno int) *proc.Breakpoint {
188 189 190 191 192
	return setFileLineBreakpoint(p, t, fixture.Source, lineno)
}

func setFileLineBreakpoint(p proc.Process, t *testing.T, path string, lineno int) *proc.Breakpoint {
	addr, err := proc.FindFileLocation(p, path, lineno)
A
aarzilli 已提交
193 194 195
	if err != nil {
		t.Fatalf("FindFileLocation: %v", err)
	}
196
	bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
A
aarzilli 已提交
197 198 199 200 201 202
	if err != nil {
		t.Fatalf("SetBreakpoint: %v", err)
	}
	return bp
}

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

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

D
Derek Parker 已提交
229 230 231
		// Loop through threads and make sure they are all
		// actually stopped, err will not be nil if the process
		// is still running.
232 233 234 235 236 237
		if p, ok := p.(*native.Process); ok {
			for _, th := range p.ThreadList() {
				if th, ok := th.(*native.Thread); ok {
					if !th.Stopped() {
						t.Fatal("expected thread to be stopped, but was not")
					}
238 239 240
				}
				_, err := th.Registers(false)
				assertNoError(err, t, "Registers")
D
Derek Parker 已提交
241 242 243 244 245
			}
		}
	})
}

246
func TestStep(t *testing.T) {
247
	protest.AllowRecording(t)
248
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
249
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", 0)
250
		assertNoError(err, t, "FindFunctionLocation")
251

252
		_, err = p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
253
		assertNoError(err, t, "SetBreakpoint()")
254
		assertNoError(proc.Continue(p), t, "Continue()")
255

256
		regs := getRegisters(p, t)
257
		rip := regs.PC()
258

259
		err = p.CurrentThread().StepInstruction()
D
Derek Parker 已提交
260
		assertNoError(err, t, "Step()")
261

262
		regs = getRegisters(p, t)
263 264 265 266 267
		if rip >= regs.PC() {
			t.Errorf("Expected %#v to be greater than %#v", regs.PC(), rip)
		}
	})
}
268

D
Derek Parker 已提交
269
func TestBreakpoint(t *testing.T) {
270
	protest.AllowRecording(t)
271
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
272
		helloworldaddr, err := proc.FindFunctionLocation(p, "main.helloworld", 0)
273
		assertNoError(err, t, "FindFunctionLocation")
274

275
		bp, err := p.SetBreakpoint(helloworldaddr, proc.UserBreakpoint, nil)
276
		assertNoError(err, t, "SetBreakpoint()")
277
		assertNoError(proc.Continue(p), t, "Continue()")
278

279 280 281
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
282

283 284 285 286
		if bp.TotalHitCount != 1 {
			t.Fatalf("Breakpoint should be hit once, got %d\n", bp.TotalHitCount)
		}

D
Derek Parker 已提交
287
		if pc-1 != bp.Addr && pc != bp.Addr {
288
			f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
289
			t.Fatalf("Break not respected:\nPC:%#v %s:%d\nFN:%#v \n", pc, f, l, bp.Addr)
290 291
		}
	})
292
}
293

J
Josh Soref 已提交
294
func TestBreakpointInSeparateGoRoutine(t *testing.T) {
295
	protest.AllowRecording(t)
296
	withTestProcess("testthreads", t, func(p proc.Process, fixture protest.Fixture) {
297
		fnentry, err := proc.FindFunctionLocation(p, "main.anotherthread", 0)
298
		assertNoError(err, t, "FindFunctionLocation")
299

300
		_, err = p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
301
		assertNoError(err, t, "SetBreakpoint")
302

303
		assertNoError(proc.Continue(p), t, "Continue")
304

305 306 307
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
308

309
		f, l, _ := p.BinInfo().PCToLine(pc)
310 311 312 313 314 315
		if f != "testthreads.go" && l != 8 {
			t.Fatal("Program did not hit breakpoint")
		}
	})
}

D
Derek Parker 已提交
316
func TestBreakpointWithNonExistantFunction(t *testing.T) {
317
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
318
		_, err := p.SetBreakpoint(0, proc.UserBreakpoint, nil)
319 320 321 322
		if err == nil {
			t.Fatal("Should not be able to break at non existant function")
		}
	})
323
}
324

325
func TestClearBreakpointBreakpoint(t *testing.T) {
326
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
327
		fnentry, err := proc.FindFunctionLocation(p, "main.sleepytime", 0)
328
		assertNoError(err, t, "FindFunctionLocation")
329
		bp, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil)
330
		assertNoError(err, t, "SetBreakpoint()")
331

332
		bp, err = p.ClearBreakpoint(fnentry)
333
		assertNoError(err, t, "ClearBreakpoint()")
334

335 336
		data, err := dataAtAddr(p.CurrentThread(), bp.Addr)
		assertNoError(err, t, "dataAtAddr")
337

338
		int3 := []byte{0xcc}
339 340 341 342
		if bytes.Equal(data, int3) {
			t.Fatalf("Breakpoint was not cleared data: %#v, int3: %#v", data, int3)
		}

343
		if countBreakpoints(p) != 0 {
344 345 346
			t.Fatal("Breakpoint not removed internally")
		}
	})
347
}
348

349 350 351
type nextTest struct {
	begin, end int
}
352

353
func countBreakpoints(p proc.Process) int {
354
	bpcount := 0
A
aarzilli 已提交
355
	for _, bp := range p.Breakpoints().M {
356 357 358 359 360 361 362
		if bp.ID >= 0 {
			bpcount++
		}
	}
	return bpcount
}

A
aarzilli 已提交
363 364 365
type contFunc int

const (
366 367
	contContinue contFunc = iota
	contNext
A
aarzilli 已提交
368
	contStep
369
	contStepout
A
aarzilli 已提交
370 371
)

372 373
type seqTest struct {
	cf  contFunc
374
	pos interface{}
375 376
}

A
aarzilli 已提交
377
func testseq(program string, contFunc contFunc, testcases []nextTest, initialLocation string, t *testing.T) {
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	seqTestcases := make([]seqTest, len(testcases)+1)
	seqTestcases[0] = seqTest{contContinue, testcases[0].begin}
	for i := range testcases {
		if i > 0 {
			if testcases[i-1].end != testcases[i].begin {
				panic(fmt.Errorf("begin/end mismatch at index %d", i))
			}
		}
		seqTestcases[i+1] = seqTest{contFunc, testcases[i].end}
	}
	testseq2(t, program, initialLocation, seqTestcases)
}

const traceTestseq2 = false

func testseq2(t *testing.T, program string, initialLocation string, testcases []seqTest) {
	testseq2Args(".", []string{}, 0, t, program, initialLocation, testcases)
}

func testseq2Args(wd string, args []string, buildFlags protest.BuildFlags, t *testing.T, program string, initialLocation string, testcases []seqTest) {
398
	protest.AllowRecording(t)
399
	withTestProcessArgs(program, t, wd, args, buildFlags, func(p proc.Process, fixture protest.Fixture) {
400
		var bp *proc.Breakpoint
A
aarzilli 已提交
401 402 403
		var err error
		if initialLocation != "" {
			bp, err = setFunctionBreakpoint(p, initialLocation)
404
		} else if testcases[0].cf == contContinue {
A
aarzilli 已提交
405
			var pc uint64
406
			pc, err = proc.FindFileLocation(p, fixture.Source, testcases[0].pos.(int))
A
aarzilli 已提交
407
			assertNoError(err, t, "FindFileLocation()")
408
			bp, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
409 410 411 412 413
		} else {
			panic("testseq2 can not set initial breakpoint")
		}
		if traceTestseq2 {
			t.Logf("initial breakpoint %v", bp)
A
aarzilli 已提交
414
		}
415
		assertNoError(err, t, "SetBreakpoint()")
416 417
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
418

D
Derek Parker 已提交
419
		f, ln := currentLineNumber(p, t)
420 421
		for i, tc := range testcases {
			switch tc.cf {
A
aarzilli 已提交
422
			case contNext:
423 424 425
				if traceTestseq2 {
					t.Log("next")
				}
426
				assertNoError(proc.Next(p), t, "Next() returned an error")
A
aarzilli 已提交
427
			case contStep:
428 429 430
				if traceTestseq2 {
					t.Log("step")
				}
431
				assertNoError(proc.Step(p), t, "Step() returned an error")
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
			case contStepout:
				if traceTestseq2 {
					t.Log("stepout")
				}
				assertNoError(proc.StepOut(p), t, "StepOut() returned an error")
			case contContinue:
				if traceTestseq2 {
					t.Log("continue")
				}
				assertNoError(proc.Continue(p), t, "Continue() returned an error")
				if i == 0 {
					if traceTestseq2 {
						t.Log("clearing initial breakpoint")
					}
					_, err := p.ClearBreakpoint(bp.Addr)
					assertNoError(err, t, "ClearBreakpoint() returned an error")
				}
A
aarzilli 已提交
449
			}
450

D
Derek Parker 已提交
451
			f, ln = currentLineNumber(p, t)
452
			regs, _ = p.CurrentThread().Registers(false)
453 454 455 456
			pc := regs.PC()

			if traceTestseq2 {
				t.Logf("at %#x %s:%d", pc, f, ln)
457
				fmt.Printf("at %#x %s:%d", pc, f, ln)
458
			}
459 460 461 462 463 464 465 466 467 468 469
			switch pos := tc.pos.(type) {
			case int:
				if ln != pos {
					t.Fatalf("Program did not continue to correct next location expected %d was %s:%d (%#x) (testcase %d)", pos, filepath.Base(f), ln, pc, i)
				}
			case string:
				v := strings.Split(pos, ":")
				tgtln, _ := strconv.Atoi(v[1])
				if !strings.HasSuffix(f, v[0]) || (ln != tgtln) {
					t.Fatalf("Program did not continue to correct next location, expected %s was %s:%d (%#x) (testcase %d)", pos, filepath.Base(f), ln, pc, i)
				}
470 471
			}
		}
472

473
		if countBreakpoints(p) != 0 {
A
aarzilli 已提交
474
			t.Fatal("Not all breakpoints were cleaned up", len(p.Breakpoints().M))
475
		}
476 477
	})
}
478

479
func TestNextGeneral(t *testing.T) {
480 481
	var testcases []nextTest

482
	ver, _ := goversion.Parse(runtime.Version())
483

484
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
		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},
		}
521
	}
522

A
aarzilli 已提交
523
	testseq("testnextprog", contNext, testcases, "main.testnext", t)
524 525
}

526
func TestNextConcurrent(t *testing.T) {
527 528 529
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
530
	testcases := []nextTest{
531
		{8, 9},
532 533 534
		{9, 10},
		{10, 11},
	}
535
	protest.AllowRecording(t)
536
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
537
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
538
		assertNoError(err, t, "SetBreakpoint")
539
		assertNoError(proc.Continue(p), t, "Continue")
540
		f, ln := currentLineNumber(p, t)
541
		initV := evalVariable(p, t, "n")
542
		initVval, _ := constant.Int64Val(initV.Value)
543 544
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")
545
		for _, tc := range testcases {
546
			g, err := proc.GetG(p.CurrentThread())
547
			assertNoError(err, t, "GetG()")
548 549
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
550
			}
551 552 553
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
554
			assertNoError(proc.Next(p), t, "Next() returned an error")
555 556
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to the expected location")
			v := evalVariable(p, t, "n")
557 558
			vval, _ := constant.Int64Val(v.Value)
			if vval != initVval {
559 560 561 562 563 564
				t.Fatal("Did not end up on same goroutine")
			}
		}
	})
}

565
func TestNextConcurrentVariant2(t *testing.T) {
566 567 568
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
569 570
	// Just like TestNextConcurrent but instead of removing the initial breakpoint we check that when it happens is for other goroutines
	testcases := []nextTest{
571
		{8, 9},
572 573 574
		{9, 10},
		{10, 11},
	}
575
	protest.AllowRecording(t)
576
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
577 578
		_, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint")
579
		assertNoError(proc.Continue(p), t, "Continue")
580
		f, ln := currentLineNumber(p, t)
581
		initV := evalVariable(p, t, "n")
582 583
		initVval, _ := constant.Int64Val(initV.Value)
		for _, tc := range testcases {
584
			t.Logf("test case %v", tc)
585
			g, err := proc.GetG(p.CurrentThread())
586
			assertNoError(err, t, "GetG()")
587 588
			if p.SelectedGoroutine().ID != g.ID {
				t.Fatalf("SelectedGoroutine not CurrentThread's goroutine: %d %d", g.ID, p.SelectedGoroutine().ID)
589 590 591 592
			}
			if ln != tc.begin {
				t.Fatalf("Program not stopped at correct spot expected %d was %s:%d", tc.begin, filepath.Base(f), ln)
			}
593
			assertNoError(proc.Next(p), t, "Next() returned an error")
594 595
			var vval int64
			for {
596
				v := evalVariable(p, t, "n")
597 598 599
				for _, thread := range p.ThreadList() {
					proc.GetG(thread)
				}
600
				vval, _ = constant.Int64Val(v.Value)
601
				if bpstate := p.CurrentThread().Breakpoint(); bpstate.Breakpoint == nil {
602 603 604 605 606 607 608 609
					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")
					}
610
					assertNoError(proc.Continue(p), t, "Continue 2")
611 612
				}
			}
613
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to the expected location")
614 615 616 617
		}
	})
}

618 619
func TestNextFunctionReturn(t *testing.T) {
	testcases := []nextTest{
620
		{13, 14},
D
Derek Parker 已提交
621 622
		{14, 15},
		{15, 35},
623
	}
624
	protest.AllowRecording(t)
A
aarzilli 已提交
625
	testseq("testnextprog", contNext, testcases, "main.helloworld", t)
626 627 628
}

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

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

633
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
A
aarzilli 已提交
634 635 636 637 638 639 640 641 642 643 644
		testcases = []nextTest{
			{5, 6},
			{6, 9},
			{9, 10},
		}
	} else {
		testcases = []nextTest{
			{5, 8},
			{8, 9},
			{9, 10},
		}
645
	}
646
	protest.AllowRecording(t)
A
aarzilli 已提交
647
	testseq("testnextdefer", contNext, testcases, "main.main", t)
648 649
}

D
Derek Parker 已提交
650 651 652 653 654
func TestNextNetHTTP(t *testing.T) {
	testcases := []nextTest{
		{11, 12},
		{12, 13},
	}
655
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
656 657 658
		go func() {
			// Wait for program to start listening.
			for {
L
Luke Hoban 已提交
659
				conn, err := net.Dial("tcp", "localhost:9191")
D
Derek Parker 已提交
660 661 662 663 664 665
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}
D
Derek Parker 已提交
666
			http.Get("http://localhost:9191")
D
Derek Parker 已提交
667
		}()
668
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
669 670 671 672 673 674 675 676
			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)
			}

677
			assertNoError(proc.Next(p), t, "Next() returned an error")
D
Derek Parker 已提交
678

679
			f, ln = assertLineNumber(p, t, tc.end, "Program did not continue to correct next location")
D
Derek Parker 已提交
680 681 682 683
		}
	})
}

D
Derek Parker 已提交
684
func TestRuntimeBreakpoint(t *testing.T) {
685
	withTestProcess("testruntimebreakpoint", t, func(p proc.Process, fixture protest.Fixture) {
686
		err := proc.Continue(p)
D
Derek Parker 已提交
687 688 689
		if err != nil {
			t.Fatal(err)
		}
690 691 692
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers")
		pc := regs.PC()
693
		f, l, _ := p.BinInfo().PCToLine(pc)
D
Derek Parker 已提交
694
		if l != 10 {
695
			t.Fatalf("did not respect breakpoint %s:%d", f, l)
D
Derek Parker 已提交
696 697 698 699
		}
	})
}

700
func returnAddress(thread proc.Thread) (uint64, error) {
701
	locations, err := proc.ThreadStacktrace(thread, 2)
702 703 704 705
	if err != nil {
		return 0, err
	}
	if len(locations) < 2 {
A
aarzilli 已提交
706
		return 0, fmt.Errorf("no return address for function: %s", locations[0].Current.Fn.BaseName())
707 708 709 710
	}
	return locations[1].Current.PC, nil
}

711
func TestFindReturnAddress(t *testing.T) {
712
	protest.AllowRecording(t)
713
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
714
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 24)
715 716 717
		if err != nil {
			t.Fatal(err)
		}
718
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
719 720 721
		if err != nil {
			t.Fatal(err)
		}
722
		err = proc.Continue(p)
723 724 725
		if err != nil {
			t.Fatal(err)
		}
726
		addr, err := returnAddress(p.CurrentThread())
727 728 729
		if err != nil {
			t.Fatal(err)
		}
730
		_, l, _ := p.BinInfo().PCToLine(addr)
731 732
		if l != 40 {
			t.Fatalf("return address not found correctly, expected line 40")
733
		}
734 735
	})
}
736

737
func TestFindReturnAddressTopOfStackFn(t *testing.T) {
738
	protest.AllowRecording(t)
739
	withTestProcess("testreturnaddress", t, func(p proc.Process, fixture protest.Fixture) {
740
		fnName := "runtime.rt0_go"
741
		fnentry, err := proc.FindFunctionLocation(p, fnName, 0)
742
		assertNoError(err, t, "FindFunctionLocation")
743
		if _, err := p.SetBreakpoint(fnentry, proc.UserBreakpoint, nil); err != nil {
744 745
			t.Fatal(err)
		}
746
		if err := proc.Continue(p); err != nil {
D
Derek Parker 已提交
747 748
			t.Fatal(err)
		}
749
		if _, err := returnAddress(p.CurrentThread()); err == nil {
750
			t.Fatal("expected error to be returned")
751 752 753
		}
	})
}
D
Derek Parker 已提交
754 755

func TestSwitchThread(t *testing.T) {
756
	protest.AllowRecording(t)
757
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
D
Derek Parker 已提交
758 759 760 761 762
		// With invalid thread id
		err := p.SwitchThread(-1)
		if err == nil {
			t.Fatal("Expected error for invalid thread id")
		}
763
		pc, err := proc.FindFunctionLocation(p, "main.main", 0)
D
Derek Parker 已提交
764 765 766
		if err != nil {
			t.Fatal(err)
		}
767
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
D
Derek Parker 已提交
768 769 770
		if err != nil {
			t.Fatal(err)
		}
771
		err = proc.Continue(p)
D
Derek Parker 已提交
772 773 774 775
		if err != nil {
			t.Fatal(err)
		}
		var nt int
776 777 778 779
		ct := p.CurrentThread().ThreadID()
		for _, thread := range p.ThreadList() {
			if thread.ThreadID() != ct {
				nt = thread.ThreadID()
D
Derek Parker 已提交
780 781 782 783 784 785 786 787 788 789 790
				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)
		}
791
		if p.CurrentThread().ThreadID() != nt {
D
Derek Parker 已提交
792 793 794 795
			t.Fatal("Did not switch threads")
		}
	})
}
A
aarzilli 已提交
796

797 798 799 800 801 802
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 已提交
803 804 805
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
806

807
	protest.AllowRecording(t)
808
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
809
		pc, err := proc.FindFunctionLocation(p, "main.main", 0)
810 811 812
		if err != nil {
			t.Fatal(err)
		}
813
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
814 815 816
		if err != nil {
			t.Fatal(err)
		}
817
		err = proc.Continue(p)
818 819 820
		if err != nil {
			t.Fatal(err)
		}
821
		err = proc.Next(p)
822 823 824 825 826 827
		if err != nil {
			t.Fatal(err)
		}
	})
}

A
aarzilli 已提交
828 829 830 831 832
type loc struct {
	line int
	fn   string
}

833
func (l1 *loc) match(l2 proc.Stackframe) bool {
A
aarzilli 已提交
834
	if l1.line >= 0 {
835
		if l1.line != l2.Call.Line {
A
aarzilli 已提交
836 837 838
			return false
		}
	}
839
	return l1.fn == l2.Call.Fn.Name
A
aarzilli 已提交
840 841 842 843
}

func TestStacktrace(t *testing.T) {
	stacks := [][]loc{
D
Derek Parker 已提交
844 845
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {16, "main.main"}},
		{{4, "main.stacktraceme"}, {8, "main.func1"}, {12, "main.func2"}, {17, "main.main"}},
A
aarzilli 已提交
846
	}
847
	protest.AllowRecording(t)
848
	withTestProcess("stacktraceprog", t, func(p proc.Process, fixture protest.Fixture) {
849
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
850 851 852
		assertNoError(err, t, "BreakByLocation()")

		for i := range stacks {
853 854
			assertNoError(proc.Continue(p), t, "Continue()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
A
aarzilli 已提交
855 856 857 858 859 860
			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)
			}

861 862 863 864
			t.Logf("Stacktrace %d:\n", i)
			for i := range locations {
				t.Logf("\t%s:%d\n", locations[i].Call.File, locations[i].Call.Line)
			}
865

A
aarzilli 已提交
866 867 868 869 870 871 872
			for j := range stacks[i] {
				if !stacks[i][j].match(locations[j]) {
					t.Fatalf("Wrong stack trace pos %d\n", j)
				}
			}
		}

873
		p.ClearBreakpoint(bp.Addr)
874
		proc.Continue(p)
A
aarzilli 已提交
875 876 877
	})
}

878
func TestStacktrace2(t *testing.T) {
879
	withTestProcess("retstack", t, func(p proc.Process, fixture protest.Fixture) {
880
		assertNoError(proc.Continue(p), t, "Continue()")
881

882
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
883
		assertNoError(err, t, "Stacktrace()")
884
		if !stackMatch([]loc{{-1, "main.f"}, {16, "main.main"}}, locations, false) {
885 886 887
			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 已提交
888
			t.Fatalf("Stack error at main.f()\n%v\n", locations)
889 890
		}

891 892
		assertNoError(proc.Continue(p), t, "Continue()")
		locations, err = proc.ThreadStacktrace(p.CurrentThread(), 40)
893
		assertNoError(err, t, "Stacktrace()")
894
		if !stackMatch([]loc{{-1, "main.g"}, {17, "main.main"}}, locations, false) {
895 896 897
			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 已提交
898
			t.Fatalf("Stack error at main.g()\n%v\n", locations)
899 900 901 902 903
		}
	})

}

904
func stackMatch(stack []loc, locations []proc.Stackframe, skipRuntime bool) bool {
A
aarzilli 已提交
905 906 907
	if len(stack) > len(locations) {
		return false
	}
908 909 910 911 912 913 914 915 916 917 918
	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 已提交
919 920
			return false
		}
921
		i++
A
aarzilli 已提交
922
	}
923
	return i >= len(stack)
A
aarzilli 已提交
924 925 926
}

func TestStacktraceGoroutine(t *testing.T) {
927
	mainStack := []loc{{14, "main.stacktraceme"}, {29, "main.main"}}
928 929 930
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		mainStack[0].line = 15
	}
931 932 933 934 935
	agoroutineStacks := [][]loc{
		{{8, "main.agoroutine"}},
		{{9, "main.agoroutine"}},
		{{10, "main.agoroutine"}},
	}
A
aarzilli 已提交
936

937
	protest.AllowRecording(t)
938
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
939
		bp, err := setFunctionBreakpoint(p, "main.stacktraceme")
A
aarzilli 已提交
940 941
		assertNoError(err, t, "BreakByLocation()")

942
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
943

944
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
aarzilli 已提交
945 946 947 948 949
		assertNoError(err, t, "GoroutinesInfo")

		agoroutineCount := 0
		mainCount := 0

D
Derek Parker 已提交
950
		for i, g := range gs {
951
			locations, err := g.Stacktrace(40, false)
952 953
			if err != nil {
				// On windows we do not have frame information for goroutines doing system calls.
A
aarzilli 已提交
954
				t.Logf("Could not retrieve goroutine stack for goid=%d: %v", g.ID, err)
955 956
				continue
			}
A
aarzilli 已提交
957

958
			if stackMatch(mainStack, locations, false) {
A
aarzilli 已提交
959 960 961
				mainCount++
			}

962 963 964 965 966 967 968 969
			found := false
			for _, agoroutineStack := range agoroutineStacks {
				if stackMatch(agoroutineStack, locations, true) {
					found = true
				}
			}

			if found {
A
aarzilli 已提交
970 971
				agoroutineCount++
			} else {
D
Derek Parker 已提交
972
				t.Logf("Non-goroutine stack: %d (%d)", i, len(locations))
A
aarzilli 已提交
973 974
				for i := range locations {
					name := ""
975 976
					if locations[i].Call.Fn != nil {
						name = locations[i].Call.Fn.Name
A
aarzilli 已提交
977
					}
978
					t.Logf("\t%s:%d %s (%#x)\n", locations[i].Call.File, locations[i].Call.Line, name, locations[i].Current.PC)
A
aarzilli 已提交
979 980 981 982 983
				}
			}
		}

		if mainCount != 1 {
984
			t.Fatalf("Main goroutine stack not found %d", mainCount)
A
aarzilli 已提交
985 986 987 988 989 990
		}

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

991
		p.ClearBreakpoint(bp.Addr)
992
		proc.Continue(p)
A
aarzilli 已提交
993 994
	})
}
995 996

func TestKill(t *testing.T) {
997 998 999 1000
	if testBackend == "lldb" {
		// k command presumably works but leaves the process around?
		return
	}
1001 1002 1003 1004
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
		if err := p.Detach(true); err != nil {
			t.Fatal(err)
		}
1005
		if valid, _ := p.Valid(); valid {
1006 1007 1008 1009 1010 1011 1012 1013 1014
			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())
			}
		}
	})
1015
}
1016

1017
func testGSupportFunc(name string, t *testing.T, p proc.Process, fixture protest.Fixture) {
1018
	bp, err := setFunctionBreakpoint(p, "main.main")
1019 1020
	assertNoError(err, t, name+": BreakByLocation()")

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

1023
	g, err := proc.GetG(p.CurrentThread())
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	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) {
1036
	withTestProcess("testprog", t, func(p proc.Process, fixture protest.Fixture) {
1037 1038 1039
		testGSupportFunc("nocgo", t, p, fixture)
	})

1040 1041 1042 1043
	// 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 已提交
1044 1045 1046
	if os.Getenv("CGO_ENABLED") == "" {
		return
	}
1047

1048
	protest.AllowRecording(t)
1049
	withTestProcess("cgotest", t, func(p proc.Process, fixture protest.Fixture) {
1050 1051 1052
		testGSupportFunc("cgo", t, p, fixture)
	})
}
1053 1054

func TestContinueMulti(t *testing.T) {
1055
	protest.AllowRecording(t)
1056
	withTestProcess("integrationprog", t, func(p proc.Process, fixture protest.Fixture) {
1057
		bp1, err := setFunctionBreakpoint(p, "main.main")
1058 1059
		assertNoError(err, t, "BreakByLocation()")

1060
		bp2, err := setFunctionBreakpoint(p, "main.sayhi")
1061 1062 1063 1064 1065
		assertNoError(err, t, "BreakByLocation()")

		mainCount := 0
		sayhiCount := 0
		for {
1066
			err := proc.Continue(p)
1067
			if valid, _ := p.Valid(); !valid {
1068 1069 1070 1071
				break
			}
			assertNoError(err, t, "Continue()")

1072
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp1.ID {
1073 1074 1075
				mainCount++
			}

1076
			if bp := p.CurrentThread().Breakpoint(); bp.ID == bp2.ID {
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
				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)
		}
	})
}
1090

1091
func TestBreakpointOnFunctionEntry(t *testing.T) {
1092
	testseq2(t, "testprog", "main.main", []seqTest{{contContinue, 17}})
1093
}
1094 1095

func TestProcessReceivesSIGCHLD(t *testing.T) {
1096
	protest.AllowRecording(t)
1097
	withTestProcess("sigchldprog", t, func(p proc.Process, fixture protest.Fixture) {
1098
		err := proc.Continue(p)
1099
		_, ok := err.(proc.ErrProcessExited)
1100
		if !ok {
1101
			t.Fatalf("Continue() returned unexpected error type %v", err)
1102 1103 1104
		}
	})
}
1105 1106

func TestIssue239(t *testing.T) {
1107
	withTestProcess("is sue239", t, func(p proc.Process, fixture protest.Fixture) {
1108
		pos, _, err := p.BinInfo().LineToPC(fixture.Source, 17)
1109
		assertNoError(err, t, "LineToPC()")
1110
		_, err = p.SetBreakpoint(pos, proc.UserBreakpoint, nil)
1111
		assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%d)", pos))
1112
		assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue()"))
1113 1114
	})
}
1115

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
func findFirstNonRuntimeFrame(p proc.Process) (proc.Stackframe, error) {
	frames, err := proc.ThreadStacktrace(p.CurrentThread(), 10)
	if err != nil {
		return proc.Stackframe{}, err
	}

	for _, frame := range frames {
		if frame.Current.Fn != nil && !strings.HasPrefix(frame.Current.Fn.Name, "runtime.") {
			return frame, nil
		}
	}
	return proc.Stackframe{}, fmt.Errorf("non-runtime frame not found")
}

1130
func evalVariableOrError(p proc.Process, symbol string) (*proc.Variable, error) {
1131 1132 1133 1134 1135 1136 1137
	var scope *proc.EvalScope
	var err error

	if testBackend == "rr" {
		var frame proc.Stackframe
		frame, err = findFirstNonRuntimeFrame(p)
		if err == nil {
1138
			scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)
1139 1140 1141 1142
		}
	} else {
		scope, err = proc.GoroutineScope(p.CurrentThread())
	}
1143

1144 1145 1146
	if err != nil {
		return nil, err
	}
1147
	return scope.EvalVariable(symbol, normalLoadConfig)
1148 1149
}

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
func evalVariable(p proc.Process, t testing.TB, symbol string) *proc.Variable {
	v, err := evalVariableOrError(p, symbol)
	if err != nil {
		_, file, line, _ := runtime.Caller(1)
		fname := filepath.Base(file)
		t.Fatalf("%s:%d: EvalVariable(%q): %v", fname, line, symbol, err)
	}
	return v
}

1160
func setVariable(p proc.Process, symbol, value string) error {
1161
	scope, err := proc.GoroutineScope(p.CurrentThread())
1162 1163 1164 1165 1166 1167 1168
	if err != nil {
		return err
	}
	return scope.SetVariable(symbol, value)
}

func TestVariableEvaluation(t *testing.T) {
1169
	protest.AllowRecording(t)
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
	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 已提交
1192 1193
		{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
		{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
		{"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},
	}

1205
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1206
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1207 1208

		for _, tc := range testcases {
1209
			v := evalVariable(p, t, tc.name)
1210 1211 1212 1213 1214 1215 1216

			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 {
1217 1218 1219
				switch v.Kind {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					x, _ := constant.Int64Val(v.Value)
1220 1221 1222
					if y, ok := tc.value.(int64); !ok || x != y {
						t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
					}
1223 1224
				case reflect.Float32, reflect.Float64:
					x, _ := constant.Float64Val(v.Value)
1225 1226 1227
					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 已提交
1228 1229 1230 1231 1232 1233
				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)
					}
1234 1235
				case reflect.String:
					if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
						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) {
1254
	protest.AllowRecording(t)
1255
	withTestProcess("goroutinestackprog", t, func(p proc.Process, fixture protest.Fixture) {
1256 1257
		_, err := setFunctionBreakpoint(p, "main.stacktraceme")
		assertNoError(err, t, "setFunctionBreakpoint")
1258
		assertNoError(proc.Continue(p), t, "Continue()")
1259

1260 1261
		t.Logf("stopped on thread %d, goroutine: %#v", p.CurrentThread().ThreadID(), p.SelectedGoroutine())

1262
		// Testing evaluation on goroutines
1263
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1264 1265 1266 1267
		assertNoError(err, t, "GoroutinesInfo")
		found := make([]bool, 10)
		for _, g := range gs {
			frame := -1
1268
			frames, err := g.Stacktrace(10, false)
1269 1270 1271 1272
			if err != nil {
				t.Logf("could not stacktrace goroutine %d: %v\n", g.ID, err)
				continue
			}
1273
			t.Logf("Goroutine %d", g.ID)
1274
			logStacktrace(t, p.BinInfo(), frames)
1275 1276 1277 1278 1279 1280 1281 1282
			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 已提交
1283
				t.Logf("Goroutine %d: could not find correct frame", g.ID)
1284 1285 1286
				continue
			}

1287
			scope, err := proc.ConvertEvalScope(p, g.ID, frame, 0)
1288 1289
			assertNoError(err, t, "ConvertEvalScope()")
			t.Logf("scope = %v", scope)
1290
			v, err := scope.EvalVariable("i", normalLoadConfig)
1291 1292
			t.Logf("v = %v", v)
			if err != nil {
D
Derek Parker 已提交
1293
				t.Logf("Goroutine %d: %v\n", g.ID, err)
1294 1295
				continue
			}
1296 1297
			vval, _ := constant.Int64Val(v.Value)
			found[vval] = true
1298 1299 1300 1301 1302 1303 1304 1305
		}

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

1306
		// Testing evaluation on frames
1307 1308
		assertNoError(proc.Continue(p), t, "Continue() 2")
		g, err := proc.GetG(p.CurrentThread())
1309 1310 1311
		assertNoError(err, t, "GetG()")

		for i := 0; i <= 3; i++ {
1312
			scope, err := proc.ConvertEvalScope(p, g.ID, i+1, 0)
1313
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope() on frame %d", i+1))
1314
			v, err := scope.EvalVariable("n", normalLoadConfig)
1315
			assertNoError(err, t, fmt.Sprintf("EvalVariable() on frame %d", i+1))
1316
			n, _ := constant.Int64Val(v.Value)
1317 1318 1319 1320 1321 1322 1323 1324 1325
			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) {
1326
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1327
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1328 1329

		pval := func(n int64) {
1330
			variable := evalVariable(p, t, "p1")
1331 1332 1333
			c0val, _ := constant.Int64Val(variable.Children[0].Value)
			if c0val != n {
				t.Fatalf("Wrong value of p1, *%d expected *%d", c0val, n)
1334 1335 1336 1337 1338 1339
			}
		}

		pval(1)

		// change p1 to point to i2
1340
		scope, err := proc.GoroutineScope(p.CurrentThread())
1341
		assertNoError(err, t, "Scope()")
1342
		i2addr, err := scope.EvalExpression("i2", normalLoadConfig)
A
aarzilli 已提交
1343 1344
		assertNoError(err, t, "EvalExpression()")
		assertNoError(setVariable(p, "p1", fmt.Sprintf("(*int)(0x%x)", i2addr.Addr)), t, "SetVariable()")
1345 1346 1347 1348 1349 1350 1351 1352 1353
		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) {
1354
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1355
		err := proc.Continue(p)
1356 1357
		assertNoError(err, t, "Continue() returned an error")

1358 1359
		evalVariable(p, t, "a1")
		evalVariable(p, t, "a2")
1360 1361

		// Move scopes, a1 exists here by a2 does not
1362
		err = proc.Continue(p)
1363 1364
		assertNoError(err, t, "Continue() returned an error")

1365
		evalVariable(p, t, "a1")
1366

1367
		_, err = evalVariableOrError(p, "a2")
1368 1369 1370 1371 1372 1373 1374
		if err == nil {
			t.Fatalf("Can eval out of scope variable a2")
		}
	})
}

func TestRecursiveStructure(t *testing.T) {
1375
	protest.AllowRecording(t)
1376
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1377
		assertNoError(proc.Continue(p), t, "Continue()")
1378
		v := evalVariable(p, t, "aas")
1379 1380 1381
		t.Logf("v: %v\n", v)
	})
}
1382 1383 1384

func TestIssue316(t *testing.T) {
	// A pointer loop that includes one interface should not send dlv into an infinite loop
1385
	protest.AllowRecording(t)
1386
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1387
		assertNoError(proc.Continue(p), t, "Continue()")
1388
		evalVariable(p, t, "iface5")
1389 1390
	})
}
1391 1392 1393

func TestIssue325(t *testing.T) {
	// nil pointer dereference when evaluating interfaces to function pointers
1394
	protest.AllowRecording(t)
1395
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1396
		assertNoError(proc.Continue(p), t, "Continue()")
1397
		iface2fn1v := evalVariable(p, t, "iface2fn1")
1398 1399
		t.Logf("iface2fn1: %v\n", iface2fn1v)

1400
		iface2fn2v := evalVariable(p, t, "iface2fn2")
1401 1402 1403
		t.Logf("iface2fn2: %v\n", iface2fn2v)
	})
}
1404 1405

func TestBreakpointCounts(t *testing.T) {
1406 1407 1408
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1409
	protest.AllowRecording(t)
1410
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1411
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1412
		assertNoError(err, t, "LineToPC")
1413
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1414 1415 1416
		assertNoError(err, t, "SetBreakpoint()")

		for {
1417
			if err := proc.Continue(p); err != nil {
1418
				if _, exited := err.(proc.ErrProcessExited); exited {
1419 1420 1421 1422 1423 1424 1425
					break
				}
				assertNoError(err, t, "Continue()")
			}
		}

		t.Logf("TotalHitCount: %d", bp.TotalHitCount)
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
		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)
			}
		}
	})
}

1442 1443
func BenchmarkArray(b *testing.B) {
	// each bencharr struct is 128 bytes, bencharr is 64 elements long
1444
	protest.AllowRecording(b)
1445
	b.SetBytes(int64(64 * 128))
1446
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1447
		assertNoError(proc.Continue(p), b, "Continue()")
1448
		for i := 0; i < b.N; i++ {
1449
			evalVariable(p, b, "bencharr")
1450 1451 1452 1453
		}
	})
}

1454 1455 1456 1457 1458 1459 1460
const doTestBreakpointCountsWithDetection = false

func TestBreakpointCountsWithDetection(t *testing.T) {
	if !doTestBreakpointCountsWithDetection {
		return
	}
	m := map[int64]int64{}
1461
	protest.AllowRecording(t)
1462
	withTestProcess("bpcountstest", t, func(p proc.Process, fixture protest.Fixture) {
1463
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 12)
1464
		assertNoError(err, t, "LineToPC")
1465
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1466 1467 1468
		assertNoError(err, t, "SetBreakpoint()")

		for {
1469
			if err := proc.Continue(p); err != nil {
1470
				if _, exited := err.(proc.ErrProcessExited); exited {
1471 1472 1473 1474
					break
				}
				assertNoError(err, t, "Continue()")
			}
1475
			for _, th := range p.ThreadList() {
1476
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
1477 1478
					continue
				}
1479
				scope, err := proc.GoroutineScope(th)
1480
				assertNoError(err, t, "Scope()")
1481
				v, err := scope.EvalVariable("i", normalLoadConfig)
1482 1483
				assertNoError(err, t, "evalVariable")
				i, _ := constant.Int64Val(v.Value)
1484
				v, err = scope.EvalVariable("id", normalLoadConfig)
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
				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)
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
		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)
			}
		}
	})
}
1516

1517 1518 1519
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
1520
	protest.AllowRecording(b)
1521
	b.SetBytes(int64(64*128 + 64*8))
1522
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1523
		assertNoError(proc.Continue(p), b, "Continue()")
1524
		for i := 0; i < b.N; i++ {
1525
			evalVariable(p, b, "bencharr")
1526 1527 1528 1529 1530 1531 1532 1533
		}
	})
}

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
1534
	protest.AllowRecording(b)
1535
	b.SetBytes(int64(41 * (2*8 + 9)))
1536
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1537
		assertNoError(proc.Continue(p), b, "Continue()")
1538
		for i := 0; i < b.N; i++ {
1539
			evalVariable(p, b, "m1")
1540 1541 1542 1543 1544
		}
	})
}

func BenchmarkGoroutinesInfo(b *testing.B) {
1545
	protest.AllowRecording(b)
1546
	withTestProcess("testvariables2", b, func(p proc.Process, fixture protest.Fixture) {
1547
		assertNoError(proc.Continue(p), b, "Continue()")
1548
		for i := 0; i < b.N; i++ {
1549
			p.Common().ClearAllGCache()
1550
			_, _, err := proc.GoroutinesInfo(p, 0, 0)
1551 1552 1553 1554 1555
			assertNoError(err, b, "GoroutinesInfo")
		}
	})
}

1556 1557
func TestIssue262(t *testing.T) {
	// Continue does not work when the current breakpoint is set on a NOP instruction
1558
	protest.AllowRecording(t)
1559
	withTestProcess("issue262", t, func(p proc.Process, fixture protest.Fixture) {
1560
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 11)
1561
		assertNoError(err, t, "LineToPC")
1562
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1563 1564
		assertNoError(err, t, "SetBreakpoint()")

1565 1566
		assertNoError(proc.Continue(p), t, "Continue()")
		err = proc.Continue(p)
1567 1568 1569
		if err == nil {
			t.Fatalf("No error on second continue")
		}
1570
		_, exited := err.(proc.ErrProcessExited)
1571 1572 1573 1574 1575
		if !exited {
			t.Fatalf("Process did not exit after second continue: %v", err)
		}
	})
}
1576

1577
func TestIssue305(t *testing.T) {
1578 1579 1580
	// If 'next' hits a breakpoint on the goroutine it's stepping through
	// the internal breakpoints aren't cleared preventing further use of
	// 'next' command
1581
	protest.AllowRecording(t)
1582
	withTestProcess("issue305", t, func(p proc.Process, fixture protest.Fixture) {
1583
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 5)
1584
		assertNoError(err, t, "LineToPC()")
1585
		_, err = p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1586 1587
		assertNoError(err, t, "SetBreakpoint()")

1588
		assertNoError(proc.Continue(p), t, "Continue()")
1589

1590 1591 1592 1593 1594
		assertNoError(proc.Next(p), t, "Next() 1")
		assertNoError(proc.Next(p), t, "Next() 2")
		assertNoError(proc.Next(p), t, "Next() 3")
		assertNoError(proc.Next(p), t, "Next() 4")
		assertNoError(proc.Next(p), t, "Next() 5")
1595 1596 1597
	})
}

1598 1599 1600
func TestPointerLoops(t *testing.T) {
	// Pointer loops through map entries, pointers and slices
	// Regression test for issue #341
1601
	protest.AllowRecording(t)
1602
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1603
		assertNoError(proc.Continue(p), t, "Continue()")
1604 1605
		for _, expr := range []string{"mapinf", "ptrinf", "sliceinf"} {
			t.Logf("requesting %s", expr)
1606
			v := evalVariable(p, t, expr)
1607 1608
			t.Logf("%s: %v\n", expr, v)
		}
1609 1610
	})
}
1611 1612

func BenchmarkLocalVariables(b *testing.B) {
1613
	protest.AllowRecording(b)
1614
	withTestProcess("testvariables", b, func(p proc.Process, fixture protest.Fixture) {
1615 1616
		assertNoError(proc.Continue(p), b, "Continue() returned an error")
		scope, err := proc.GoroutineScope(p.CurrentThread())
1617 1618
		assertNoError(err, b, "Scope()")
		for i := 0; i < b.N; i++ {
1619
			_, err := scope.LocalVariables(normalLoadConfig)
1620 1621 1622 1623
			assertNoError(err, b, "LocalVariables()")
		}
	})
}
1624 1625

func TestCondBreakpoint(t *testing.T) {
1626 1627 1628
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1629
	protest.AllowRecording(t)
1630
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1631
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1632
		assertNoError(err, t, "LineToPC")
1633
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1634 1635 1636 1637 1638 1639 1640
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1641
		assertNoError(proc.Continue(p), t, "Continue()")
1642

1643
		nvar := evalVariable(p, t, "n")
1644 1645 1646 1647 1648 1649 1650 1651 1652

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

func TestCondBreakpointError(t *testing.T) {
1653 1654 1655
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1656
	protest.AllowRecording(t)
1657
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1658
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1659
		assertNoError(err, t, "LineToPC")
1660
		bp, err := p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
1661 1662 1663 1664 1665 1666 1667
		assertNoError(err, t, "SetBreakpoint()")
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "nonexistentvariable"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "7"},
		}

1668
		err = proc.Continue(p)
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
		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"},
		}

1683
		err = proc.Continue(p)
1684
		if err != nil {
1685
			if _, exited := err.(proc.ErrProcessExited); !exited {
1686 1687 1688
				t.Fatalf("Unexpected error on second Continue(): %v", err)
			}
		} else {
1689
			nvar := evalVariable(p, t, "n")
1690 1691 1692 1693 1694 1695 1696 1697

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

func TestIssue356(t *testing.T) {
	// slice with a typedef does not get printed correctly
1701
	protest.AllowRecording(t)
1702
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
1703
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1704
		mmvar := evalVariable(p, t, "mainMenu")
1705 1706 1707 1708 1709
		if mmvar.Kind != reflect.Slice {
			t.Fatalf("Wrong kind for mainMenu: %v\n", mmvar.Kind)
		}
	})
}
1710 1711

func TestStepIntoFunction(t *testing.T) {
1712
	withTestProcess("teststep", t, func(p proc.Process, fixture protest.Fixture) {
1713
		// Continue until breakpoint
1714
		assertNoError(proc.Continue(p), t, "Continue() returned an error")
1715
		// Step into function
1716
		assertNoError(proc.Step(p), t, "Step() returned an error")
1717
		// We should now be inside the function.
1718
		loc, err := p.CurrentThread().Location()
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
		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)
		}
	})
}
1733 1734 1735

func TestIssue384(t *testing.T) {
	// Crash related to reading uninitialized memory, introduced by the memory prefetching optimization
1736 1737 1738 1739 1740

	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major < 0 || ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// go 1.10 emits DW_AT_decl_line and we won't be able to evaluate 'st'
		// which is declared after line 13.
1741
		t.Skip("can not evaluate not-yet-declared variables with go 1.10")
1742 1743
	}

1744
	protest.AllowRecording(t)
1745
	withTestProcess("issue384", t, func(p proc.Process, fixture protest.Fixture) {
1746
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 13)
1747
		assertNoError(err, t, "LineToPC()")
1748
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1749
		assertNoError(err, t, "SetBreakpoint()")
1750
		assertNoError(proc.Continue(p), t, "Continue()")
1751
		evalVariable(p, t, "st")
1752 1753
	})
}
A
aarzilli 已提交
1754 1755 1756

func TestIssue332_Part1(t *testing.T) {
	// Next shouldn't step inside a function call
1757
	protest.AllowRecording(t)
1758
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1759
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1760
		assertNoError(err, t, "LineToPC()")
1761
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1762
		assertNoError(err, t, "SetBreakpoint()")
1763 1764 1765
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "first Next()")
		locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
		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
1784
	protest.AllowRecording(t)
1785
	withTestProcess("issue332", t, func(p proc.Process, fixture protest.Fixture) {
1786
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 8)
A
aarzilli 已提交
1787
		assertNoError(err, t, "LineToPC()")
1788
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
A
aarzilli 已提交
1789
		assertNoError(err, t, "SetBreakpoint()")
1790
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
1791 1792 1793

		// step until we enter changeMe
		for {
1794 1795
			assertNoError(proc.Step(p), t, "Step()")
			locations, err := proc.ThreadStacktrace(p.CurrentThread(), 2)
A
aarzilli 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804
			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
			}
		}

1805 1806 1807
		regs, err := p.CurrentThread().Registers(false)
		assertNoError(err, t, "Registers()")
		pc := regs.PC()
1808
		pcAfterPrologue, err := proc.FindFunctionLocation(p, "main.changeMe", 0)
1809
		assertNoError(err, t, "FindFunctionLocation()")
1810
		if pcAfterPrologue == p.BinInfo().LookupFunc["main.changeMe"].Entry {
1811 1812 1813 1814 1815 1816
			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)
		}

1817 1818 1819 1820
		assertNoError(proc.Next(p), t, "first Next()")
		assertNoError(proc.Next(p), t, "second Next()")
		assertNoError(proc.Next(p), t, "third Next()")
		err = proc.Continue(p)
1821
		if _, exited := err.(proc.ErrProcessExited); !exited {
A
aarzilli 已提交
1822 1823 1824 1825
			assertNoError(err, t, "final Continue()")
		}
	})
}
1826 1827

func TestIssue396(t *testing.T) {
A
Alessandro Arzilli 已提交
1828 1829 1830 1831 1832
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 13) {
		// CL 161337 in Go 1.13 and later removes the autogenerated init function
		// https://go-review.googlesource.com/c/go/+/161337
		t.Skip("no autogenerated init function in Go 1.13 or later")
	}
1833
	withTestProcess("callme", t, func(p proc.Process, fixture protest.Fixture) {
1834
		_, err := proc.FindFunctionLocation(p, "main.init", 0)
1835 1836 1837
		assertNoError(err, t, "FindFunctionLocation()")
	})
}
1838 1839 1840

func TestIssue414(t *testing.T) {
	// Stepping until the program exits
1841
	protest.AllowRecording(t)
1842
	withTestProcess("math", t, func(p proc.Process, fixture protest.Fixture) {
1843
		start, _, err := p.BinInfo().LineToPC(fixture.Source, 9)
1844
		assertNoError(err, t, "LineToPC()")
1845
		_, err = p.SetBreakpoint(start, proc.UserBreakpoint, nil)
1846
		assertNoError(err, t, "SetBreakpoint()")
1847
		assertNoError(proc.Continue(p), t, "Continue()")
1848
		for {
1849
			err := proc.Step(p)
1850
			if err != nil {
1851
				if _, exited := err.(proc.ErrProcessExited); exited {
1852 1853 1854 1855 1856 1857 1858
					break
				}
			}
			assertNoError(err, t, "Step()")
		}
	})
}
1859 1860

func TestPackageVariables(t *testing.T) {
1861
	protest.AllowRecording(t)
1862
	withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {
1863
		err := proc.Continue(p)
1864
		assertNoError(err, t, "Continue()")
1865
		scope, err := proc.GoroutineScope(p.CurrentThread())
1866
		assertNoError(err, t, "Scope()")
1867
		vars, err := scope.PackageVariables(normalLoadConfig)
1868 1869 1870
		assertNoError(err, t, "PackageVariables()")
		failed := false
		for _, v := range vars {
1871
			if v.Unreadable != nil && v.Unreadable.Error() != "no location attribute Location" {
1872 1873 1874 1875 1876 1877 1878 1879 1880
				failed = true
				t.Logf("Unreadable variable %s: %v", v.Name, v.Unreadable)
			}
		}
		if failed {
			t.Fatalf("previous errors")
		}
	})
}
1881 1882

func TestIssue149(t *testing.T) {
1883 1884
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
1885 1886 1887
		return
	}
	// setting breakpoint on break statement
1888
	withTestProcess("break", t, func(p proc.Process, fixture protest.Fixture) {
1889
		_, err := proc.FindFileLocation(p, fixture.Source, 8)
1890 1891 1892
		assertNoError(err, t, "FindFileLocation()")
	})
}
1893 1894

func TestPanicBreakpoint(t *testing.T) {
1895
	protest.AllowRecording(t)
1896
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
1897
		assertNoError(proc.Continue(p), t, "Continue()")
1898 1899
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1900
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1901 1902 1903
		}
	})
}
1904

1905
func TestCmdLineArgs(t *testing.T) {
1906
	expectSuccess := func(p proc.Process, fixture protest.Fixture) {
1907
		err := proc.Continue(p)
1908 1909
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint != nil && bp.Name == proc.UnrecoveredPanic {
1910
			t.Fatalf("testing args failed on unrecovered-panic breakpoint: %v", bp)
1911
		}
1912
		exit, exited := err.(proc.ErrProcessExited)
1913
		if !exited {
1914
			t.Fatalf("Process did not exit: %v", err)
1915 1916
		} else {
			if exit.Status != 0 {
1917
				t.Fatalf("process exited with invalid status %d", exit.Status)
1918 1919 1920 1921
			}
		}
	}

1922
	expectPanic := func(p proc.Process, fixture protest.Fixture) {
1923
		proc.Continue(p)
1924 1925
		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != proc.UnrecoveredPanic {
1926
			t.Fatalf("not on unrecovered-panic breakpoint: %v", bp)
1927 1928 1929 1930
		}
	}

	// make sure multiple arguments (including one with spaces) are passed to the binary correctly
1931 1932 1933
	withTestProcessArgs("testargs", t, ".", []string{"test"}, 0, expectSuccess)
	withTestProcessArgs("testargs", t, ".", []string{"-test"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass flag"}, 0, expectSuccess)
1934
	// check that arguments with spaces are *only* passed correctly when correctly called
1935 1936 1937
	withTestProcessArgs("testargs", t, ".", []string{"test pass", "flag"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "pass", "flag"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test pass flag"}, 0, expectPanic)
1938 1939
	// and that invalid cases (wrong arguments or no arguments) panic
	withTestProcess("testargs", t, expectPanic)
1940 1941 1942
	withTestProcessArgs("testargs", t, ".", []string{"invalid"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"test", "invalid"}, 0, expectPanic)
	withTestProcessArgs("testargs", t, ".", []string{"invalid", "pass flag"}, 0, expectPanic)
1943 1944
}

1945 1946 1947 1948 1949
func TestIssue462(t *testing.T) {
	// Stacktrace of Goroutine 0 fails with an error
	if runtime.GOOS == "windows" {
		return
	}
1950
	withTestProcess("testnextnethttp", t, func(p proc.Process, fixture protest.Fixture) {
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
		go func() {
			// Wait for program to start listening.
			for {
				conn, err := net.Dial("tcp", "localhost:9191")
				if err == nil {
					conn.Close()
					break
				}
				time.Sleep(50 * time.Millisecond)
			}

			p.RequestManualStop()
		}()

1965 1966
		assertNoError(proc.Continue(p), t, "Continue()")
		_, err := proc.ThreadStacktrace(p.CurrentThread(), 40)
1967 1968 1969
		assertNoError(err, t, "Stacktrace()")
	})
}
1970

1971
func TestNextParked(t *testing.T) {
1972 1973 1974
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
1975
	protest.AllowRecording(t)
1976
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
1977 1978 1979 1980
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
1981
		var parkedg *proc.G
1982
		for parkedg == nil {
1983
			err := proc.Continue(p)
1984
			if _, exited := err.(proc.ErrProcessExited); exited {
1985 1986 1987 1988 1989
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

1990
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
1991 1992
			assertNoError(err, t, "GoroutinesInfo()")

1993 1994 1995 1996
			// Search for a parked goroutine that we know for sure will have to be
			// resumed before the program can exit. This is a parked goroutine that:
			// 1. is executing main.sayhi
			// 2. hasn't called wg.Done yet
1997
			for _, g := range gs {
1998 1999 2000
				if g.Thread != nil {
					continue
				}
2001
				frames, _ := g.Stacktrace(5, false)
2002 2003 2004 2005 2006 2007 2008 2009 2010
				for _, frame := range frames {
					// line 11 is the line where wg.Done is called
					if frame.Current.Fn != nil && frame.Current.Fn.Name == "main.sayhi" && frame.Current.Line < 11 {
						parkedg = g
						break
					}
				}
				if parkedg != nil {
					break
2011 2012 2013 2014 2015 2016
				}
			}
		}

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

2019 2020
		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)
2021 2022 2023
		}
	})
}
2024 2025

func TestStepParked(t *testing.T) {
2026 2027 2028
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
2029
	protest.AllowRecording(t)
2030
	withTestProcess("parallel_next", t, func(p proc.Process, fixture protest.Fixture) {
2031 2032 2033 2034
		bp, err := setFunctionBreakpoint(p, "main.sayhi")
		assertNoError(err, t, "SetBreakpoint()")

		// continue until a parked goroutine exists
2035
		var parkedg *proc.G
2036 2037
	LookForParkedG:
		for {
2038
			err := proc.Continue(p)
2039
			if _, exited := err.(proc.ErrProcessExited); exited {
2040 2041 2042 2043 2044
				t.Log("could not find parked goroutine")
				return
			}
			assertNoError(err, t, "Continue()")

2045
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
2046 2047 2048
			assertNoError(err, t, "GoroutinesInfo()")

			for _, g := range gs {
2049
				if g.Thread == nil && g.CurrentLoc.Fn != nil && g.CurrentLoc.Fn.Name == "main.sayhi" {
2050 2051 2052 2053 2054 2055
					parkedg = g
					break LookForParkedG
				}
			}
		}

A
aarzilli 已提交
2056
		t.Logf("Parked g is: %v\n", parkedg)
2057
		frames, _ := parkedg.Stacktrace(20, false)
A
aarzilli 已提交
2058 2059 2060 2061 2062 2063 2064 2065
		for _, frame := range frames {
			name := ""
			if frame.Call.Fn != nil {
				name = frame.Call.Fn.Name
			}
			t.Logf("\t%s:%d in %s (%#x)", frame.Call.File, frame.Call.Line, name, frame.Current.PC)
		}

2066 2067
		assertNoError(p.SwitchGoroutine(parkedg.ID), t, "SwitchGoroutine()")
		p.ClearBreakpoint(bp.Addr)
2068
		assertNoError(proc.Step(p), t, "Step()")
2069

2070 2071
		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)
2072 2073 2074
		}
	})
}
2075 2076 2077 2078 2079 2080 2081 2082

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")
2083 2084 2085 2086 2087
	defer os.Remove(exepath)
	var err error

	switch testBackend {
	case "native":
2088
		_, err = native.Launch([]string{exepath}, ".", false, []string{})
2089
	case "lldb":
2090
		_, err = gdbserial.LLDBLaunch([]string{exepath}, ".", false, []string{})
2091 2092 2093
	default:
		t.Skip("test not valid for this backend")
	}
2094 2095 2096
	if err == nil {
		t.Fatalf("expected error but none was generated")
	}
2097 2098
	if err != proc.ErrNotExecutable {
		t.Fatalf("expected error \"%v\" got \"%v\"", proc.ErrNotExecutable, err)
2099 2100 2101 2102
	}
}

func TestUnsupportedArch(t *testing.T) {
2103 2104
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major < 0 || !ver.AfterOrEqual(goversion.GoVersion{1, 6, -1, 0, 0, ""}) || ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {
2105 2106 2107
		// cross compile (with -N?) works only on select versions of go
		return
	}
2108

2109 2110 2111
	fixturesDir := protest.FindFixturesDir()
	infile := filepath.Join(fixturesDir, "math.go")
	outfile := filepath.Join(fixturesDir, "_math_debug_386")
2112

2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
	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)
2125

2126 2127 2128 2129
	var p proc.Process

	switch testBackend {
	case "native":
2130
		p, err = native.Launch([]string{outfile}, ".", false, []string{})
2131
	case "lldb":
2132
		p, err = gdbserial.LLDBLaunch([]string{outfile}, ".", false, []string{})
2133 2134 2135 2136
	default:
		t.Skip("test not valid for this backend")
	}

2137
	switch err {
2138
	case proc.ErrUnsupportedLinuxArch, proc.ErrUnsupportedWindowsArch, proc.ErrUnsupportedDarwinArch:
2139 2140
		// all good
	case nil:
A
aarzilli 已提交
2141
		p.Detach(true)
2142 2143 2144 2145 2146
		t.Fatal("Launch is expected to fail, but succeeded")
	default:
		t.Fatal(err)
	}
}
2147

2148
func TestIssue573(t *testing.T) {
2149
	// calls to runtime.duffzero and runtime.duffcopy jump directly into the middle
2150
	// of the function and the internal breakpoint set by StepInto may be missed.
2151
	protest.AllowRecording(t)
2152
	withTestProcess("issue573", t, func(p proc.Process, fixture protest.Fixture) {
2153
		fentry, _ := proc.FindFunctionLocation(p, "main.foo", 0)
2154
		_, err := p.SetBreakpoint(fentry, proc.UserBreakpoint, nil)
2155
		assertNoError(err, t, "SetBreakpoint()")
2156 2157 2158 2159
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step() #1")
		assertNoError(proc.Step(p), t, "Step() #2") // Bug exits here.
		assertNoError(proc.Step(p), t, "Step() #3") // Third step ought to be possible; program ought not have exited.
2160 2161
	})
}
2162 2163

func TestTestvariables2Prologue(t *testing.T) {
2164
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2165 2166
		addrEntry := p.BinInfo().LookupFunc["main.main"].Entry
		addrPrologue, err := proc.FindFunctionLocation(p, "main.main", 0)
2167 2168 2169 2170 2171 2172
		assertNoError(err, t, "FindFunctionLocation - postprologue")
		if addrEntry == addrPrologue {
			t.Fatalf("Prologue detection failed on testvariables2.go/main.main")
		}
	})
}
2173 2174 2175 2176 2177

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 已提交
2178
	testseq("defercall", contNext, []nextTest{
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
		{9, 10},
		{10, 11},
		{11, 12},
		{12, 13},
		{13, 28}}, "main.callAndDeferReturn", t)
}

func TestNextPanicAndDirectCall(t *testing.T) {
	// Next should not step into a deferred function if it is called
	// directly, only if it is called through a panic or a deferreturn.
	// Here we test the case where the function is called by a panic
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq("defercall", contNext, []nextTest{
			{15, 16},
			{16, 17},
			{17, 18},
			{18, 6}}, "main.callAndPanic2", t)
	} else {
		testseq("defercall", contNext, []nextTest{
			{15, 16},
			{16, 17},
			{17, 18},
			{18, 5}}, "main.callAndPanic2", t)
	}
2203
}
A
aarzilli 已提交
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213

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.
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq("teststepprog", contStep, []nextTest{
			{9, 10},
			{10, 6},
			{6, 7},
			{7, 11}}, "", t)
	} else {
		testseq("teststepprog", contStep, []nextTest{
			{9, 10},
			{10, 5},
			{5, 6},
			{6, 7},
			{7, 11}}, "", t)
	}
A
aarzilli 已提交
2228 2229 2230 2231 2232
}

func TestStepReturnAndPanic(t *testing.T) {
	// Tests that Step works correctly when returning from functions
	// and when a deferred function is called when panic'ing.
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
	switch {
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 11):
		testseq("defercall", contStep, []nextTest{
			{17, 6},
			{6, 7},
			{7, 18},
			{18, 6},
			{6, 7}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 10):
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 9):
A
aarzilli 已提交
2251 2252 2253 2254 2255 2256 2257 2258 2259
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 17},
			{17, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
2260
	default:
A
aarzilli 已提交
2261 2262 2263 2264 2265 2266 2267 2268 2269
		testseq("defercall", contStep, []nextTest{
			{17, 5},
			{5, 6},
			{6, 7},
			{7, 18},
			{18, 5},
			{5, 6},
			{6, 7}}, "", t)
	}
A
aarzilli 已提交
2270 2271 2272 2273 2274
}

func TestStepDeferReturn(t *testing.T) {
	// Tests that Step works correctly when a deferred function is
	// called during a return.
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq("defercall", contStep, []nextTest{
			{11, 6},
			{6, 7},
			{7, 12},
			{12, 13},
			{13, 6},
			{6, 7},
			{7, 13},
			{13, 28}}, "", t)
	} else {
		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)
	}
A
aarzilli 已提交
2298 2299 2300 2301 2302
}

func TestStepIgnorePrivateRuntime(t *testing.T) {
	// Tests that Step will ignore calls to private runtime functions
	// (such as runtime.convT2E in this case)
2303 2304 2305 2306 2307 2308 2309
	switch {
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 11):
		testseq("teststepprog", contStep, []nextTest{
			{21, 14},
			{14, 15},
			{15, 22}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 10):
A
aarzilli 已提交
2310 2311 2312 2313
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
2314 2315
			{15, 22}}, "", t)
	case goversion.VersionAfterOrEqual(runtime.Version(), 1, 7):
2316 2317 2318 2319
		testseq("teststepprog", contStep, []nextTest{
			{21, 13},
			{13, 14},
			{14, 15},
2320 2321 2322 2323
			{15, 14},
			{14, 17},
			{17, 22}}, "", t)
	default:
A
aarzilli 已提交
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
		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.
2336
	protest.AllowRecording(t)
2337
	withTestProcess("issue561", t, func(p proc.Process, fixture protest.Fixture) {
2338
		setFileBreakpoint(p, t, fixture, 10)
2339 2340
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Step(p), t, "Step()")
2341
		assertLineNumber(p, t, 5, "wrong line number after Step,")
A
aarzilli 已提交
2342 2343 2344
	})
}

A
aarzilli 已提交
2345
func TestStepOut(t *testing.T) {
2346
	testseq2(t, "testnextprog", "main.helloworld", []seqTest{{contContinue, 13}, {contStepout, 35}})
A
aarzilli 已提交
2347 2348
}

A
aarzilli 已提交
2349
func TestStepConcurrentDirect(t *testing.T) {
2350 2351 2352
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
2353
	protest.AllowRecording(t)
2354
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2355
		pc, err := proc.FindFileLocation(p, fixture.Source, 37)
A
aarzilli 已提交
2356
		assertNoError(err, t, "FindFileLocation()")
2357
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2358 2359
		assertNoError(err, t, "SetBreakpoint()")

2360
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2361 2362 2363
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint()")

A
aarzilli 已提交
2364
		for _, b := range p.Breakpoints().M {
2365
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2366 2367 2368 2369 2370 2371
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

2372
		gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2373 2374 2375 2376 2377 2378

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

		i := 0
		count := 0
		for {
A
aarzilli 已提交
2379
			anyerr := false
2380 2381
			if p.SelectedGoroutine().ID != gid {
				t.Errorf("Step switched to different goroutine %d %d\n", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2382 2383
				anyerr = true
			}
A
aarzilli 已提交
2384 2385 2386 2387 2388 2389
			f, ln := currentLineNumber(p, t)
			if ln != seq[i] {
				if i == 1 && ln == 40 {
					// loop exited
					break
				}
2390
				frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
A
aarzilli 已提交
2391
				if err != nil {
2392
					t.Errorf("Could not get stacktrace of goroutine %d\n", p.SelectedGoroutine().ID)
A
aarzilli 已提交
2393
				} else {
2394
					t.Logf("Goroutine %d (thread: %d):", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
A
aarzilli 已提交
2395 2396 2397 2398 2399 2400
					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 已提交
2401
			}
A
aarzilli 已提交
2402 2403
			if anyerr {
				t.FailNow()
A
aarzilli 已提交
2404 2405 2406 2407 2408
			}
			i = (i + 1) % len(seq)
			if i == 0 {
				count++
			}
2409
			assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2410 2411 2412 2413 2414 2415 2416 2417 2418
		}

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

func TestStepConcurrentPtr(t *testing.T) {
2419 2420 2421
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
2422
	protest.AllowRecording(t)
2423
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
2424
		pc, err := proc.FindFileLocation(p, fixture.Source, 24)
A
aarzilli 已提交
2425
		assertNoError(err, t, "FindFileLocation()")
2426
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2427 2428
		assertNoError(err, t, "SetBreakpoint()")

A
aarzilli 已提交
2429
		for _, b := range p.Breakpoints().M {
2430
			if b.Name == proc.UnrecoveredPanic {
A
aarzilli 已提交
2431 2432 2433 2434 2435 2436
				_, err := p.ClearBreakpoint(b.Addr)
				assertNoError(err, t, "ClearBreakpoint(unrecovered-panic)")
				break
			}
		}

A
aarzilli 已提交
2437 2438 2439
		kvals := map[int]int64{}
		count := 0
		for {
2440
			err := proc.Continue(p)
2441
			_, exited := err.(proc.ErrProcessExited)
A
aarzilli 已提交
2442 2443 2444 2445 2446 2447 2448
			if exited {
				break
			}
			assertNoError(err, t, "Continue()")

			f, ln := currentLineNumber(p, t)
			if ln != 24 {
2449
				for _, th := range p.ThreadList() {
2450
					t.Logf("thread %d stopped on breakpoint %v", th.ThreadID(), th.Breakpoint())
A
aarzilli 已提交
2451
				}
2452
				curbp := p.CurrentThread().Breakpoint()
2453
				t.Fatalf("Program did not continue at expected location (24): %s:%d %#x [%v] (gid %d count %d)", f, ln, currentPC(p, t), curbp, p.SelectedGoroutine().ID, count)
A
aarzilli 已提交
2454 2455
			}

2456
			gid := p.SelectedGoroutine().ID
A
aarzilli 已提交
2457

2458
			kvar := evalVariable(p, t, "k")
A
aarzilli 已提交
2459 2460 2461 2462
			k, _ := constant.Int64Val(kvar.Value)

			if oldk, ok := kvals[gid]; ok {
				if oldk >= k {
2463
					t.Fatalf("Goroutine %d did not make progress?", gid)
A
aarzilli 已提交
2464 2465 2466 2467
				}
			}
			kvals[gid] = k

2468
			assertNoError(proc.Step(p), t, "Step()")
2469
			for p.Breakpoints().HasInternalBreakpoints() {
2470 2471
				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 已提交
2472
				}
2473
				assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2474 2475
			}

2476 2477
			if p.SelectedGoroutine().ID != gid {
				t.Fatalf("Step switched goroutines (wanted: %d got: %d)", gid, p.SelectedGoroutine().ID)
A
aarzilli 已提交
2478 2479
			}

2480
			f, ln = assertLineNumber(p, t, 13, "Step did not step into function call")
A
aarzilli 已提交
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495

			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 已提交
2496
func TestStepOutDefer(t *testing.T) {
2497
	protest.AllowRecording(t)
2498
	withTestProcess("testnextdefer", t, func(p proc.Process, fixture protest.Fixture) {
2499
		pc, err := proc.FindFileLocation(p, fixture.Source, 9)
A
aarzilli 已提交
2500
		assertNoError(err, t, "FindFileLocation()")
2501
		bp, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2502
		assertNoError(err, t, "SetBreakpoint()")
2503
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2504 2505
		p.ClearBreakpoint(bp.Addr)

2506
		assertLineNumber(p, t, 9, "wrong line number")
A
aarzilli 已提交
2507

2508
		assertNoError(proc.StepOut(p), t, "StepOut()")
A
aarzilli 已提交
2509

2510
		f, l, _ := p.BinInfo().PCToLine(currentPC(p, t))
A
aarzilli 已提交
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
		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
2521 2522 2523
	testseq2(t, "defercall", "", []seqTest{
		{contContinue, 11},
		{contStepout, 28}})
A
aarzilli 已提交
2524 2525
}

2526 2527
const maxInstructionLength uint64 = 15

A
aarzilli 已提交
2528
func TestStepOnCallPtrInstr(t *testing.T) {
2529
	protest.AllowRecording(t)
2530
	withTestProcess("teststepprog", t, func(p proc.Process, fixture protest.Fixture) {
2531
		pc, err := proc.FindFileLocation(p, fixture.Source, 10)
A
aarzilli 已提交
2532
		assertNoError(err, t, "FindFileLocation()")
2533
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
A
aarzilli 已提交
2534 2535
		assertNoError(err, t, "SetBreakpoint()")

2536
		assertNoError(proc.Continue(p), t, "Continue()")
A
aarzilli 已提交
2537 2538 2539 2540 2541 2542 2543 2544

		found := false

		for {
			_, ln := currentLineNumber(p, t)
			if ln != 10 {
				break
			}
2545
			regs, err := p.CurrentThread().Registers(false)
2546
			assertNoError(err, t, "Registers()")
2547
			pc := regs.PC()
2548
			text, err := proc.Disassemble(p, nil, pc, pc+maxInstructionLength)
A
aarzilli 已提交
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
			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")
		}

2561
		assertNoError(proc.Step(p), t, "Step()")
A
aarzilli 已提交
2562

2563 2564 2565 2566 2567
		if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
			assertLineNumber(p, t, 6, "Step continued to wrong line,")
		} else {
			assertLineNumber(p, t, 5, "Step continued to wrong line,")
		}
A
aarzilli 已提交
2568 2569
	})
}
2570 2571

func TestIssue594(t *testing.T) {
2572 2573 2574 2575 2576 2577 2578 2579
	if runtime.GOOS == "darwin" && testBackend == "lldb" {
		// debugserver will receive an EXC_BAD_ACCESS for this, at that point
		// there is no way to reconvert this exception into a unix signal and send
		// it to the process.
		// This is a bug in debugserver/lldb:
		//  https://bugs.llvm.org//show_bug.cgi?id=22868
		return
	}
2580 2581 2582 2583
	// 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.
2584
	protest.AllowRecording(t)
2585
	withTestProcess("issue594", t, func(p proc.Process, fixture protest.Fixture) {
2586
		assertNoError(proc.Continue(p), t, "Continue()")
2587 2588 2589 2590 2591 2592 2593 2594 2595
		var f string
		var ln int
		if testBackend == "rr" {
			frame, err := findFirstNonRuntimeFrame(p)
			assertNoError(err, t, "findFirstNonRuntimeFrame")
			f, ln = frame.Current.File, frame.Current.Line
		} else {
			f, ln = currentLineNumber(p, t)
		}
2596 2597 2598 2599 2600
		if ln != 21 {
			t.Fatalf("Program stopped at %s:%d, expected :21", f, ln)
		}
	})
}
A
aarzilli 已提交
2601 2602 2603 2604 2605

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
2606 2607 2608 2609 2610 2611 2612 2613 2614
	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		testseq2(t, "defercall", "", []seqTest{
			{contContinue, 17},
			{contStepout, 6}})
	} else {
		testseq2(t, "defercall", "", []seqTest{
			{contContinue, 17},
			{contStepout, 5}})
	}
A
aarzilli 已提交
2615
}
E
Evgeny L 已提交
2616 2617 2618 2619 2620 2621 2622

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"
	}
2623
	protest.AllowRecording(t)
2624
	withTestProcessArgs("workdir", t, wd, []string{}, 0, func(p proc.Process, fixture protest.Fixture) {
2625
		addr, _, err := p.BinInfo().LineToPC(fixture.Source, 14)
E
Evgeny L 已提交
2626
		assertNoError(err, t, "LineToPC")
2627 2628
		p.SetBreakpoint(addr, proc.UserBreakpoint, nil)
		proc.Continue(p)
2629
		v := evalVariable(p, t, "pwd")
E
Evgeny L 已提交
2630 2631 2632 2633
		str := constant.StringVal(v.Value)
		if wd != str {
			t.Fatalf("Expected %s got %s\n", wd, str)
		}
2634
	})
E
Evgeny L 已提交
2635
}
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646

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)},
	}
2647
	protest.AllowRecording(t)
2648
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
2649
		assertNoError(proc.Continue(p), t, "Continue()")
2650
		for _, tc := range testcases {
2651
			v := evalVariable(p, t, tc.name)
2652 2653 2654 2655 2656 2657 2658 2659 2660
			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)
			}
		}
	})
}
2661 2662 2663

func TestIssue683(t *testing.T) {
	// Step panics when source file can not be found
2664
	protest.AllowRecording(t)
2665
	withTestProcess("issue683", t, func(p proc.Process, fixture protest.Fixture) {
2666 2667
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
2668
		assertNoError(proc.Continue(p), t, "First Continue()")
2669 2670 2671
		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
2672
			err := proc.Step(p)
2673 2674 2675 2676
			if err != nil {
				break
			}
		}
2677 2678 2679 2680
	})
}

func TestIssue664(t *testing.T) {
2681
	protest.AllowRecording(t)
2682
	withTestProcess("issue664", t, func(p proc.Process, fixture protest.Fixture) {
2683
		setFileBreakpoint(p, t, fixture, 4)
2684 2685
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
2686
		assertLineNumber(p, t, 5, "Did not continue to correct location,")
2687 2688
	})
}
A
Alessandro Arzilli 已提交
2689 2690 2691

// Benchmarks (*Processs).Continue + (*Scope).FunctionArguments
func BenchmarkTrace(b *testing.B) {
2692
	protest.AllowRecording(b)
2693
	withTestProcess("traceperf", b, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2694 2695 2696 2697
		_, err := setFunctionBreakpoint(p, "main.PerfCheck")
		assertNoError(err, b, "setFunctionBreakpoint()")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
2698 2699
			assertNoError(proc.Continue(p), b, "Continue()")
			s, err := proc.GoroutineScope(p.CurrentThread())
A
Alessandro Arzilli 已提交
2700
			assertNoError(err, b, "Scope()")
2701
			_, err = s.FunctionArguments(proc.LoadConfig{false, 0, 64, 0, 3, 0})
A
Alessandro Arzilli 已提交
2702 2703 2704 2705 2706
			assertNoError(err, b, "FunctionArguments()")
		}
		b.StopTimer()
	})
}
A
Alessandro Arzilli 已提交
2707 2708 2709 2710 2711 2712

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.
2713
	protest.AllowRecording(t)
2714
	withTestProcess("defercall", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2715
		_, err := setFunctionBreakpoint(p, "runtime.deferreturn")
2716
		assertNoError(err, t, "setFunctionBreakpoint(runtime.deferreturn)")
2717
		assertNoError(proc.Continue(p), t, "First Continue()")
2718 2719 2720 2721 2722 2723

		// Set a breakpoint on the deferred function so that the following loop
		// can not step out of the runtime.deferreturn and all the way to the
		// point where the target program panics.
		_, err = setFunctionBreakpoint(p, "main.sampleFunction")
		assertNoError(err, t, "setFunctionBreakpoint(main.sampleFunction)")
A
Alessandro Arzilli 已提交
2724
		for i := 0; i < 20; i++ {
2725 2726 2727 2728 2729 2730
			loc, err := p.CurrentThread().Location()
			assertNoError(err, t, "CurrentThread().Location()")
			t.Logf("at %#x %s:%d", loc.PC, loc.File, loc.Line)
			if loc.Fn != nil && loc.Fn.Name == "main.sampleFunction" {
				break
			}
2731
			assertNoError(proc.Next(p), t, fmt.Sprintf("Next() %d", i))
A
Alessandro Arzilli 已提交
2732 2733 2734 2735
		}
	})
}

2736
func getg(goid int, gs []*proc.G) *proc.G {
A
Alessandro Arzilli 已提交
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
	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.
2751

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

2757 2758 2759 2760 2761
	// 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")

2762
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
A
Alessandro Arzilli 已提交
2763 2764 2765 2766 2767
		// 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 {
2768
			err := proc.Continue(p)
2769
			if _, exited := err.(proc.ErrProcessExited); exited {
2770 2771 2772 2773
				t.Logf("Could not run test")
				return
			}
			assertNoError(err, t, "Continue()")
2774
			gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
Alessandro Arzilli 已提交
2775
			assertNoError(err, t, "GoroutinesInfo()")
2776
			for _, th := range p.ThreadList() {
2777
				if bp := th.Breakpoint(); bp.Breakpoint == nil {
A
Alessandro Arzilli 已提交
2778 2779 2780
					continue
				}

2781
				goidVar := evalVariable(p, t, "gp.goid")
A
Alessandro Arzilli 已提交
2782 2783 2784
				goid, _ := constant.Int64Val(goidVar.Value)

				if g := getg(int(goid), gs); g != nil {
2785
					stack, err := g.Stacktrace(50, false)
A
Alessandro Arzilli 已提交
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
					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)

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

2805
		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
A
Alessandro Arzilli 已提交
2806 2807 2808 2809 2810
		assertNoError(err, t, "GoroutinesInfo()")

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

2811
			stack, err := g.Stacktrace(200, false)
A
Alessandro Arzilli 已提交
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
			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
				}
2834
				t.Logf("\t%s [CFA: %x Ret: %x] at %s:%d", name, frame.Regs.CFA, frame.Ret, frame.Current.File, frame.Current.Line)
A
Alessandro Arzilli 已提交
2835 2836 2837
			}

			if !found {
2838
				t.Logf("Truncated stacktrace for %d\n", goid)
A
Alessandro Arzilli 已提交
2839 2840 2841 2842
			}
		}
	})
}
2843 2844

func TestAttachDetach(t *testing.T) {
2845 2846 2847 2848 2849 2850
	if testBackend == "lldb" && runtime.GOOS == "linux" {
		bs, _ := ioutil.ReadFile("/proc/sys/kernel/yama/ptrace_scope")
		if bs == nil || strings.TrimSpace(string(bs)) != "0" {
			t.Logf("can not run TestAttachDetach: %v\n", bs)
			return
		}
2851
	}
2852 2853 2854
	if testBackend == "rr" {
		return
	}
2855 2856 2857 2858 2859
	var buildFlags protest.BuildFlags
	if buildMode == "pie" {
		buildFlags |= protest.BuildModePIE
	}
	fixture := protest.BuildFixture("testnextnethttp", buildFlags)
2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
	cmd := exec.Command(fixture.Path)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	assertNoError(cmd.Start(), t, "starting fixture")

	// wait for testnextnethttp to start listening
	t0 := time.Now()
	for {
		conn, err := net.Dial("tcp", "localhost:9191")
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(50 * time.Millisecond)
		if time.Since(t0) > 10*time.Second {
			t.Fatal("fixture did not start")
		}
	}

2879
	var p proc.Process
2880 2881 2882 2883
	var err error

	switch testBackend {
	case "native":
2884
		p, err = native.Attach(cmd.Process.Pid, []string{})
2885 2886 2887 2888 2889
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
2890
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path, []string{})
2891 2892 2893 2894
	default:
		err = fmt.Errorf("unknown backend %q", testBackend)
	}

2895 2896 2897 2898 2899 2900
	assertNoError(err, t, "Attach")
	go func() {
		time.Sleep(1 * time.Second)
		http.Get("http://localhost:9191")
	}()

2901
	assertNoError(proc.Continue(p), t, "Continue")
2902
	assertLineNumber(p, t, 11, "Did not continue to correct location,")
2903 2904 2905 2906 2907 2908 2909

	assertNoError(p.Detach(false), t, "Detach")

	resp, err := http.Get("http://localhost:9191/nobp")
	assertNoError(err, t, "Page request after detach")
	bs, err := ioutil.ReadAll(resp.Body)
	assertNoError(err, t, "Reading /nobp page")
2910
	if out := string(bs); !strings.Contains(out, "hello, world!") {
2911 2912 2913 2914 2915
		t.Fatalf("/nobp page does not contain \"hello, world!\": %q", out)
	}

	cmd.Process.Kill()
}
2916 2917

func TestVarSum(t *testing.T) {
2918
	protest.AllowRecording(t)
2919 2920
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2921
		sumvar := evalVariable(p, t, "s1[0] + s1[1]")
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932
		sumvarstr := constant.StringVal(sumvar.Value)
		if sumvarstr != "onetwo" {
			t.Fatalf("s1[0] + s1[1] == %q (expected \"onetwo\")", sumvarstr)
		}
		if sumvar.Len != int64(len(sumvarstr)) {
			t.Fatalf("sumvar.Len == %d (expected %d)", sumvar.Len, len(sumvarstr))
		}
	})
}

func TestPackageWithPathVar(t *testing.T) {
2933
	protest.AllowRecording(t)
2934 2935
	withTestProcess("pkgrenames", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2936 2937
		evalVariable(p, t, "pkg.SomeVar")
		evalVariable(p, t, "pkg.SomeVar.X")
2938 2939
	})
}
2940 2941

func TestEnvironment(t *testing.T) {
2942
	protest.AllowRecording(t)
2943 2944 2945
	os.Setenv("SOMEVAR", "bah")
	withTestProcess("testenv", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
2946
		v := evalVariable(p, t, "x")
2947 2948 2949 2950 2951 2952 2953
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != "bah" {
			t.Fatalf("value of v is %q (expected \"bah\")", vv)
		}
	})
}
2954 2955

func getFrameOff(p proc.Process, t *testing.T) int64 {
2956
	frameoffvar := evalVariable(p, t, "runtime.frameoff")
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
	frameoff, _ := constant.Int64Val(frameoffvar.Value)
	return frameoff
}

func TestRecursiveNext(t *testing.T) {
	protest.AllowRecording(t)
	testcases := []nextTest{
		{6, 7},
		{7, 10},
		{10, 11},
		{11, 17},
	}
	testseq("increment", contNext, testcases, "main.Increment", t)

	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		bp, err := setFunctionBreakpoint(p, "main.Increment")
		assertNoError(err, t, "setFunctionBreakpoint")
		assertNoError(proc.Continue(p), t, "Continue")
		_, err = p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint")
		assertNoError(proc.Next(p), t, "Next 1")
		assertNoError(proc.Next(p), t, "Next 2")
		assertNoError(proc.Next(p), t, "Next 3")
		frameoff0 := getFrameOff(p, t)
		assertNoError(proc.Step(p), t, "Step")
		frameoff1 := getFrameOff(p, t)
		if frameoff0 == frameoff1 {
			t.Fatalf("did not step into function?")
		}
2986
		assertLineNumber(p, t, 6, "program did not continue to expected location,")
2987
		assertNoError(proc.Next(p), t, "Next 4")
2988
		assertLineNumber(p, t, 7, "program did not continue to expected location,")
2989
		assertNoError(proc.StepOut(p), t, "StepOut")
2990
		assertLineNumber(p, t, 11, "program did not continue to expected location,")
2991 2992 2993 2994 2995 2996
		frameoff2 := getFrameOff(p, t)
		if frameoff0 != frameoff2 {
			t.Fatalf("frame offset mismatch %x != %x", frameoff0, frameoff2)
		}
	})
}
2997 2998 2999 3000 3001 3002 3003

// TestIssue877 ensures that the environment variables starting with DYLD_ and LD_
// are passed when executing the binary on OSX via debugserver
func TestIssue877(t *testing.T) {
	if runtime.GOOS != "darwin" && testBackend == "lldb" {
		return
	}
A
aarzilli 已提交
3004 3005 3006 3007 3008
	if os.Getenv("TRAVIS") == "true" && runtime.GOOS == "darwin" {
		// Something changed on Travis side that makes the Go compiler fail if
		// DYLD_LIBRARY_PATH is set.
		t.Skip("broken")
	}
3009 3010 3011 3012
	const envval = "/usr/local/lib"
	os.Setenv("DYLD_LIBRARY_PATH", envval)
	withTestProcess("issue877", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
3013
		v := evalVariable(p, t, "dyldenv")
3014 3015 3016 3017 3018 3019 3020
		vv := constant.StringVal(v.Value)
		t.Logf("v = %q", vv)
		if vv != envval {
			t.Fatalf("value of v is %q (expected %q)", vv, envval)
		}
	})
}
3021 3022 3023 3024

func TestIssue893(t *testing.T) {
	// Test what happens when next is called immediately after launching the
	// executable, acceptable behaviors are: (a) no error, (b) no source at PC
3025
	// error, (c) program runs to completion
3026 3027 3028 3029 3030 3031
	protest.AllowRecording(t)
	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		err := proc.Next(p)
		if err == nil {
			return
		}
3032
		if _, ok := err.(*frame.ErrNoFDEForPC); ok {
3033 3034
			return
		}
3035
		if _, ok := err.(proc.ErrThreadBlocked); ok {
3036
			return
3037
		}
3038
		if _, ok := err.(*proc.ErrNoSourceForPC); ok {
3039
			return
3040
		}
3041
		if _, ok := err.(proc.ErrProcessExited); ok {
3042 3043
			return
		}
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
		assertNoError(err, t, "Next")
	})
}

func TestStepInstructionNoGoroutine(t *testing.T) {
	protest.AllowRecording(t)
	withTestProcess("increment", t, func(p proc.Process, fixture protest.Fixture) {
		// Call StepInstruction immediately after launching the program, it should
		// work even though no goroutine is selected.
		assertNoError(p.StepInstruction(), t, "StepInstruction")
	})
}
3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067

func TestIssue871(t *testing.T) {
	protest.AllowRecording(t)
	withTestProcess("issue871", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")

		var scope *proc.EvalScope
		var err error
		if testBackend == "rr" {
			var frame proc.Stackframe
			frame, err = findFirstNonRuntimeFrame(p)
			if err == nil {
3068
				scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
			}
		} else {
			scope, err = proc.GoroutineScope(p.CurrentThread())
		}
		assertNoError(err, t, "scope")

		locals, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables")

		foundA, foundB := false, false

		for _, v := range locals {
			t.Logf("local %v", v)
			switch v.Name {
			case "a":
				foundA = true
				if v.Flags&proc.VariableEscaped == 0 {
					t.Errorf("variable a not flagged as escaped")
				}
			case "b":
				foundB = true
			}
		}

		if !foundA {
			t.Errorf("variable a not found")
		}

		if !foundB {
			t.Errorf("variable b not found")
		}
	})
}
A
aarzilli 已提交
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141

func TestShadowedFlag(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
		return
	}
	withTestProcess("testshadow", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope")
		locals, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables")
		foundShadowed := false
		foundNonShadowed := false
		for _, v := range locals {
			if v.Flags&proc.VariableShadowed != 0 {
				if v.Name != "a" {
					t.Errorf("wrong shadowed variable %s", v.Name)
				}
				foundShadowed = true
				if n, _ := constant.Int64Val(v.Value); n != 0 {
					t.Errorf("wrong value for shadowed variable a: %d", n)
				}
			} else {
				if v.Name != "a" {
					t.Errorf("wrong non-shadowed variable %s", v.Name)
				}
				foundNonShadowed = true
				if n, _ := constant.Int64Val(v.Value); n != 1 {
					t.Errorf("wrong value for non-shadowed variable a: %d", n)
				}
			}
		}
		if !foundShadowed {
			t.Error("could not find any shadowed variable")
		}
		if !foundNonShadowed {
			t.Error("could not find any non-shadowed variable")
		}
	})
}
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157

func TestAttachStripped(t *testing.T) {
	if testBackend == "lldb" && runtime.GOOS == "linux" {
		bs, _ := ioutil.ReadFile("/proc/sys/kernel/yama/ptrace_scope")
		if bs == nil || strings.TrimSpace(string(bs)) != "0" {
			t.Logf("can not run TestAttachStripped: %v\n", bs)
			return
		}
	}
	if testBackend == "rr" {
		return
	}
	if runtime.GOOS == "darwin" {
		t.Log("-s does not produce stripped executables on macOS")
		return
	}
3158 3159 3160
	if buildMode != "" {
		t.Skip("not enabled with buildmode=PIE")
	}
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
	fixture := protest.BuildFixture("testnextnethttp", protest.LinkStrip)
	cmd := exec.Command(fixture.Path)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	assertNoError(cmd.Start(), t, "starting fixture")

	// wait for testnextnethttp to start listening
	t0 := time.Now()
	for {
		conn, err := net.Dial("tcp", "localhost:9191")
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(50 * time.Millisecond)
		if time.Since(t0) > 10*time.Second {
			t.Fatal("fixture did not start")
		}
	}

	var p proc.Process
	var err error

	switch testBackend {
	case "native":
3186
		p, err = native.Attach(cmd.Process.Pid, []string{})
3187 3188 3189 3190 3191
	case "lldb":
		path := ""
		if runtime.GOOS == "darwin" {
			path = fixture.Path
		}
3192
		p, err = gdbserial.LLDBAttach(cmd.Process.Pid, path, []string{})
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
	default:
		t.Fatalf("unknown backend %q", testBackend)
	}

	t.Logf("error is %v", err)

	if err == nil {
		p.Detach(true)
		t.Fatalf("expected error after attach, got nothing")
	} else {
		cmd.Process.Kill()
	}
	os.Remove(fixture.Path)
}
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220

func TestIssue844(t *testing.T) {
	// Conditional breakpoints should not prevent next from working if their
	// condition isn't met.
	withTestProcess("nextcond", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 9)
		condbp := setFileBreakpoint(p, t, fixture, 10)
		condbp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "n"},
			Y:  &ast.BasicLit{Kind: token.INT, Value: "11"},
		}
		assertNoError(proc.Continue(p), t, "Continue")
		assertNoError(proc.Next(p), t, "Next")
3221
		assertLineNumber(p, t, 10, "continued to wrong location,")
3222 3223
	})
}
A
aarzilli 已提交
3224

3225
func logStacktrace(t *testing.T, bi *proc.BinaryInfo, frames []proc.Stackframe) {
A
aarzilli 已提交
3226 3227 3228 3229 3230 3231 3232
	for j := range frames {
		name := "?"
		if frames[j].Current.Fn != nil {
			name = frames[j].Current.Fn.Name
		}

		t.Logf("\t%#x %#x %#x %s at %s:%d\n", frames[j].Call.PC, frames[j].FrameOffset(), frames[j].FramePointerOffset(), name, filepath.Base(frames[j].Call.File), frames[j].Call.Line)
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
		if frames[j].TopmostDefer != nil {
			f, l, fn := bi.PCToLine(frames[j].TopmostDefer.DeferredPC)
			fnname := ""
			if fn != nil {
				fnname = fn.Name
			}
			t.Logf("\t\ttopmost defer: %#x %s at %s:%d\n", frames[j].TopmostDefer.DeferredPC, fnname, f, l)
		}
		for deferIdx, _defer := range frames[j].Defers {
			f, l, fn := bi.PCToLine(_defer.DeferredPC)
			fnname := ""
			if fn != nil {
				fnname = fn.Name
			}
			t.Logf("\t\t%d defer: %#x %s at %s:%d\n", deferIdx, _defer.DeferredPC, fnname, f, l)

		}
A
aarzilli 已提交
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
	}
}

// stacktraceCheck checks that all the functions listed in tc appear in
// frames in the same order.
// Checks that all the functions in tc starting with "C." or with "!" are in
// a systemstack frame.
// Returns a slice m where m[i] is the index in frames of the function tc[i]
// or nil if any check fails.
func stacktraceCheck(t *testing.T, tc []string, frames []proc.Stackframe) []int {
	m := make([]int, len(tc))
	i, j := 0, 0
	for i < len(tc) {
		tcname := tc[i]
		tcsystem := strings.HasPrefix(tcname, "C.")
		if tcname[0] == '!' {
			tcsystem = true
			tcname = tcname[1:]
		}
		for j < len(frames) {
			name := "?"
			if frames[j].Current.Fn != nil {
				name = frames[j].Current.Fn.Name
			}
			if name == tcname {
				m[i] = j
				if tcsystem != frames[j].SystemStack {
					t.Logf("system stack check failed for frame %d (expected %v got %v)", j, tcsystem, frames[j].SystemStack)
					t.Logf("expected: %v\n", tc)
					return nil
				}
				break
			}

			j++
		}
		if j >= len(frames) {
			t.Logf("couldn't find frame %d %s", i, tc)
			t.Logf("expected: %v\n", tc)
			return nil
		}

		i++
	}
	return m
}

func frameInFile(frame proc.Stackframe, file string) bool {
	for _, loc := range []proc.Location{frame.Current, frame.Call} {
		if !strings.HasSuffix(loc.File, "/"+file) && !strings.HasSuffix(loc.File, "\\"+file) {
			return false
		}
		if loc.Line <= 0 {
			return false
		}
	}
	return true
}

func TestCgoStacktrace(t *testing.T) {
	if runtime.GOOS == "windows" {
		ver, _ := goversion.Parse(runtime.Version())
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
			t.Skip("disabled on windows with go before version 1.9")
		}
	}
	if runtime.GOOS == "darwin" {
		ver, _ := goversion.Parse(runtime.Version())
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 8, -1, 0, 0, ""}) {
			t.Skip("disabled on macOS with go before version 1.8")
		}
	}

	// Tests that:
	// a) we correctly identify the goroutine while we are executing cgo code
	// b) that we can stitch together the system stack (where cgo code
	// executes) and the normal goroutine stack

	// Each test case describes how the stack trace should appear after a
	// continue. The first function on each test case is the topmost function
	// that should be found on the stack, the actual stack trace can have more
	// frame than those listed here but all the frames listed must appear in
	// the specified order.
	testCases := [][]string{
		[]string{"main.main"},
		[]string{"C.helloworld_pt2", "C.helloworld", "main.main"},
		[]string{"main.helloWorldS", "main.helloWorld", "C.helloworld_pt2", "C.helloworld", "main.main"},
		[]string{"C.helloworld_pt4", "C.helloworld_pt3", "main.helloWorldS", "main.helloWorld", "C.helloworld_pt2", "C.helloworld", "main.main"},
		[]string{"main.helloWorld2", "C.helloworld_pt4", "C.helloworld_pt3", "main.helloWorldS", "main.helloWorld", "C.helloworld_pt2", "C.helloworld", "main.main"}}

	var gid int

	frameOffs := map[string]int64{}
	framePointerOffs := map[string]int64{}

	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
		for itidx, tc := range testCases {
			assertNoError(proc.Continue(p), t, fmt.Sprintf("Continue at iteration step %d", itidx))

			g, err := proc.GetG(p.CurrentThread())
			assertNoError(err, t, fmt.Sprintf("GetG at iteration step %d", itidx))

			if itidx == 0 {
				gid = g.ID
			} else {
				if gid != g.ID {
					t.Fatalf("wrong goroutine id at iteration step %d (expected %d got %d)", itidx, gid, g.ID)
				}
			}

3360
			frames, err := g.Stacktrace(100, false)
A
aarzilli 已提交
3361 3362 3363
			assertNoError(err, t, fmt.Sprintf("Stacktrace at iteration step %d", itidx))

			t.Logf("iteration step %d", itidx)
3364
			logStacktrace(t, p.BinInfo(), frames)
A
aarzilli 已提交
3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400

			m := stacktraceCheck(t, tc, frames)
			mismatch := (m == nil)

			for i, j := range m {
				if strings.HasPrefix(tc[i], "C.hellow") {
					if !frameInFile(frames[j], "hello.c") {
						t.Logf("position in %q is %s:%d (call %s:%d)", tc[i], frames[j].Current.File, frames[j].Current.Line, frames[j].Call.File, frames[j].Call.Line)
						mismatch = true
						break
					}
				}
				if frameOff, ok := frameOffs[tc[i]]; ok {
					if frameOff != frames[j].FrameOffset() {
						t.Logf("frame %s offset mismatch", tc[i])
					}
					if framePointerOffs[tc[i]] != frames[j].FramePointerOffset() {
						t.Logf("frame %s pointer offset mismatch", tc[i])
					}
				} else {
					frameOffs[tc[i]] = frames[j].FrameOffset()
					framePointerOffs[tc[i]] = frames[j].FramePointerOffset()
				}
			}

			// also check that ThreadStacktrace produces the same list of frames
			threadFrames, err := proc.ThreadStacktrace(p.CurrentThread(), 100)
			assertNoError(err, t, fmt.Sprintf("ThreadStacktrace at iteration step %d", itidx))

			if len(threadFrames) != len(frames) {
				mismatch = true
			} else {
				for j := range frames {
					if frames[j].Current.File != threadFrames[j].Current.File || frames[j].Current.Line != threadFrames[j].Current.Line {
						t.Logf("stack mismatch between goroutine stacktrace and thread stacktrace")
						t.Logf("thread stacktrace:")
3401
						logStacktrace(t, p.BinInfo(), threadFrames)
A
aarzilli 已提交
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
						mismatch = true
						break
					}
				}
			}
			if mismatch {
				t.Fatal("see previous loglines")
			}
		}
	})
}

func TestCgoSources(t *testing.T) {
	if runtime.GOOS == "windows" {
		ver, _ := goversion.Parse(runtime.Version())
		if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
			t.Skip("disabled on windows with go before version 1.9")
		}
	}

	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
		sources := p.BinInfo().Sources
		for _, needle := range []string{"main.go", "hello.c"} {
			found := false
			for _, k := range sources {
				if strings.HasSuffix(k, "/"+needle) || strings.HasSuffix(k, "\\"+needle) {
					found = true
					break
				}
			}
			if !found {
				t.Errorf("File %s not found", needle)
			}
		}
	})
}

func TestSystemstackStacktrace(t *testing.T) {
	// check that we can follow a stack switch initiated by runtime.systemstack()
	withTestProcess("panic", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "runtime.startpanic_m")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "first continue")
		assertNoError(proc.Continue(p), t, "second continue")
		g, err := proc.GetG(p.CurrentThread())
		assertNoError(err, t, "GetG")
3448
		frames, err := g.Stacktrace(100, false)
A
aarzilli 已提交
3449
		assertNoError(err, t, "stacktrace")
3450
		logStacktrace(t, p.BinInfo(), frames)
3451
		m := stacktraceCheck(t, []string{"!runtime.startpanic_m", "runtime.gopanic", "main.main"}, frames)
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
		if m == nil {
			t.Fatal("see previous loglines")
		}
	})
}

func TestSystemstackOnRuntimeNewstack(t *testing.T) {
	// The bug being tested here manifests as follows:
	// - set a breakpoint somewhere or interrupt the program with Ctrl-C
	// - try to look at stacktraces of other goroutines
	// If one of the other goroutines is resizing its own stack the stack
	// command won't work for it.
	withTestProcess("binarytrees", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint(main.main)")
		assertNoError(proc.Continue(p), t, "first continue")
3468

3469 3470
		g, err := proc.GetG(p.CurrentThread())
		assertNoError(err, t, "GetG")
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482
		mainGoroutineID := g.ID

		_, err = setFunctionBreakpoint(p, "runtime.newstack")
		assertNoError(err, t, "setFunctionBreakpoint(runtime.newstack)")
		for {
			assertNoError(proc.Continue(p), t, "second continue")
			g, err = proc.GetG(p.CurrentThread())
			assertNoError(err, t, "GetG")
			if g.ID == mainGoroutineID {
				break
			}
		}
3483
		frames, err := g.Stacktrace(100, false)
3484
		assertNoError(err, t, "stacktrace")
3485
		logStacktrace(t, p.BinInfo(), frames)
3486
		m := stacktraceCheck(t, []string{"!runtime.newstack", "main.main"}, frames)
A
aarzilli 已提交
3487 3488 3489 3490 3491
		if m == nil {
			t.Fatal("see previous loglines")
		}
	})
}
3492 3493 3494 3495 3496 3497 3498 3499

func TestIssue1034(t *testing.T) {
	// The external linker on macOS produces an abbrev for DW_TAG_subprogram
	// without the "has children" flag, we should support this.
	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
3500
		frames, err := p.SelectedGoroutine().Stacktrace(10, false)
3501
		assertNoError(err, t, "Stacktrace")
3502
		scope := proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frames[2:]...)
3503 3504 3505 3506 3507 3508 3509
		args, _ := scope.FunctionArguments(normalLoadConfig)
		assertNoError(err, t, "FunctionArguments()")
		if len(args) > 0 {
			t.Fatalf("wrong number of arguments for frame %v (%d)", frames[2], len(args))
		}
	})
}
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528

func TestIssue1008(t *testing.T) {
	// The external linker on macOS inserts "end of sequence" extended opcodes
	// in debug_line. which we should support correctly.
	withTestProcess("cgostacktest/", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.main")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
		loc, err := p.CurrentThread().Location()
		assertNoError(err, t, "CurrentThread().Location()")
		t.Logf("location %v\n", loc)
		if !strings.HasSuffix(loc.File, "/main.go") {
			t.Errorf("unexpected location %s:%d\n", loc.File, loc.Line)
		}
		if loc.Line > 31 {
			t.Errorf("unexpected location %s:%d (file only has 30 lines)\n", loc.File, loc.Line)
		}
	})
}
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556

func TestDeclLine(t *testing.T) {
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major > 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		t.Skip("go 1.9 and prior versions do not emit DW_AT_decl_line")
	}

	withTestProcess("decllinetest", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope (1)")
		vars, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables (1)")
		if len(vars) != 1 {
			t.Fatalf("wrong number of variables %d", len(vars))
		}

		assertNoError(proc.Continue(p), t, "Continue")
		scope, err = proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope (2)")
		scope.LocalVariables(normalLoadConfig)
		vars, err = scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables (2)")
		if len(vars) != 2 {
			t.Fatalf("wrong number of variables %d", len(vars))
		}
	})
}
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566

func TestIssue1137(t *testing.T) {
	withTestProcess("dotpackagesiface", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		v := evalVariable(p, t, "iface")
		assertNoError(v.Unreadable, t, "iface unreadable")
		v2 := evalVariable(p, t, "iface2")
		assertNoError(v2.Unreadable, t, "iface2 unreadable")
	})
}
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596

func TestIssue1101(t *testing.T) {
	// If a breakpoint is hit close to process death on a thread that isn't the
	// group leader the process could die while we are trying to stop it.
	//
	// This can be easily reproduced by having the goroutine that's executing
	// main.main (which will almost always run on the thread group leader) wait
	// for a second goroutine before exiting, then setting a breakpoint on the
	// second goroutine and stepping through it (see TestIssue1101 in
	// proc_test.go).
	//
	// When stepping over the return instruction of main.f the deferred
	// wg.Done() call will be executed which will cause the main goroutine to
	// resume and proceed to exit. Both the temporary breakpoint on wg.Done and
	// the temporary breakpoint on the return address of main.f will be in
	// close proximity to main.main calling os.Exit() and causing the death of
	// the thread group leader.

	withTestProcess("issue1101", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.f")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next() 1")
		assertNoError(proc.Next(p), t, "Next() 2")
		lastCmd := "Next() 3"
		exitErr := proc.Next(p)
		if exitErr == nil {
			lastCmd = "final Continue()"
			exitErr = proc.Continue(p)
		}
3597
		if pexit, exited := exitErr.(proc.ErrProcessExited); exited {
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
			if pexit.Status != 2 && testBackend != "lldb" {
				// looks like there's a bug with debugserver on macOS that sometimes
				// will report exit status 0 instead of the proper exit status.
				t.Fatalf("process exited status %d (expected 2)", pexit.Status)
			}
		} else {
			assertNoError(exitErr, t, lastCmd)
			t.Fatalf("process did not exit after %s", lastCmd)
		}
	})
}
3609 3610

func TestIssue1145(t *testing.T) {
3611 3612
	withTestProcess("sleep", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 18)
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
		assertNoError(proc.Continue(p), t, "Continue()")
		resumeChan := make(chan struct{}, 1)
		p.ResumeNotify(resumeChan)
		go func() {
			<-resumeChan
			time.Sleep(100 * time.Millisecond)
			p.RequestManualStop()
		}()

		assertNoError(proc.Next(p), t, "Next()")
		if p.Breakpoints().HasInternalBreakpoints() {
			t.Fatal("has internal breakpoints after manual stop request")
		}
	})
}
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645

func TestDisassembleGlobalVars(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		mainfn := p.BinInfo().LookupFunc["main.main"]
		text, err := proc.Disassemble(p, nil, mainfn.Entry, mainfn.End)
		assertNoError(err, t, "Disassemble")
		found := false
		for i := range text {
			if strings.Index(text[i].Text(proc.IntelFlavour, p.BinInfo()), "main.v") > 0 {
				found = true
				break
			}
		}
		if !found {
			t.Fatalf("could not find main.v reference in disassembly")
		}
	})
}
A
aarzilli 已提交
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663

func checkFrame(frame proc.Stackframe, fnname, file string, line int, inlined bool) error {
	if frame.Call.Fn == nil || frame.Call.Fn.Name != fnname {
		return fmt.Errorf("wrong function name: %s", fnname)
	}
	if frame.Call.File != file || frame.Call.Line != line {
		return fmt.Errorf("wrong file:line %s:%d", frame.Call.File, frame.Call.Line)
	}
	if frame.Inlined != inlined {
		if inlined {
			return fmt.Errorf("not inlined")
		} else {
			return fmt.Errorf("inlined")
		}
	}
	return nil
}

3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684
func TestAllPCsForFileLines(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining, func(p proc.Process, fixture protest.Fixture) {
		l2pcs := p.BinInfo().AllPCsForFileLines(fixture.Source, []int{7, 20})
		if len(l2pcs) != 2 {
			t.Fatalf("expected two map entries for %s:{%d,%d} (got %d: %v)", fixture.Source, 7, 20, len(l2pcs), l2pcs)
		}
		pcs := l2pcs[20]
		if len(pcs) < 1 {
			t.Fatalf("expected at least one location for %s:%d (got %d: %#x)", fixture.Source, 20, len(pcs), pcs)
		}
		pcs = l2pcs[7]
		if len(pcs) < 2 {
			t.Fatalf("expected at least two locations for %s:%d (got %d: %#x)", fixture.Source, 7, len(pcs), pcs)
		}
	})
}

A
aarzilli 已提交
3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735
func TestInlinedStacktraceAndVariables(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}

	firstCallCheck := &scopeCheck{
		line: 7,
		ok:   false,
		varChecks: []varCheck{
			varCheck{
				name:   "a",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 3,
			},
			varCheck{
				name:   "z",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 9,
			},
		},
	}

	secondCallCheck := &scopeCheck{
		line: 7,
		ok:   false,
		varChecks: []varCheck{
			varCheck{
				name:   "a",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 4,
			},
			varCheck{
				name:   "z",
				typ:    "int",
				kind:   reflect.Int,
				hasVal: true,
				intVal: 16,
			},
		},
	}

	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining, func(p proc.Process, fixture protest.Fixture) {
		pcs := p.BinInfo().AllPCsForFileLine(fixture.Source, 7)
		if len(pcs) < 2 {
3736
			t.Fatalf("expected at least two locations for %s:%d (got %d: %#x)", fixture.Source, 7, len(pcs), pcs)
A
aarzilli 已提交
3737 3738
		}
		for _, pc := range pcs {
3739
			t.Logf("setting breakpoint at %#x\n", pc)
A
aarzilli 已提交
3740 3741 3742 3743 3744 3745 3746 3747 3748 3749
			_, err := p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
			assertNoError(err, t, fmt.Sprintf("SetBreakpoint(%#x)", pc))
		}

		// first inlined call
		assertNoError(proc.Continue(p), t, "Continue")
		frames, err := proc.ThreadStacktrace(p.CurrentThread(), 20)
		assertNoError(err, t, "ThreadStacktrace")
		t.Logf("Stacktrace:\n")
		for i := range frames {
3750
			t.Logf("\t%s at %s:%d (%#x)\n", frames[i].Call.Fn.Name, frames[i].Call.File, frames[i].Call.Line, frames[i].Current.PC)
A
aarzilli 已提交
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
		}

		if err := checkFrame(frames[0], "main.inlineThis", fixture.Source, 7, true); err != nil {
			t.Fatalf("Wrong frame 0: %v", err)
		}
		if err := checkFrame(frames[1], "main.main", fixture.Source, 18, false); err != nil {
			t.Fatalf("Wrong frame 1: %v", err)
		}

		if avar, _ := constant.Int64Val(evalVariable(p, t, "a").Value); avar != 3 {
			t.Fatalf("value of 'a' variable is not 3 (%d)", avar)
		}
		if zvar, _ := constant.Int64Val(evalVariable(p, t, "z").Value); zvar != 9 {
			t.Fatalf("value of 'z' variable is not 9 (%d)", zvar)
		}

		if _, ok := firstCallCheck.checkLocalsAndArgs(p, t); !ok {
			t.Fatalf("exiting for past errors")
		}

		// second inlined call
		assertNoError(proc.Continue(p), t, "Continue")
		frames, err = proc.ThreadStacktrace(p.CurrentThread(), 20)
		assertNoError(err, t, "ThreadStacktrace (2)")
		t.Logf("Stacktrace 2:\n")
		for i := range frames {
3777
			t.Logf("\t%s at %s:%d (%#x)\n", frames[i].Call.Fn.Name, frames[i].Call.File, frames[i].Call.Line, frames[i].Current.PC)
A
aarzilli 已提交
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
		}

		if err := checkFrame(frames[0], "main.inlineThis", fixture.Source, 7, true); err != nil {
			t.Fatalf("Wrong frame 0: %v", err)
		}
		if err := checkFrame(frames[1], "main.main", fixture.Source, 19, false); err != nil {
			t.Fatalf("Wrong frame 1: %v", err)
		}

		if avar, _ := constant.Int64Val(evalVariable(p, t, "a").Value); avar != 4 {
			t.Fatalf("value of 'a' variable is not 3 (%d)", avar)
		}
		if zvar, _ := constant.Int64Val(evalVariable(p, t, "z").Value); zvar != 16 {
			t.Fatalf("value of 'z' variable is not 9 (%d)", zvar)
		}
		if bvar, err := evalVariableOrError(p, "b"); err == nil {
			t.Fatalf("expected error evaluating 'b', but it succeeded instead: %v", bvar)
		}

		if _, ok := secondCallCheck.checkLocalsAndArgs(p, t); !ok {
			t.Fatalf("exiting for past errors")
		}
	})
}

func TestInlineStep(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contStep, 6},
		{contStep, 7},
		{contStep, 18},
		{contStep, 19},
	})
}

func TestInlineNext(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contStep, 6},
		{contNext, 7},
		{contNext, 18},
		{contNext, 19},
	})
}

func TestInlineStepOver(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contNext, 19},
		{contNext, 20},
	})
}

func TestInlineStepOut(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	testseq2Args(".", []string{}, protest.EnableInlining, t, "testinline", "", []seqTest{
		{contContinue, 18},
		{contStep, 6},
		{contStepout, 18},
	})
}
3854

3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896
func TestInlineFunctionList(t *testing.T) {
	// We should be able to list all functions, even inlined ones.
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining|protest.EnableOptimization, func(p proc.Process, fixture protest.Fixture) {
		var found bool
		for _, fn := range p.BinInfo().Functions {
			if strings.Contains(fn.Name, "inlineThis") {
				found = true
				break
			}
		}
		if !found {
			t.Fatal("inline function not returned")
		}
	})
}

func TestInlineBreakpoint(t *testing.T) {
	// We should be able to set a breakpoint on the call site of an inlined function.
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		// Versions of go before 1.10 do not have DWARF information for inlined calls
		t.Skip("inlining not supported")
	}
	withTestProcessArgs("testinline", t, ".", []string{}, protest.EnableInlining|protest.EnableOptimization, func(p proc.Process, fixture protest.Fixture) {
		pc, fn, err := p.BinInfo().LineToPC(fixture.Source, 17)
		if pc == 0 {
			t.Fatal("unable to get PC for inlined function call")
		}
		expectedFn := "main.main"
		if fn.Name != expectedFn {
			t.Fatalf("incorrect function returned, expected %s, got %s", expectedFn, fn.Name)
		}
		_, err = p.SetBreakpoint(pc, proc.UserBreakpoint, nil)
		if err != nil {
			t.Fatalf("unable to set breakpoint: %v", err)
		}
	})
}

3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
func TestIssue951(t *testing.T) {
	if ver, _ := goversion.Parse(runtime.Version()); ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {
		t.Skip("scopes not implemented in <=go1.8")
	}

	withTestProcess("issue951", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope")
		args, err := scope.FunctionArguments(normalLoadConfig)
		assertNoError(err, t, "FunctionArguments")
		t.Logf("%#v", args[0])
		if args[0].Flags&proc.VariableShadowed == 0 {
			t.Error("argument is not shadowed")
		}
		vars, err := scope.LocalVariables(normalLoadConfig)
		assertNoError(err, t, "LocalVariables")
		shadowed, notShadowed := 0, 0
		for i := range vars {
			t.Logf("var %d: %#v\n", i, vars[i])
			if vars[i].Flags&proc.VariableShadowed != 0 {
				shadowed++
			} else {
				notShadowed++
			}
		}
		if shadowed != 1 || notShadowed != 1 {
			t.Errorf("Wrong number of shadowed/non-shadowed local variables: %d %d", shadowed, notShadowed)
		}
	})
}
3928

3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944
func TestDWZCompression(t *testing.T) {
	// If dwz is not available in the system, skip this test
	if _, err := exec.LookPath("dwz"); err != nil {
		t.Skip("dwz not installed")
	}

	withTestProcessArgs("dwzcompression", t, ".", []string{}, protest.EnableDWZCompression, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "C.fortytwo")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "first Continue()")
		val := evalVariable(p, t, "stdin")
		if val.RealType == nil {
			t.Errorf("Can't find type for \"stdin\" global variable")
		}
	})
}
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969

func TestMapLoadConfigWithReslice(t *testing.T) {
	// Check that load configuration is respected for resliced maps.
	withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {
		zolotovLoadCfg := proc.LoadConfig{FollowPointers: true, MaxStructFields: -1, MaxVariableRecurse: 3, MaxStringLen: 10, MaxArrayValues: 10}
		assertNoError(proc.Continue(p), t, "First Continue()")
		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope")
		m1, err := scope.EvalExpression("m1", zolotovLoadCfg)
		assertNoError(err, t, "EvalVariable")
		t.Logf("m1 returned children %d (%d)", len(m1.Children)/2, m1.Len)

		expr := fmt.Sprintf("(*(*%q)(%d))[10:]", m1.DwarfType.String(), m1.Addr)
		t.Logf("expr %q\n", expr)

		m1cont, err := scope.EvalExpression(expr, zolotovLoadCfg)
		assertNoError(err, t, "EvalVariable")

		t.Logf("m1cont returned children %d", len(m1cont.Children)/2)

		if len(m1cont.Children) != 20 {
			t.Fatalf("wrong number of children returned %d\n", len(m1cont.Children)/2)
		}
	})
}
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985

func TestStepOutReturn(t *testing.T) {
	ver, _ := goversion.Parse(runtime.Version())
	if ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 10, -1, 0, 0, ""}) {
		t.Skip("return variables aren't marked on 1.9 or earlier")
	}
	withTestProcess("stepoutret", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.stepout")
		assertNoError(err, t, "SetBreakpoint")
		assertNoError(proc.Continue(p), t, "Continue")
		assertNoError(proc.StepOut(p), t, "StepOut")
		ret := p.CurrentThread().Common().ReturnValues(normalLoadConfig)
		if len(ret) != 2 {
			t.Fatalf("wrong number of return values %v", ret)
		}

3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003
		stridx := 0
		numidx := 1

		if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 12) {
			// in 1.11 and earlier the order of return values in DWARF is
			// unspecified, in 1.11 and later it follows the order of definition
			// specified by the user
			for i := range ret {
				if ret[i].Name == "str" {
					stridx = i
					numidx = 1 - i
					break
				}
			}
		}

		if ret[stridx].Name != "str" {
			t.Fatalf("(str) bad return value name %s", ret[stridx].Name)
4004
		}
4005 4006
		if ret[stridx].Kind != reflect.String {
			t.Fatalf("(str) bad return value kind %v", ret[stridx].Kind)
4007
		}
4008
		if s := constant.StringVal(ret[stridx].Value); s != "return 47" {
4009 4010 4011
			t.Fatalf("(str) bad return value %q", s)
		}

4012 4013
		if ret[numidx].Name != "num" {
			t.Fatalf("(num) bad return value name %s", ret[numidx].Name)
4014
		}
4015 4016
		if ret[numidx].Kind != reflect.Int {
			t.Fatalf("(num) bad return value kind %v", ret[numidx].Kind)
4017
		}
4018
		if n, _ := constant.Int64Val(ret[numidx].Value); n != 48 {
4019 4020 4021 4022
			t.Fatalf("(num) bad return value %d", n)
		}
	})
}
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040

func TestOptimizationCheck(t *testing.T) {
	withTestProcess("continuetestprog", t, func(p proc.Process, fixture protest.Fixture) {
		fn := p.BinInfo().LookupFunc["main.main"]
		if fn.Optimized() {
			t.Fatalf("main.main is optimized")
		}
	})

	if goversion.VersionAfterOrEqual(runtime.Version(), 1, 10) {
		withTestProcessArgs("continuetestprog", t, ".", []string{}, protest.EnableOptimization|protest.EnableInlining, func(p proc.Process, fixture protest.Fixture) {
			fn := p.BinInfo().LookupFunc["main.main"]
			if !fn.Optimized() {
				t.Fatalf("main.main is not optimized")
			}
		})
	}
}
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051

func TestIssue1264(t *testing.T) {
	// It should be possible to set a breakpoint condition that consists only
	// of evaluating a single boolean variable.
	withTestProcess("issue1264", t, func(p proc.Process, fixture protest.Fixture) {
		bp := setFileBreakpoint(p, t, fixture, 8)
		bp.Cond = &ast.Ident{Name: "equalsTwo"}
		assertNoError(proc.Continue(p), t, "Continue()")
		assertLineNumber(p, t, 8, "after continue")
	})
}
4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110

func TestReadDefer(t *testing.T) {
	withTestProcess("deferstack", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		frames, err := p.SelectedGoroutine().Stacktrace(10, true)
		assertNoError(err, t, "Stacktrace")

		logStacktrace(t, p.BinInfo(), frames)

		examples := []struct {
			frameIdx     int
			topmostDefer string
			defers       []string
		}{
			// main.call3 (defers nothing, topmost defer main.f2)
			{0, "main.f2", []string{}},

			// main.call2 (defers main.f2, main.f3, topmost defer main.f2)
			{1, "main.f2", []string{"main.f2", "main.f3"}},

			// main.call1 (defers main.f1, main.f2, topmost defer main.f1)
			{2, "main.f1", []string{"main.f1", "main.f2"}},

			// main.main (defers nothing)
			{3, "", []string{}}}

		defercheck := func(d *proc.Defer, deferName, tgt string, frameIdx int) {
			if d == nil {
				t.Fatalf("expected %q as %s of frame %d, got nothing", tgt, deferName, frameIdx)
			}
			if d.Unreadable != nil {
				t.Fatalf("expected %q as %s of frame %d, got unreadable defer: %v", tgt, deferName, frameIdx, d.Unreadable)
			}
			_, _, dfn := p.BinInfo().PCToLine(d.DeferredPC)
			if dfn == nil {
				t.Fatalf("expected %q as %s of frame %d, got %#x", tgt, deferName, frameIdx, d.DeferredPC)
			}
			if dfn.Name != tgt {
				t.Fatalf("expected %q as %s of frame %d, got %q", tgt, deferName, frameIdx, dfn.Name)
			}
		}

		for _, example := range examples {
			frame := &frames[example.frameIdx]

			if example.topmostDefer != "" {
				defercheck(frame.TopmostDefer, "topmost defer", example.topmostDefer, example.frameIdx)
			}

			if len(example.defers) != len(frames[example.frameIdx].Defers) {
				t.Fatalf("expected %d defers for %d, got %v", len(example.defers), example.frameIdx, frame.Defers)
			}

			for deferIdx := range example.defers {
				defercheck(frame.Defers[deferIdx], fmt.Sprintf("defer %d", deferIdx), example.defers[deferIdx], example.frameIdx)
			}
		}
	})
}
A
aarzilli 已提交
4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122

func TestNextUnknownInstr(t *testing.T) {
	if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 10) {
		t.Skip("versions of Go before 1.10 can't assemble the instruction VPUNPCKLWD")
	}
	withTestProcess("nodisasm/", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.asmFunc")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
		assertNoError(proc.Next(p), t, "Next()")
	})
}
4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165

func TestReadDeferArgs(t *testing.T) {
	var tests = []struct {
		frame, deferCall int
		a, b             int64
	}{
		{1, 1, 42, 61},
		{2, 2, 1, -1},
	}

	withTestProcess("deferstack", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")

		for _, test := range tests {
			scope, err := proc.ConvertEvalScope(p, -1, test.frame, test.deferCall)
			assertNoError(err, t, fmt.Sprintf("ConvertEvalScope(-1, %d, %d)", test.frame, test.deferCall))

			if scope.Fn.Name != "main.f2" {
				t.Fatalf("expected function \"main.f2\" got %q", scope.Fn.Name)
			}

			avar, err := scope.EvalVariable("a", normalLoadConfig)
			if err != nil {
				t.Fatal(err)
			}
			bvar, err := scope.EvalVariable("b", normalLoadConfig)
			if err != nil {
				t.Fatal(err)
			}

			a, _ := constant.Int64Val(avar.Value)
			b, _ := constant.Int64Val(bvar.Value)

			if a != test.a {
				t.Errorf("value of argument 'a' at frame %d, deferred call %d: %d (expected %d)", test.frame, test.deferCall, a, test.a)
			}

			if b != test.b {
				t.Errorf("value of argument 'b' at frame %d, deferred call %d: %d (expected %d)", test.frame, test.deferCall, b, test.b)
			}
		}
	})
}
4166 4167 4168 4169 4170 4171 4172 4173

func TestIssue1374(t *testing.T) {
	// Continue did not work when stopped at a breakpoint immediately after calling CallFunction.
	protest.MustSupportFunctionCalls(t, testBackend)
	withTestProcess("issue1374", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 7)
		assertNoError(proc.Continue(p), t, "First Continue")
		assertLineNumber(p, t, 7, "Did not continue to correct location (first continue),")
4174
		assertNoError(proc.EvalExpressionWithCalls(p, p.SelectedGoroutine(), "getNum()", normalLoadConfig, true), t, "Call")
4175 4176 4177 4178 4179 4180 4181 4182
		err := proc.Continue(p)
		if _, isexited := err.(proc.ErrProcessExited); !isexited {
			regs, _ := p.CurrentThread().Registers(false)
			f, l, _ := p.BinInfo().PCToLine(regs.PC())
			t.Fatalf("expected process exited error got %v at %s:%d", err, f, l)
		}
	})
}
4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200

func TestIssue1432(t *testing.T) {
	// Check that taking the address of a struct, casting it into a pointer to
	// the struct's type and then accessing a member field will still:
	// - perform auto-dereferencing on struct member access
	// - yield a Variable that's ultimately assignable (i.e. has an address)
	withTestProcess("issue1432", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		svar := evalVariable(p, t, "s")
		t.Logf("%#x", svar.Addr)

		scope, err := proc.GoroutineScope(p.CurrentThread())
		assertNoError(err, t, "GoroutineScope()")

		err = scope.SetVariable(fmt.Sprintf("(*\"main.s\")(%#x).i", svar.Addr), "10")
		assertNoError(err, t, "SetVariable")
	})
}
A
aarzilli 已提交
4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229

func TestGoroutinesInfoLimit(t *testing.T) {
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 37)
		assertNoError(proc.Continue(p), t, "Continue()")

		gcount := 0
		nextg := 0
		const goroutinesInfoLimit = 10
		for nextg >= 0 {
			oldnextg := nextg
			var gs []*proc.G
			var err error
			gs, nextg, err = proc.GoroutinesInfo(p, nextg, goroutinesInfoLimit)
			assertNoError(err, t, fmt.Sprintf("GoroutinesInfo(%d, %d)", oldnextg, goroutinesInfoLimit))
			gcount += len(gs)
			t.Logf("got %d goroutines\n", len(gs))
		}

		t.Logf("number of goroutines: %d\n", gcount)

		gs, _, err := proc.GoroutinesInfo(p, 0, 0)
		assertNoError(err, t, "GoroutinesInfo(0, 0)")
		t.Logf("number of goroutines (full scan): %d\n", gcount)
		if len(gs) != gcount {
			t.Fatalf("mismatch in the number of goroutines %d %d\n", gcount, len(gs))
		}
	})
}
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261

func TestIssue1469(t *testing.T) {
	withTestProcess("issue1469", t, func(p proc.Process, fixture protest.Fixture) {
		setFileBreakpoint(p, t, fixture, 13)
		assertNoError(proc.Continue(p), t, "Continue()")

		gid2thread := make(map[int][]proc.Thread)
		for _, thread := range p.ThreadList() {
			g, _ := proc.GetG(thread)
			if g == nil {
				continue
			}
			gid2thread[g.ID] = append(gid2thread[g.ID], thread)
		}

		for gid := range gid2thread {
			if len(gid2thread[gid]) > 1 {
				t.Logf("too many threads running goroutine %d", gid)
				for _, thread := range gid2thread[gid] {
					t.Logf("\tThread %d", thread.ThreadID())
					frames, err := proc.ThreadStacktrace(thread, 20)
					if err != nil {
						t.Logf("\t\tcould not get stacktrace %v", err)
					}
					for _, frame := range frames {
						t.Logf("\t\t%#x at %s:%d (systemstack: %v)", frame.Call.PC, frame.Call.File, frame.Call.Line, frame.SystemStack)
					}
				}
			}
		}
	})
}
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279

func TestDeadlockBreakpoint(t *testing.T) {
	if buildMode == "pie" {
		t.Skip("See https://github.com/golang/go/issues/29322")
	}
	deadlockBp := proc.FatalThrow
	if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		deadlockBp = proc.UnrecoveredPanic
	}
	withTestProcess("testdeadlock", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue()")

		bp := p.CurrentThread().Breakpoint()
		if bp.Breakpoint == nil || bp.Name != deadlockBp {
			t.Fatalf("did not stop at deadlock breakpoint %v", bp)
		}
	})
}
4280 4281

func TestListImages(t *testing.T) {
A
Alessandro Arzilli 已提交
4282
	pluginFixtures := protest.WithPlugins(t, protest.AllNonOptimized, "plugin1/", "plugin2/")
4283

A
Alessandro Arzilli 已提交
4284
	withTestProcessArgs("plugintest", t, ".", []string{pluginFixtures[0].Path, pluginFixtures[1].Path}, protest.AllNonOptimized, func(p proc.Process, fixture protest.Fixture) {
4285
		assertNoError(proc.Continue(p), t, "first continue")
4286
		f, l := currentLineNumber(p, t)
4287
		plugin1Found := false
4288
		t.Logf("Libraries before %s:%d:", f, l)
4289
		for _, image := range p.BinInfo().Images {
4290
			t.Logf("\t%#x %q err:%v", image.StaticBase, image.Path, image.LoadError())
4291 4292 4293 4294 4295 4296 4297 4298
			if image.Path == pluginFixtures[0].Path {
				plugin1Found = true
			}
		}
		if !plugin1Found {
			t.Fatalf("Could not find plugin1")
		}
		assertNoError(proc.Continue(p), t, "second continue")
4299
		f, l = currentLineNumber(p, t)
4300
		plugin1Found, plugin2Found := false, false
4301
		t.Logf("Libraries after %s:%d:", f, l)
4302
		for _, image := range p.BinInfo().Images {
4303
			t.Logf("\t%#x %q err:%v", image.StaticBase, image.Path, image.LoadError())
4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318
			switch image.Path {
			case pluginFixtures[0].Path:
				plugin1Found = true
			case pluginFixtures[1].Path:
				plugin2Found = true
			}
		}
		if !plugin1Found {
			t.Fatalf("Could not find plugin1")
		}
		if !plugin2Found {
			t.Fatalf("Could not find plugin2")
		}
	})
}
4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330

func TestAncestors(t *testing.T) {
	if !goversion.VersionAfterOrEqual(runtime.Version(), 1, 11) {
		t.Skip("not supported on Go <= 1.10")
	}
	savedGodebug := os.Getenv("GODEBUG")
	os.Setenv("GODEBUG", "tracebackancestors=100")
	defer os.Setenv("GODEBUG", savedGodebug)
	withTestProcess("testnextprog", t, func(p proc.Process, fixture protest.Fixture) {
		_, err := setFunctionBreakpoint(p, "main.testgoroutine")
		assertNoError(err, t, "setFunctionBreakpoint()")
		assertNoError(proc.Continue(p), t, "Continue()")
4331
		as, err := proc.Ancestors(p, p.SelectedGoroutine(), 1000)
4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353
		assertNoError(err, t, "Ancestors")
		t.Logf("ancestors: %#v\n", as)
		if len(as) != 1 {
			t.Fatalf("expected only one ancestor got %d", len(as))
		}
		mainFound := false
		for i, a := range as {
			astack, err := a.Stack(100)
			assertNoError(err, t, fmt.Sprintf("Ancestor %d stack", i))
			t.Logf("ancestor %d\n", i)
			logStacktrace(t, p.BinInfo(), astack)
			for _, frame := range astack {
				if frame.Current.Fn != nil && frame.Current.Fn.Name == "main.main" {
					mainFound = true
				}
			}
		}
		if !mainFound {
			t.Fatal("could not find main.main function in ancestors")
		}
	})
}
4354

4355 4356
func testCallConcurrentCheckReturns(p proc.Process, t *testing.T, gid1, gid2 int) int {
	found := 0
4357 4358
	for _, thread := range p.ThreadList() {
		g, _ := proc.GetG(thread)
4359
		if g == nil || (g.ID != gid1 && g.ID != gid2) {
4360 4361 4362
			continue
		}
		retvals := thread.Common().ReturnValues(normalLoadConfig)
4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378
		if len(retvals) == 0 {
			continue
		}
		n, _ := constant.Int64Val(retvals[0].Value)
		t.Logf("injection on goroutine %d (thread %d) returned %v\n", g.ID, thread.ThreadID(), n)
		switch g.ID {
		case gid1:
			if n != 11 {
				t.Errorf("wrong return value for goroutine %d", g.ID)
			}
			found++
		case gid2:
			if n != 12 {
				t.Errorf("wrong return value for goroutine %d", g.ID)
			}
			found++
4379 4380
		}
	}
4381
	return found
4382 4383 4384
}

func TestCallConcurrent(t *testing.T) {
4385 4386 4387
	if runtime.GOOS == "freebsd" {
		t.Skip("test is not valid on FreeBSD")
	}
4388 4389 4390 4391
	protest.MustSupportFunctionCalls(t, testBackend)
	withTestProcess("teststepconcurrent", t, func(p proc.Process, fixture protest.Fixture) {
		bp := setFileBreakpoint(p, t, fixture, 24)
		assertNoError(proc.Continue(p), t, "Continue()")
4392 4393
		//_, err := p.ClearBreakpoint(bp.Addr)
		//assertNoError(err, t, "ClearBreakpoint() returned an error")
4394 4395 4396

		gid1 := p.SelectedGoroutine().ID
		t.Logf("starting injection in %d / %d", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
4397
		assertNoError(proc.EvalExpressionWithCalls(p, p.SelectedGoroutine(), "Foo(10, 1)", normalLoadConfig, false), t, "EvalExpressionWithCalls()")
4398

4399
		returned := testCallConcurrentCheckReturns(p, t, gid1, -1)
4400 4401

		curthread := p.CurrentThread()
4402 4403
		if curbp := curthread.Breakpoint(); curbp.Breakpoint == nil || curbp.ID != bp.ID || returned > 0 {
			t.Logf("skipping test, the call injection terminated before we hit a breakpoint in a different thread")
4404 4405 4406
			return
		}

4407 4408 4409 4410 4411 4412 4413
		_, err := p.ClearBreakpoint(bp.Addr)
		assertNoError(err, t, "ClearBreakpoint() returned an error")

		gid2 := p.SelectedGoroutine().ID
		t.Logf("starting second injection in %d / %d", p.SelectedGoroutine().ID, p.CurrentThread().ThreadID())
		assertNoError(proc.EvalExpressionWithCalls(p, p.SelectedGoroutine(), "Foo(10, 2)", normalLoadConfig, false), t, "EvalExpressioniWithCalls")

4414
		for {
4415 4416
			returned += testCallConcurrentCheckReturns(p, t, gid1, gid2)
			if returned >= 2 {
4417 4418
				break
			}
4419
			t.Logf("Continuing... %d", returned)
4420 4421 4422 4423 4424 4425
			assertNoError(proc.Continue(p), t, "Continue()")
		}

		proc.Continue(p)
	})
}
4426 4427

func TestPluginStepping(t *testing.T) {
A
Alessandro Arzilli 已提交
4428
	pluginFixtures := protest.WithPlugins(t, protest.AllNonOptimized, "plugin1/", "plugin2/")
4429

A
Alessandro Arzilli 已提交
4430
	testseq2Args(".", []string{pluginFixtures[0].Path, pluginFixtures[1].Path}, protest.AllNonOptimized, t, "plugintest2", "", []seqTest{
4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442
		{contContinue, 41},
		{contStep, "plugin1.go:9"},
		{contStep, "plugin1.go:10"},
		{contStep, "plugin1.go:11"},
		{contNext, "plugin1.go:12"},
		{contNext, "plugintest2.go:41"},
		{contNext, "plugintest2.go:42"},
		{contStep, "plugin2.go:22"},
		{contNext, "plugin2.go:23"},
		{contNext, "plugin2.go:26"},
		{contNext, "plugintest2.go:42"}})
}
4443 4444 4445 4446 4447 4448 4449 4450

func TestIssue1601(t *testing.T) {
	//Tests that recursive types involving C qualifiers and typedefs are parsed correctly
	withTestProcess("issue1601", t, func(p proc.Process, fixture protest.Fixture) {
		assertNoError(proc.Continue(p), t, "Continue")
		evalVariable(p, t, "C.globalq")
	})
}
4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466

func TestIssue1615(t *testing.T) {
	// A breakpoint condition that tests for string equality with a constant string shouldn't fail with 'string too long for comparison' error

	withTestProcess("issue1615", t, func(p proc.Process, fixture protest.Fixture) {
		bp := setFileBreakpoint(p, t, fixture, 19)
		bp.Cond = &ast.BinaryExpr{
			Op: token.EQL,
			X:  &ast.Ident{Name: "s"},
			Y:  &ast.BasicLit{Kind: token.STRING, Value: `"projects/my-gcp-project-id-string/locations/us-central1/queues/my-task-queue-name"`},
		}

		assertNoError(proc.Continue(p), t, "Continue")
		assertLineNumber(p, t, 19, "")
	})
}