-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
gdbserver.go
2143 lines (1897 loc) · 60.7 KB
/
gdbserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file and its companion gdbserver_conn implement a target.Interface
// backed by a connection to a debugger speaking the "Gdb Remote Serial
// Protocol".
//
// The "Gdb Remote Serial Protocol" is a low level debugging protocol
// originally designed so that gdb could be used to debug programs running
// in embedded environments but it was later extended to support programs
// running on any environment and a variety of debuggers support it:
// gdbserver, lldb-server, macOS's debugserver and rr.
//
// The protocol is specified at:
// https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html
// with additional documentation for lldb specific extensions described at:
// https://github.com/llvm/llvm-project/blob/main/lldb/docs/lldb-gdb-remote.txt
//
// Terminology:
// * inferior: the program we are trying to debug
// * stub: the debugger on the other side of the protocol's connection (for
// example lldb-server)
// * gdbserver: stub version of gdb
// * lldb-server: stub version of lldb
// * debugserver: a different stub version of lldb, installed with lldb on
// macOS.
// * mozilla rr: a stub that records the full execution of a program
// and can then play it back.
//
// Implementations of the protocol vary wildly between stubs, while there is
// a command to query the stub about supported features (qSupported) this
// only covers *some* of the more recent additions to the protocol and most
// of the older packets are optional and *not* implemented by all stubs.
// For example gdbserver implements 'g' (read all registers) but not 'p'
// (read single register) while lldb-server implements 'p' but not 'g'.
//
// The protocol is also underspecified with regards to how the stub should
// handle a multithreaded inferior. Its default mode of operation is
// "all-stop mode", when a thread hits a breakpoint all other threads are
// also stopped. But the protocol doesn't say what happens if a second
// thread hits a breakpoint while the stub is in the process of stopping all
// other threads.
//
// In practice the stub is allowed to swallow the second breakpoint hit or
// to return it at a later time. If the stub chooses the latter behavior
// (like gdbserver does) it is allowed to return delayed events on *any*
// vCont packet. This is incredibly inconvenient since if we get notified
// about a delayed breakpoint while we are trying to singlestep another
// thread it's impossible to know when the singlestep we requested ended.
//
// What this means is that gdbserver can only be supported for multithreaded
// inferiors by selecting non-stop mode, which behaves in a markedly
// different way from all-stop mode and isn't supported by anything except
// gdbserver.
//
// lldb-server/debugserver takes a different approach, only the first stop
// event is reported, if any other event happens "simultaneously" they are
// suppressed by the stub and the debugger can query for them using
// qThreadStopInfo. This is much easier for us to implement and the
// implementation gracefully degrades to the case where qThreadStopInfo is
// unavailable but the inferior is run in single threaded mode.
//
// Therefore the following code will assume lldb-server-like behavior.
package gdbserial
import (
"bytes"
"debug/macho"
"encoding/binary"
"errors"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/go-delve/delve/pkg/dwarf/op"
"github.com/go-delve/delve/pkg/elfwriter"
"github.com/go-delve/delve/pkg/logflags"
"github.com/go-delve/delve/pkg/proc"
"github.com/go-delve/delve/pkg/proc/internal/ebpf"
"github.com/go-delve/delve/pkg/proc/linutil"
"github.com/go-delve/delve/pkg/proc/macutil"
isatty "github.com/mattn/go-isatty"
)
const (
gdbWireFullStopPacket = false
gdbWireMaxLen = 120
maxTransmitAttempts = 3 // number of retransmission attempts on failed checksum
initialInputBufferSize = 2048 // size of the input buffer for gdbConn
debugServerEnvVar = "DELVE_DEBUGSERVER_PATH" // use this environment variable to override the path to debugserver used by Launch/Attach
)
const heartbeatInterval = 10 * time.Second
// Relative to $(xcode-select --print-path)/../
// xcode-select typically returns the path to the Developer directory, which is a sibling to SharedFrameworks.
var debugserverXcodeRelativeExecutablePath = "SharedFrameworks/LLDB.framework/Versions/A/Resources/debugserver"
var debugserverExecutablePaths = []string{
"debugserver",
"/Library/Developer/CommandLineTools/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/debugserver",
// Function returns the active developer directory provided by xcode-select to compute a debugserver path.
func() string {
if _, err := exec.LookPath("xcode-select"); err != nil {
return ""
}
stdout, err := exec.Command("xcode-select", "--print-path").Output()
if err != nil {
return ""
}
xcodePath := strings.TrimSpace(string(stdout))
if xcodePath == "" {
return ""
}
// xcode-select prints the path to the active Developer directory, which is typically a sibling to SharedFrameworks.
return filepath.Join(xcodePath, "..", debugserverXcodeRelativeExecutablePath)
}(),
}
// ErrDirChange is returned when trying to change execution direction
// while there are still internal breakpoints set.
var ErrDirChange = errors.New("direction change with internal breakpoints")
// ErrStartCallInjectionBackwards is returned when trying to start a call
// injection while the recording is being run backwards.
var ErrStartCallInjectionBackwards = errors.New("can not start a call injection while running backwards")
var checkCanUnmaskSignalsOnce sync.Once
var canUnmaskSignalsCached bool
// gdbProcess implements proc.Process using a connection to a debugger stub
// that understands Gdb Remote Serial Protocol.
type gdbProcess struct {
bi *proc.BinaryInfo
regnames *gdbRegnames
conn gdbConn
threads map[int]*gdbThread
currentThread *gdbThread
exited, detached bool
almostExited bool // true if 'rr' has sent its synthetic SIGKILL
ctrlC bool // ctrl-c was sent to stop inferior
breakpoints proc.BreakpointMap
gcmdok bool // true if the stub supports g and (maybe) G commands
_Gcmdok bool // true if the stub supports G command
threadStopInfo bool // true if the stub supports qThreadStopInfo
tracedir string // if attached to rr the path to the trace directory
loadGInstrAddr uint64 // address of the g loading instruction, zero if we couldn't allocate it
breakpointKind int // breakpoint kind to pass to 'z' and 'Z' when creating software breakpoints
process *os.Process
waitChan chan *os.ProcessState
onDetach func() // called after a successful detach
}
var _ proc.RecordingManipulationInternal = &gdbProcess{}
// gdbThread represents an operating system thread.
type gdbThread struct {
ID int
strID string
regs gdbRegisters
CurrentBreakpoint proc.BreakpointState
p *gdbProcess
sig uint8 // signal received by thread after last stop
setbp bool // thread was stopped because of a breakpoint
watchAddr uint64 // if > 0 this is the watchpoint address
common proc.CommonThread
}
// ErrBackendUnavailable is returned when the stub program can not be found.
type ErrBackendUnavailable struct{}
func (err *ErrBackendUnavailable) Error() string {
return "backend unavailable"
}
// gdbRegisters represents the current value of the registers of a thread.
// The storage space for all the registers is allocated as a single memory
// block in buf, the value field inside an individual gdbRegister will be a
// slice of the global buf field.
type gdbRegisters struct {
regs map[string]gdbRegister
regsInfo []gdbRegisterInfo
tls uint64
gaddr uint64
hasgaddr bool
buf []byte
arch *proc.Arch
regnames *gdbRegnames
}
type gdbRegister struct {
value []byte
regnum int
ignoreOnWrite bool
}
// gdbRegname records names of important CPU registers
type gdbRegnames struct {
PC, SP, BP, CX, FsBase string
}
// newProcess creates a new Process instance.
// If process is not nil it is the stub's process and will be killed after
// Detach.
// Use Listen, Dial or Connect to complete connection.
func newProcess(process *os.Process) *gdbProcess {
logger := logflags.GdbWireLogger()
p := &gdbProcess{
conn: gdbConn{
maxTransmitAttempts: maxTransmitAttempts,
inbuf: make([]byte, 0, initialInputBufferSize),
direction: proc.Forward,
log: logger,
goarch: runtime.GOARCH,
goos: runtime.GOOS,
},
threads: make(map[int]*gdbThread),
bi: proc.NewBinaryInfo(runtime.GOOS, runtime.GOARCH),
regnames: new(gdbRegnames),
breakpoints: proc.NewBreakpointMap(),
gcmdok: true,
threadStopInfo: true,
process: process,
}
switch p.bi.Arch.Name {
default:
fallthrough
case "amd64":
p.breakpointKind = 1
case "arm64":
p.breakpointKind = 4
}
p.regnames.PC = registerName(p.bi.Arch, p.bi.Arch.PCRegNum)
p.regnames.SP = registerName(p.bi.Arch, p.bi.Arch.SPRegNum)
p.regnames.BP = registerName(p.bi.Arch, p.bi.Arch.BPRegNum)
switch p.bi.Arch.Name {
case "arm64":
p.regnames.BP = "fp"
p.regnames.CX = "x0"
case "amd64":
p.regnames.CX = "rcx"
p.regnames.FsBase = "fs_base"
default:
panic("not implemented")
}
if process != nil {
p.waitChan = make(chan *os.ProcessState)
go func() {
state, _ := process.Wait()
p.waitChan <- state
}()
}
return p
}
// Listen waits for a connection from the stub.
func (p *gdbProcess) Listen(listener net.Listener, path string, pid int, debugInfoDirs []string, stopReason proc.StopReason) (*proc.TargetGroup, error) {
acceptChan := make(chan net.Conn)
go func() {
conn, _ := listener.Accept()
acceptChan <- conn
}()
select {
case conn := <-acceptChan:
listener.Close()
if conn == nil {
return nil, errors.New("could not connect")
}
return p.Connect(conn, path, pid, debugInfoDirs, stopReason)
case status := <-p.waitChan:
listener.Close()
return nil, fmt.Errorf("stub exited while waiting for connection: %v", status)
}
}
// Dial attempts to connect to the stub.
func (p *gdbProcess) Dial(addr string, path string, pid int, debugInfoDirs []string, stopReason proc.StopReason) (*proc.TargetGroup, error) {
for {
conn, err := net.Dial("tcp", addr)
if err == nil {
return p.Connect(conn, path, pid, debugInfoDirs, stopReason)
}
select {
case status := <-p.waitChan:
return nil, fmt.Errorf("stub exited while attempting to connect: %v", status)
default:
}
time.Sleep(time.Second)
}
}
// Connect connects to a stub and performs a handshake.
//
// Path and pid are, respectively, the path to the executable of the target
// program and the PID of the target process, both are optional, however
// some stubs do not provide ways to determine path and pid automatically
// and Connect will be unable to function without knowing them.
func (p *gdbProcess) Connect(conn net.Conn, path string, pid int, debugInfoDirs []string, stopReason proc.StopReason) (*proc.TargetGroup, error) {
p.conn.conn = conn
p.conn.pid = pid
err := p.conn.handshake(p.regnames)
if err != nil {
conn.Close()
return nil, err
}
if p.conn.isDebugserver {
// There are multiple problems with the 'g'/'G' commands on debugserver.
// On version 902 it used to crash the server completely (https://bugs.llvm.org/show_bug.cgi?id=36968),
// on arm64 it results in E74 being returned (https://bugs.llvm.org/show_bug.cgi?id=50169)
// and on systems where AVX-512 is used it returns the floating point
// registers scrambled and sometimes causes the mask registers to be
// zeroed out (https://github.com/go-delve/delve/pull/2498).
// All of these bugs stem from the fact that the main consumer of
// debugserver, lldb, never uses 'g' or 'G' which would make Delve the
// sole tester of those codepaths.
// Therefore we disable it here. The associated code is kept around to be
// used with Mozilla RR.
p.gcmdok = false
}
tgt, err := p.initialize(path, debugInfoDirs, stopReason)
if err != nil {
return nil, err
}
if p.bi.Arch.Name != "arm64" {
// None of the stubs we support returns the value of fs_base or gs_base
// along with the registers, therefore we have to resort to executing a MOV
// instruction on the inferior to find out where the G struct of a given
// thread is located.
// Here we try to allocate some memory on the inferior which we will use to
// store the MOV instruction.
// If the stub doesn't support memory allocation reloadRegisters will
// overwrite some existing memory to store the MOV.
if ginstr, err := p.loadGInstr(); err == nil {
if addr, err := p.conn.allocMemory(256); err == nil {
if _, err := p.conn.writeMemory(addr, ginstr); err == nil {
p.loadGInstrAddr = addr
}
}
}
}
return tgt, nil
}
func (p *gdbProcess) SupportsBPF() bool {
return false
}
func (dbp *gdbProcess) GetBufferedTracepoints() []ebpf.RawUProbeParams {
return nil
}
func (dbp *gdbProcess) SetUProbe(fnName string, goidOffset int64, args []ebpf.UProbeArgMap) error {
panic("not implemented")
}
// unusedPort returns an unused tcp port
// This is a hack and subject to a race condition with other running
// programs, but most (all?) OS will cycle through all ephemeral ports
// before reassigning one port they just assigned, unless there's heavy
// churn in the ephemeral range this should work.
func unusedPort() string {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return ":8081"
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
return fmt.Sprintf(":%d", port)
}
// getDebugServerAbsolutePath returns a string of the absolute path to the debugserver binary IFF it is
// found in the system path ($PATH), the Xcode bundle or the standalone CLT location.
func getDebugServerAbsolutePath() string {
if path := os.Getenv(debugServerEnvVar); path != "" {
return path
}
for _, debugServerPath := range debugserverExecutablePaths {
if debugServerPath == "" {
continue
}
if _, err := exec.LookPath(debugServerPath); err == nil {
return debugServerPath
}
}
return ""
}
func canUnmaskSignals(debugServerExecutable string) bool {
checkCanUnmaskSignalsOnce.Do(func() {
buf, _ := exec.Command(debugServerExecutable, "--unmask-signals").CombinedOutput()
canUnmaskSignalsCached = !strings.Contains(string(buf), "unrecognized option")
})
return canUnmaskSignalsCached
}
// commandLogger is a wrapper around the exec.Command() function to log the arguments prior to
// starting the process
func commandLogger(binary string, arguments ...string) *exec.Cmd {
logflags.GdbWireLogger().Debugf("executing %s %v", binary, arguments)
return exec.Command(binary, arguments...)
}
// ErrUnsupportedOS is returned when trying to use the lldb backend on Windows.
var ErrUnsupportedOS = errors.New("lldb backend not supported on Windows")
func getLdEnvVars() []string {
var result []string
environ := os.Environ()
for i := 0; i < len(environ); i++ {
if strings.HasPrefix(environ[i], "LD_") ||
strings.HasPrefix(environ[i], "DYLD_") {
result = append(result, "-e", environ[i])
}
}
return result
}
// LLDBLaunch starts an instance of lldb-server and connects to it, asking
// it to launch the specified target program with the specified arguments
// (cmd) on the specified directory wd.
func LLDBLaunch(cmd []string, wd string, flags proc.LaunchFlags, debugInfoDirs []string, tty string, redirects [3]string) (*proc.TargetGroup, error) {
if runtime.GOOS == "windows" {
return nil, ErrUnsupportedOS
}
if err := macutil.CheckRosetta(); err != nil {
return nil, err
}
foreground := flags&proc.LaunchForeground != 0
var (
isDebugserver bool
listener net.Listener
port string
process *exec.Cmd
err error
hasRedirects bool
)
if debugserverExecutable := getDebugServerAbsolutePath(); debugserverExecutable != "" {
listener, err = net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
ldEnvVars := getLdEnvVars()
args := make([]string, 0, len(cmd)+4+len(ldEnvVars))
args = append(args, ldEnvVars...)
if tty != "" {
args = append(args, "--stdio-path", tty)
} else {
found := [3]bool{}
names := [3]string{"stdin", "stdout", "stderr"}
for i := range redirects {
if redirects[i] != "" {
found[i] = true
hasRedirects = true
args = append(args, fmt.Sprintf("--%s-path", names[i]), redirects[i])
}
}
if foreground || hasRedirects {
for i := range found {
if !found[i] {
args = append(args, fmt.Sprintf("--%s-path", names[i]), "/dev/"+names[i])
}
}
}
}
if logflags.LLDBServerOutput() {
args = append(args, "-g", "-l", "stdout")
}
if flags&proc.LaunchDisableASLR != 0 {
args = append(args, "-D")
}
if canUnmaskSignals(debugserverExecutable) {
args = append(args, "--unmask-signals")
}
args = append(args, "-F", "-R", fmt.Sprintf("127.0.0.1:%d", listener.Addr().(*net.TCPAddr).Port), "--")
args = append(args, cmd...)
isDebugserver = true
process = commandLogger(debugserverExecutable, args...)
} else {
if _, err = exec.LookPath("lldb-server"); err != nil {
return nil, &ErrBackendUnavailable{}
}
port = unusedPort()
args := make([]string, 0, len(cmd)+3)
args = append(args, "gdbserver", port, "--")
args = append(args, cmd...)
process = commandLogger("lldb-server", args...)
}
if logflags.LLDBServerOutput() || logflags.GdbWire() || foreground || hasRedirects {
process.Stdout = os.Stdout
process.Stderr = os.Stderr
}
if foreground || hasRedirects {
if isatty.IsTerminal(os.Stdin.Fd()) {
foregroundSignalsIgnore()
}
process.Stdin = os.Stdin
}
if wd != "" {
process.Dir = wd
}
if isatty.IsTerminal(os.Stdin.Fd()) {
process.SysProcAttr = sysProcAttr(foreground)
}
if runtime.GOOS == "darwin" {
process.Env = proc.DisableAsyncPreemptEnv()
// Filter out DYLD_INSERT_LIBRARIES on Darwin.
// This is needed since macOS Ventura, loading custom dylib into debugserver
// using DYLD_INSERT_LIBRARIES leads to a crash.
// This is unlike other protected processes, where they just strip it out.
env := make([]string, 0, len(process.Env))
for _, v := range process.Env {
if !strings.HasPrefix(v, "DYLD_INSERT_LIBRARIES") {
env = append(env, v)
}
}
process.Env = env
}
if err = process.Start(); err != nil {
return nil, err
}
p := newProcess(process.Process)
p.conn.isDebugserver = isDebugserver
var grp *proc.TargetGroup
if listener != nil {
grp, err = p.Listen(listener, cmd[0], 0, debugInfoDirs, proc.StopLaunched)
} else {
grp, err = p.Dial(port, cmd[0], 0, debugInfoDirs, proc.StopLaunched)
}
if p.conn.pid != 0 && foreground && isatty.IsTerminal(os.Stdin.Fd()) {
// Make the target process the controlling process of the tty if it is a foreground process.
err := tcsetpgrp(os.Stdin.Fd(), p.conn.pid)
if err != nil {
logflags.DebuggerLogger().Errorf("could not set controlling process: %v", err)
}
}
return grp, err
}
// LLDBAttach starts an instance of lldb-server and connects to it, asking
// it to attach to the specified pid.
// Path is path to the target's executable, path only needs to be specified
// for some stubs that do not provide an automated way of determining it
// (for example debugserver).
func LLDBAttach(pid int, path string, debugInfoDirs []string) (*proc.TargetGroup, error) {
if runtime.GOOS == "windows" {
return nil, ErrUnsupportedOS
}
if err := macutil.CheckRosetta(); err != nil {
return nil, err
}
var (
isDebugserver bool
process *exec.Cmd
listener net.Listener
port string
err error
)
if debugserverExecutable := getDebugServerAbsolutePath(); debugserverExecutable != "" {
isDebugserver = true
listener, err = net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
args := []string{"-R", fmt.Sprintf("127.0.0.1:%d", listener.Addr().(*net.TCPAddr).Port), "--attach=" + strconv.Itoa(pid)}
if canUnmaskSignals(debugserverExecutable) {
args = append(args, "--unmask-signals")
}
process = commandLogger(debugserverExecutable, args...)
} else {
if _, err = exec.LookPath("lldb-server"); err != nil {
return nil, &ErrBackendUnavailable{}
}
port = unusedPort()
process = commandLogger("lldb-server", "gdbserver", "--attach", strconv.Itoa(pid), port)
}
process.Stdout = os.Stdout
process.Stderr = os.Stderr
process.SysProcAttr = sysProcAttr(false)
if err = process.Start(); err != nil {
return nil, err
}
p := newProcess(process.Process)
p.conn.isDebugserver = isDebugserver
var grp *proc.TargetGroup
if listener != nil {
grp, err = p.Listen(listener, path, pid, debugInfoDirs, proc.StopAttached)
} else {
grp, err = p.Dial(port, path, pid, debugInfoDirs, proc.StopAttached)
}
return grp, err
}
// EntryPoint will return the process entry point address, useful for
// debugging PIEs.
func (p *gdbProcess) EntryPoint() (uint64, error) {
var entryPoint uint64
if p.bi.GOOS == "darwin" && p.bi.Arch.Name == "arm64" {
// There is no auxv on darwin, however, we can get the location of the mach-o
// header from the debugserver by going through the loaded libraries, which includes
// the exe itself
images, _ := p.conn.getLoadedDynamicLibraries()
for _, image := range images {
if image.MachHeader.FileType == macho.TypeExec {
// This is a bit hacky. This is technically not the entrypoint,
// but rather we use the variable to points at the mach-o header,
// so we can get the offset in bininfo
entryPoint = image.LoadAddress
break
}
}
} else if auxv, err := p.conn.readAuxv(); err == nil {
// If we can't read the auxiliary vector it just means it's not supported
// by the OS or by the stub. If we are debugging a PIE and the entry point
// is needed proc.LoadBinaryInfo will complain about it.
entryPoint = linutil.EntryPointFromAuxv(auxv, p.BinInfo().Arch.PtrSize())
}
return entryPoint, nil
}
// initialize uses qProcessInfo to load the inferior's PID and
// executable path. This command is not supported by all stubs and not all
// stubs will report both the PID and executable path.
func (p *gdbProcess) initialize(path string, debugInfoDirs []string, stopReason proc.StopReason) (*proc.TargetGroup, error) {
var err error
if path == "" {
// If we are attaching to a running process and the user didn't specify
// the executable file manually we must ask the stub for it.
// We support both qXfer:exec-file:read:: (the gdb way) and calling
// qProcessInfo (the lldb way).
// Unfortunately debugserver on macOS supports neither.
path, err = p.conn.readExecFile()
if err != nil {
if isProtocolErrorUnsupported(err) {
_, path, err = queryProcessInfo(p, p.Pid())
if err != nil {
p.conn.conn.Close()
return nil, err
}
} else {
p.conn.conn.Close()
return nil, fmt.Errorf("could not determine executable path: %v", err)
}
}
}
if path == "" {
// try using jGetLoadedDynamicLibrariesInfos which is the only way to do
// this supported on debugserver (but only on macOS >= 12.10)
images, _ := p.conn.getLoadedDynamicLibraries()
for _, image := range images {
if image.MachHeader.FileType == macho.TypeExec {
path = image.Pathname
break
}
}
}
err = p.updateThreadList(&threadUpdater{p: p})
if err != nil {
p.conn.conn.Close()
p.bi.Close()
return nil, err
}
p.clearThreadSignals()
if p.conn.pid <= 0 {
p.conn.pid, _, err = queryProcessInfo(p, 0)
if err != nil && !isProtocolErrorUnsupported(err) {
p.conn.conn.Close()
p.bi.Close()
return nil, err
}
}
grp, addTarget := proc.NewGroup(p, proc.NewTargetGroupConfig{
DebugInfoDirs: debugInfoDirs,
DisableAsyncPreempt: runtime.GOOS == "darwin",
StopReason: stopReason,
CanDump: runtime.GOOS == "darwin",
})
_, err = addTarget(p, p.conn.pid, p.currentThread, path, stopReason)
if err != nil {
p.Detach(true)
return nil, err
}
return grp, nil
}
func queryProcessInfo(p *gdbProcess, pid int) (int, string, error) {
pi, err := p.conn.queryProcessInfo(pid)
if err != nil {
return 0, "", err
}
if pid == 0 {
n, _ := strconv.ParseUint(pi["pid"], 16, 64)
pid = int(n)
}
return pid, pi["name"], nil
}
// BinInfo returns information on the binary.
func (p *gdbProcess) BinInfo() *proc.BinaryInfo {
return p.bi
}
// Recorded returns whether or not we are debugging
// a recorded "traced" program.
func (p *gdbProcess) Recorded() (bool, string) {
return p.tracedir != "", p.tracedir
}
// Pid returns the process ID.
func (p *gdbProcess) Pid() int {
return int(p.conn.pid)
}
// Valid returns true if we are not detached
// and the process has not exited.
func (p *gdbProcess) Valid() (bool, error) {
if p.detached {
return false, proc.ErrProcessDetached
}
if p.exited {
return false, proc.ErrProcessExited{Pid: p.Pid()}
}
if p.almostExited && p.conn.direction == proc.Forward {
return false, proc.ErrProcessExited{Pid: p.Pid()}
}
return true, nil
}
// FindThread returns the thread with the given ID.
func (p *gdbProcess) FindThread(threadID int) (proc.Thread, bool) {
thread, ok := p.threads[threadID]
return thread, ok
}
// ThreadList returns all threads in the process.
func (p *gdbProcess) ThreadList() []proc.Thread {
r := make([]proc.Thread, 0, len(p.threads))
for _, thread := range p.threads {
r = append(r, thread)
}
return r
}
// Memory returns the process memory.
func (p *gdbProcess) Memory() proc.MemoryReadWriter {
return p
}
const (
interruptSignal = 0x2
breakpointSignal = 0x5
faultSignal = 0xb
childSignal = 0x11
stopSignal = 0x13
_SIGILL = 0x4
_SIGFPE = 0x8
_SIGKILL = 0x9
debugServerTargetExcBadAccess = 0x91
debugServerTargetExcBadInstruction = 0x92
debugServerTargetExcArithmetic = 0x93
debugServerTargetExcEmulation = 0x94
debugServerTargetExcSoftware = 0x95
debugServerTargetExcBreakpoint = 0x96
)
func (p *gdbProcess) ContinueOnce(cctx *proc.ContinueOnceContext) (proc.Thread, proc.StopReason, error) {
if p.exited {
return nil, proc.StopExited, proc.ErrProcessExited{Pid: p.conn.pid}
}
if p.almostExited {
if p.conn.direction == proc.Forward {
return nil, proc.StopExited, proc.ErrProcessExited{Pid: p.conn.pid}
}
p.almostExited = false
}
if p.conn.direction == proc.Forward {
// step threads stopped at any breakpoint over their breakpoint
for _, thread := range p.threads {
if thread.CurrentBreakpoint.Breakpoint != nil {
if err := thread.StepInstruction(); err != nil {
return nil, proc.StopUnknown, err
}
}
}
}
for _, th := range p.threads {
th.clearBreakpointState()
}
p.setCtrlC(cctx, false)
// resume all threads
var threadID string
var trapthread *gdbThread
var tu = threadUpdater{p: p}
var atstart bool
continueLoop:
for {
tu.Reset()
sp, err := p.conn.resume(cctx, p.threads, &tu)
threadID = sp.threadID
if err != nil {
if _, exited := err.(proc.ErrProcessExited); exited {
p.exited = true
return nil, proc.StopExited, err
}
return nil, proc.StopUnknown, err
}
// For stubs that support qThreadStopInfo updateThreadList will
// find out the reason why each thread stopped.
// NOTE: because debugserver will sometimes send two stop packets after a
// continue it is important that this is the very first thing we do after
// resume(). See comment in threadStopInfo for an explanation.
p.updateThreadList(&tu)
trapthread = p.findThreadByStrID(threadID)
if trapthread != nil && !p.threadStopInfo {
// For stubs that do not support qThreadStopInfo we manually set the
// reason the thread returned by resume() stopped.
trapthread.sig = sp.sig
trapthread.watchAddr = sp.watchAddr
}
var shouldStop, shouldExitErr bool
trapthread, atstart, shouldStop, shouldExitErr = p.handleThreadSignals(cctx, trapthread)
if shouldExitErr {
p.almostExited = true
return nil, proc.StopExited, proc.ErrProcessExited{Pid: p.conn.pid}
}
if shouldStop {
break continueLoop
}
}
p.clearThreadRegisters()
stopReason := proc.StopUnknown
if atstart {
stopReason = proc.StopLaunched
}
if p.BinInfo().GOOS == "linux" {
if err := linutil.ElfUpdateSharedObjects(p); err != nil {
return nil, stopReason, err
}
}
if err := p.setCurrentBreakpoints(); err != nil {
return nil, stopReason, err
}
if trapthread == nil {
return nil, stopReason, fmt.Errorf("could not find thread %s", threadID)
}
err := machTargetExcToError(trapthread.sig)
if err != nil {
// the signals that are reported here can not be propagated back to the target process.
trapthread.sig = 0
}
p.currentThread = trapthread
return trapthread, stopReason, err
}
func (p *gdbProcess) findThreadByStrID(threadID string) *gdbThread {
for _, thread := range p.threads {
if thread.strID == threadID {
return thread
}
}
return nil
}
// handleThreadSignals looks at the signals received by each thread and
// decides which ones to mask and which ones to propagate back to the target
// and returns true if we should stop execution in response to one of the
// signals and return control to the user.
// Adjusts trapthread to a thread that we actually want to stop at.
func (p *gdbProcess) handleThreadSignals(cctx *proc.ContinueOnceContext, trapthread *gdbThread) (trapthreadOut *gdbThread, atstart, shouldStop, shouldExitErr bool) {
var trapthreadCandidate *gdbThread
for _, th := range p.threads {
isStopSignal := false
// 0x5 is always a breakpoint, a manual stop either manifests as 0x13
// (lldb), 0x11 (debugserver) or 0x2 (gdbserver).
// Since 0x2 could also be produced by the user
// pressing ^C (in which case it should be passed to the inferior) we need
// the ctrlC flag to know that we are the originators.
switch th.sig {
case interruptSignal: // interrupt
if p.getCtrlC(cctx) {
isStopSignal = true
}
case breakpointSignal: // breakpoint
isStopSignal = true
case childSignal: // stop on debugserver but SIGCHLD on lldb-server/linux
if p.conn.isDebugserver {
isStopSignal = true
}
case stopSignal: // stop
isStopSignal = true
case _SIGKILL:
if p.tracedir != "" {
// RR will send a synthetic SIGKILL packet right before the program
// exits, even if the program exited normally.
// Treat this signal as if the process had exited because right after
// this it is still possible to set breakpoints and rewind the process.
shouldExitErr = true
isStopSignal = true
}
// The following are fake BSD-style signals sent by debugserver
// Unfortunately debugserver can not convert them into signals for the
// process so we must stop here.
case debugServerTargetExcBadAccess, debugServerTargetExcBadInstruction, debugServerTargetExcArithmetic, debugServerTargetExcEmulation, debugServerTargetExcSoftware, debugServerTargetExcBreakpoint:
trapthreadCandidate = th
shouldStop = true
// Signal 0 is returned by rr when it reaches the start of the process
// in backward continue mode.
case 0:
if p.conn.direction == proc.Backward && th == trapthread {
isStopSignal = true
atstart = true
}
default:
// any other signal is always propagated to inferior
}
if isStopSignal {
if trapthreadCandidate == nil {
trapthreadCandidate = th
}
th.sig = 0
shouldStop = true
}