command_test.go 15.1 KB
Newer Older
D
Dan Mace 已提交
1
package terminal
D
Derek Parker 已提交
2

D
Derek Parker 已提交
3
import (
4
	"flag"
D
Derek Parker 已提交
5
	"fmt"
6 7
	"io/ioutil"
	"net"
8
	"net/http"
9
	"os"
10
	"path/filepath"
A
aarzilli 已提交
11
	"regexp"
12
	"strconv"
13
	"strings"
D
Derek Parker 已提交
14
	"testing"
15
	"time"
16

D
Derek Parker 已提交
17
	"github.com/derekparker/delve/pkg/proc/test"
18
	"github.com/derekparker/delve/service"
19
	"github.com/derekparker/delve/service/api"
20
	"github.com/derekparker/delve/service/rpc2"
21
	"github.com/derekparker/delve/service/rpccommon"
D
Derek Parker 已提交
22
)
D
Derek Parker 已提交
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37
var testBackend string

func TestMain(m *testing.M) {
	flag.StringVar(&testBackend, "backend", "", "selects backend")
	flag.Parse()
	if testBackend == "" {
		testBackend = os.Getenv("PROCTEST")
		if testBackend == "" {
			testBackend = "native"
		}
	}
	os.Exit(m.Run())
}

38
type FakeTerminal struct {
D
Derek Parker 已提交
39
	*Term
D
Derek Parker 已提交
40
	t testing.TB
41 42
}

43 44
const logCommandOutput = false

D
Derek Parker 已提交
45
func (ft *FakeTerminal) Exec(cmdstr string) (outstr string, err error) {
46 47
	outfh, err := ioutil.TempFile("", "cmdtestout")
	if err != nil {
D
Derek Parker 已提交
48
		ft.t.Fatalf("could not create temporary file: %v", err)
49 50
	}

A
aarzilli 已提交
51 52
	stdout, stderr, termstdout := os.Stdout, os.Stderr, ft.Term.stdout
	os.Stdout, os.Stderr, ft.Term.stdout = outfh, outfh, outfh
53
	defer func() {
A
aarzilli 已提交
54
		os.Stdout, os.Stderr, ft.Term.stdout = stdout, stderr, termstdout
55 56 57
		outfh.Close()
		outbs, err1 := ioutil.ReadFile(outfh.Name())
		if err1 != nil {
D
Derek Parker 已提交
58
			ft.t.Fatalf("could not read temporary output file: %v", err)
59 60
		}
		outstr = string(outbs)
61 62 63
		if logCommandOutput {
			ft.t.Logf("command %q -> %q", cmdstr, outstr)
		}
64 65
		os.Remove(outfh.Name())
	}()
66
	err = ft.cmds.Call(cmdstr, ft.Term)
67 68 69
	return
}

D
Derek Parker 已提交
70 71
func (ft *FakeTerminal) MustExec(cmdstr string) string {
	outstr, err := ft.Exec(cmdstr)
72
	if err != nil {
D
Derek Parker 已提交
73
		ft.t.Fatalf("Error executing <%s>: %v", cmdstr, err)
74 75 76 77
	}
	return outstr
}

78 79 80 81 82 83 84 85 86 87
func (ft *FakeTerminal) AssertExec(cmdstr, tgt string) {
	out := ft.MustExec(cmdstr)
	if out != tgt {
		ft.t.Fatalf("Error executing %q, expected %q got %q", cmdstr, tgt, out)
	}
}

func (ft *FakeTerminal) AssertExecError(cmdstr, tgterr string) {
	_, err := ft.Exec(cmdstr)
	if err == nil {
D
Derek Parker 已提交
88
		ft.t.Fatalf("Expected error executing %q", cmdstr)
89 90 91 92 93 94
	}
	if err.Error() != tgterr {
		ft.t.Fatalf("Expected error %q executing %q, got error %q", tgterr, cmdstr, err.Error())
	}
}

95
func withTestTerminal(name string, t testing.TB, fn func(*FakeTerminal)) {
96 97 98
	if testBackend == "rr" {
		test.MustHaveRecordingAllowed(t)
	}
99
	os.Setenv("TERM", "dumb")
100 101 102 103 104
	listener, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatalf("couldn't start listener: %s\n", err)
	}
	defer listener.Close()
A
aarzilli 已提交
105
	server := rpccommon.NewServer(&service.Config{
106 107
		Listener:    listener,
		ProcessArgs: []string{test.BuildFixture(name).Path},
108
		Backend:     testBackend,
109 110 111 112
	}, false)
	if err := server.Run(); err != nil {
		t.Fatal(err)
	}
113
	client := rpc2.NewClient(listener.Addr().String())
114
	defer func() {
115
		dir, _ := client.TraceDirectory()
116
		client.Detach(true)
117
		if dir != "" {
118 119
			test.SafeRemoveAll(dir)
		}
120
	}()
121

D
Derek Parker 已提交
122
	ft := &FakeTerminal{
D
Derek Parker 已提交
123 124
		t:    t,
		Term: New(client, nil),
D
Derek Parker 已提交
125 126
	}
	fn(ft)
127 128
}

D
Derek Parker 已提交
129 130
func TestCommandDefault(t *testing.T) {
	var (
J
Jason Del Ponte 已提交
131
		cmds = Commands{}
132
		cmd  = cmds.Find("non-existant-command", noPrefix)
D
Derek Parker 已提交
133 134
	)

135
	err := cmd(nil, callContext{}, "")
D
Derek Parker 已提交
136 137 138 139 140 141 142 143
	if err == nil {
		t.Fatal("cmd() did not default")
	}

	if err.Error() != "command not available" {
		t.Fatal("wrong command output")
	}
}
D
Derek Parker 已提交
144

145
func TestCommandReplay(t *testing.T) {
D
Dan Mace 已提交
146
	cmds := DebugCommands(nil)
147 148
	cmds.Register("foo", func(t *Term, ctx callContext, args string) error { return fmt.Errorf("registered command") }, "foo command")
	cmd := cmds.Find("foo", noPrefix)
149

150
	err := cmd(nil, callContext{}, "")
151 152 153 154
	if err.Error() != "registered command" {
		t.Fatal("wrong command output")
	}

155 156
	cmd = cmds.Find("", noPrefix)
	err = cmd(nil, callContext{}, "")
157 158 159 160 161 162 163
	if err.Error() != "registered command" {
		t.Fatal("wrong command output")
	}
}

func TestCommandReplayWithoutPreviousCommand(t *testing.T) {
	var (
D
Dan Mace 已提交
164
		cmds = DebugCommands(nil)
165 166
		cmd  = cmds.Find("", noPrefix)
		err  = cmd(nil, callContext{}, "")
167 168 169 170 171 172
	)

	if err != nil {
		t.Error("Null command not returned", err)
	}
}
173 174 175 176

func TestCommandThread(t *testing.T) {
	var (
		cmds = DebugCommands(nil)
177
		cmd  = cmds.Find("thread", noPrefix)
178 179
	)

180
	err := cmd(nil, callContext{}, "")
181 182 183 184 185 186 187 188
	if err == nil {
		t.Fatal("thread terminal command did not default")
	}

	if err.Error() != "you must specify a thread" {
		t.Fatal("wrong command output: ", err.Error())
	}
}
189 190 191 192 193 194 195

func TestExecuteFile(t *testing.T) {
	breakCount := 0
	traceCount := 0
	c := &Commands{
		client: nil,
		cmds: []command{
196
			{aliases: []string{"trace"}, cmdFn: func(t *Term, ctx callContext, args string) error {
197 198 199
				traceCount++
				return nil
			}},
200
			{aliases: []string{"break"}, cmdFn: func(t *Term, ctx callContext, args string) error {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
				breakCount++
				return nil
			}},
		},
	}

	fixturesDir := test.FindFixturesDir()
	err := c.executeFile(nil, filepath.Join(fixturesDir, "bpfile"))
	if err != nil {
		t.Fatalf("executeFile: %v", err)
	}

	if breakCount != 1 || traceCount != 1 {
		t.Fatalf("Wrong counts break: %d trace: %d\n", breakCount, traceCount)
	}
}
217 218

func TestIssue354(t *testing.T) {
A
aarzilli 已提交
219
	printStack([]api.Stackframe{}, "")
220
	printStack([]api.Stackframe{{api.Location{PC: 0, File: "irrelevant.go", Line: 10, Function: nil}, nil, nil, 0, ""}}, "")
221
}
222 223

func TestIssue411(t *testing.T) {
224
	test.AllowRecording(t)
225 226 227 228 229 230 231 232 233 234
	withTestTerminal("math", t, func(term *FakeTerminal) {
		term.MustExec("break math.go:8")
		term.MustExec("trace math.go:9")
		term.MustExec("continue")
		out := term.MustExec("next")
		if !strings.HasPrefix(out, "> main.main()") {
			t.Fatalf("Wrong output for next: <%s>", out)
		}
	})
}
235 236 237 238

func TestScopePrefix(t *testing.T) {
	const goroutinesLinePrefix = "  Goroutine "
	const goroutinesCurLinePrefix = "* Goroutine "
239
	test.AllowRecording(t)
240 241 242 243 244 245
	withTestTerminal("goroutinestackprog", t, func(term *FakeTerminal) {
		term.MustExec("b stacktraceme")
		term.MustExec("continue")

		goroutinesOut := strings.Split(term.MustExec("goroutines"), "\n")
		agoroutines := []int{}
246
		nonagoroutines := []int{}
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
		curgid := -1

		for _, line := range goroutinesOut {
			iscur := strings.HasPrefix(line, goroutinesCurLinePrefix)
			if !iscur && !strings.HasPrefix(line, goroutinesLinePrefix) {
				continue
			}

			dash := strings.Index(line, " - ")
			if dash < 0 {
				continue
			}

			gid, err := strconv.Atoi(line[len(goroutinesLinePrefix):dash])
			if err != nil {
				continue
			}

			if iscur {
				curgid = gid
			}

			if idx := strings.Index(line, " main.agoroutine "); idx < 0 {
270
				nonagoroutines = append(nonagoroutines, gid)
271 272 273 274 275 276
				continue
			}

			agoroutines = append(agoroutines, gid)
		}

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
		if len(agoroutines) > 10 {
			t.Fatalf("Output of goroutines did not have 10 goroutines stopped on main.agoroutine (%d found): %q", len(agoroutines), goroutinesOut)
		}

		if len(agoroutines) < 10 {
			extraAgoroutines := 0
			for _, gid := range nonagoroutines {
				stackOut := strings.Split(term.MustExec(fmt.Sprintf("goroutine %d stack", gid)), "\n")
				for _, line := range stackOut {
					if strings.HasSuffix(line, " main.agoroutine") {
						extraAgoroutines++
						break
					}
				}
			}
			if len(agoroutines)+extraAgoroutines < 10 {
				t.Fatalf("Output of goroutines did not have 10 goroutines stopped on main.agoroutine (%d+%d found): %q", len(agoroutines), extraAgoroutines, goroutinesOut)
			}
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
		}

		if curgid < 0 {
			t.Fatalf("Could not find current goroutine in output of goroutines: %q", goroutinesOut)
		}

		seen := make([]bool, 10)
		for _, gid := range agoroutines {
			stackOut := strings.Split(term.MustExec(fmt.Sprintf("goroutine %d stack", gid)), "\n")
			fid := -1
			for _, line := range stackOut {
				space := strings.Index(line, " ")
				if space < 0 {
					continue
				}
				curfid, err := strconv.Atoi(line[:space])
				if err != nil {
					continue
				}

				if idx := strings.Index(line, " main.agoroutine"); idx >= 0 {
					fid = curfid
					break
				}
			}
			if fid < 0 {
				t.Fatalf("Could not find frame for goroutine %d: %v", gid, stackOut)
			}
323
			term.AssertExec(fmt.Sprintf("goroutine     %d    frame     %d     locals", gid, fid), "(no locals)\n")
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
			argsOut := strings.Split(term.MustExec(fmt.Sprintf("goroutine %d frame %d args", gid, fid)), "\n")
			if len(argsOut) != 4 || argsOut[3] != "" {
				t.Fatalf("Wrong number of arguments in goroutine %d frame %d: %v", gid, fid, argsOut)
			}
			out := term.MustExec(fmt.Sprintf("goroutine %d frame %d p i", gid, fid))
			ival, err := strconv.Atoi(out[:len(out)-1])
			if err != nil {
				t.Fatalf("could not parse value %q of i for goroutine %d frame %d: %v", out, gid, fid, err)
			}
			seen[ival] = true
		}

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

		term.MustExec("c")

		term.AssertExecError("frame", "not enough arguments")
		term.AssertExecError("frame 1", "not enough arguments")
		term.AssertExecError("frame 1 goroutines", "command not available")
		term.AssertExecError("frame 1 goroutine", "no command passed to goroutine")
		term.AssertExecError(fmt.Sprintf("frame 1 goroutine %d", curgid), "no command passed to goroutine")
		term.AssertExecError(fmt.Sprintf("goroutine %d frame 10 locals", curgid), fmt.Sprintf("Frame 10 does not exist in goroutine %d", curgid))
		term.AssertExecError("goroutine 9000 locals", "Unknown goroutine 9000")

		term.AssertExecError("print n", "could not find symbol value for n")
		term.AssertExec("frame 1 print n", "3\n")
		term.AssertExec("frame 2 print n", "2\n")
		term.AssertExec("frame 3 print n", "1\n")
		term.AssertExec("frame 4 print n", "0\n")
		term.AssertExecError("frame 5 print n", "could not find symbol value for n")
	})
}

func TestOnPrefix(t *testing.T) {
	const prefix = "\ti: "
363
	test.AllowRecording(t)
364 365 366 367 368 369 370 371 372
	withTestTerminal("goroutinestackprog", t, func(term *FakeTerminal) {
		term.MustExec("b agobp main.agoroutine")
		term.MustExec("on agobp print i")

		seen := make([]bool, 10)

		for {
			outstr, err := term.Exec("continue")
			if err != nil {
373
				if !strings.Contains(err.Error(), "exited") {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
					t.Fatalf("Unexpected error executing 'continue': %v", err)
				}
				break
			}
			out := strings.Split(outstr, "\n")

			for i := range out {
				if !strings.HasPrefix(out[i], "\ti: ") {
					continue
				}
				id, err := strconv.Atoi(out[i][len(prefix):])
				if err != nil {
					continue
				}
				if seen[id] {
					t.Fatalf("Goroutine %d seen twice\n", id)
				}
				seen[id] = true
			}
		}

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

func TestNoVars(t *testing.T) {
404
	test.AllowRecording(t)
405 406 407 408 409 410 411 412
	withTestTerminal("locationsUpperCase", t, func(term *FakeTerminal) {
		term.MustExec("b main.main")
		term.MustExec("continue")
		term.AssertExec("args", "(no args)\n")
		term.AssertExec("locals", "(no locals)\n")
		term.AssertExec("vars filterThatMatchesNothing", "(no vars)\n")
	})
}
413 414 415

func TestOnPrefixLocals(t *testing.T) {
	const prefix = "\ti: "
416
	test.AllowRecording(t)
417 418 419 420 421 422 423 424 425
	withTestTerminal("goroutinestackprog", t, func(term *FakeTerminal) {
		term.MustExec("b agobp main.agoroutine")
		term.MustExec("on agobp args -v")

		seen := make([]bool, 10)

		for {
			outstr, err := term.Exec("continue")
			if err != nil {
426
				if !strings.Contains(err.Error(), "exited") {
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
					t.Fatalf("Unexpected error executing 'continue': %v", err)
				}
				break
			}
			out := strings.Split(outstr, "\n")

			for i := range out {
				if !strings.HasPrefix(out[i], "\ti: ") {
					continue
				}
				id, err := strconv.Atoi(out[i][len(prefix):])
				if err != nil {
					continue
				}
				if seen[id] {
					t.Fatalf("Goroutine %d seen twice\n", id)
				}
				seen[id] = true
			}
		}

		for i := range seen {
			if !seen[i] {
				t.Fatalf("Goroutine %d not seen\n", i)
			}
		}
	})
}
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

func countOccourences(s string, needle string) int {
	count := 0
	for {
		idx := strings.Index(s, needle)
		if idx < 0 {
			break
		}
		count++
		s = s[idx+len(needle):]
	}
	return count
}

func TestIssue387(t *testing.T) {
	// a breakpoint triggering during a 'next' operation will interrupt it
471
	test.AllowRecording(t)
472 473 474 475 476 477 478 479
	withTestTerminal("issue387", t, func(term *FakeTerminal) {
		breakpointHitCount := 0
		term.MustExec("break dostuff")
		for {
			outstr, err := term.Exec("continue")
			breakpointHitCount += countOccourences(outstr, "issue387.go:8")
			t.Log(outstr)
			if err != nil {
480
				if !strings.Contains(err.Error(), "exited") {
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
					t.Fatalf("Unexpected error executing 'continue': %v", err)
				}
				break
			}

			pos := 9

			for {
				outstr = term.MustExec("next")
				breakpointHitCount += countOccourences(outstr, "issue387.go:8")
				t.Log(outstr)
				if countOccourences(outstr, fmt.Sprintf("issue387.go:%d", pos)) == 0 {
					t.Fatalf("did not continue to expected position %d", pos)
				}
				pos++
496
				if pos >= 11 {
497 498 499 500 501 502 503 504 505
					break
				}
			}
		}
		if breakpointHitCount != 10 {
			t.Fatalf("Breakpoint hit wrong number of times, expected 10 got %d", breakpointHitCount)
		}
	})
}
A
aarzilli 已提交
506 507 508 509 510 511 512

func listIsAt(t *testing.T, term *FakeTerminal, listcmd string, cur, start, end int) {
	outstr := term.MustExec(listcmd)
	lines := strings.Split(outstr, "\n")

	t.Logf("%q: %q", listcmd, outstr)

513
	if !strings.Contains(lines[0], fmt.Sprintf(":%d", cur)) {
A
aarzilli 已提交
514 515 516 517 518 519 520
		t.Fatalf("Could not find current line number in first output line: %q", lines[0])
	}

	re := regexp.MustCompile(`(=>)?\s+(\d+):`)

	outStart, outEnd := 0, 0

521
	for _, line := range lines[1:] {
A
aarzilli 已提交
522 523 524 525 526
		if line == "" {
			continue
		}
		v := re.FindStringSubmatch(line)
		if len(v) != 3 {
527
			continue
A
aarzilli 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540
		}
		curline, _ := strconv.Atoi(v[2])
		if v[1] == "=>" {
			if cur != curline {
				t.Fatalf("Wrong current line, got %d expected %d", curline, cur)
			}
		}
		if outStart == 0 {
			outStart = curline
		}
		outEnd = curline
	}

541 542 543 544
	if start != -1 || end != -1 {
		if outStart != start || outEnd != end {
			t.Fatalf("Wrong output range, got %d:%d expected %d:%d", outStart, outEnd, start, end)
		}
A
aarzilli 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
	}
}

func TestListCmd(t *testing.T) {
	withTestTerminal("testvariables", t, func(term *FakeTerminal) {
		term.MustExec("continue")
		term.MustExec("continue")
		listIsAt(t, term, "list", 24, 19, 29)
		listIsAt(t, term, "list 69", 69, 64, 70)
		listIsAt(t, term, "frame 1 list", 62, 57, 67)
		listIsAt(t, term, "frame 1 list 69", 69, 64, 70)
		_, err := term.Exec("frame 50 list")
		if err == nil {
			t.Fatalf("Expected error requesting 50th frame")
		}
	})
}
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

func TestReverseContinue(t *testing.T) {
	test.AllowRecording(t)
	if testBackend != "rr" {
		return
	}
	withTestTerminal("continuetestprog", t, func(term *FakeTerminal) {
		term.MustExec("break main.main")
		term.MustExec("break main.sayhi")
		listIsAt(t, term, "continue", 16, -1, -1)
		listIsAt(t, term, "continue", 12, -1, -1)
		listIsAt(t, term, "rewind", 16, -1, -1)
	})
}

func TestCheckpoints(t *testing.T) {
	test.AllowRecording(t)
	if testBackend != "rr" {
		return
	}
	withTestTerminal("continuetestprog", t, func(term *FakeTerminal) {
		term.MustExec("break main.main")
		listIsAt(t, term, "continue", 16, -1, -1)
		term.MustExec("checkpoint")
		term.MustExec("checkpoints")
		listIsAt(t, term, "next", 17, -1, -1)
		listIsAt(t, term, "next", 18, -1, -1)
		listIsAt(t, term, "restart c1", 16, -1, -1)
	})
}
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

func TestIssue827(t *testing.T) {
	// switching goroutines when the current thread isn't running any goroutine
	// causes nil pointer dereference.
	withTestTerminal("notify-v2", t, func(term *FakeTerminal) {
		go func() {
			time.Sleep(1 * time.Second)
			http.Get("http://127.0.0.1:8888/test")
			time.Sleep(1 * time.Second)
			term.client.Halt()
		}()
		term.MustExec("continue")
		term.MustExec("goroutine 1")
	})
}