gitlab.com/Raven-IO/raven-delve@v1.22.4/service/api/types.go (about) 1 package api 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "reflect" 8 "strconv" 9 "unicode" 10 11 "gitlab.com/Raven-IO/raven-delve/pkg/proc" 12 ) 13 14 // ErrNotExecutable is an error returned when trying 15 // to debug a non-executable file. 16 var ErrNotExecutable = errors.New("not an executable file") 17 18 // DebuggerState represents the current context of the debugger. 19 type DebuggerState struct { 20 // PID of the process we are debugging. 21 Pid int 22 // Command line of the process we are debugging. 23 TargetCommandLine string 24 // Running is true if the process is running and no other information can be collected. 25 Running bool 26 // Recording is true if the process is currently being recorded and no other 27 // information can be collected. While the debugger is in this state 28 // sending a StopRecording request will halt the recording, every other 29 // request will block until the process has been recorded. 30 Recording bool 31 // Core dumping currently in progress. 32 CoreDumping bool 33 // CurrentThread is the currently selected debugger thread. 34 CurrentThread *Thread `json:"currentThread,omitempty"` 35 // SelectedGoroutine is the currently selected goroutine 36 SelectedGoroutine *Goroutine `json:"currentGoroutine,omitempty"` 37 // List of all the process threads 38 Threads []*Thread 39 // NextInProgress indicates that a next or step operation was interrupted by another breakpoint 40 // or a manual stop and is waiting to complete. 41 // While NextInProgress is set further requests for next or step may be rejected. 42 // Either execute continue until NextInProgress is false or call CancelNext 43 NextInProgress bool 44 // WatchOutOfScope contains the list of watchpoints that went out of scope 45 // during the last continue. 46 WatchOutOfScope []*Breakpoint 47 // Exited indicates whether the debugged process has exited. 48 Exited bool `json:"exited"` 49 ExitStatus int `json:"exitStatus"` 50 // When contains a description of the current position in a recording 51 When string 52 // Filled by RPCClient.Continue, indicates an error 53 Err error `json:"-"` 54 } 55 56 type TracepointResult struct { 57 // Addr is the address of this tracepoint. 58 Addr uint64 `json:"addr"` 59 // File is the source file for the breakpoint. 60 File string `json:"file"` 61 // Line is a line in File for the breakpoint. 62 Line int `json:"line"` 63 IsRet bool `json:"is_ret"` 64 // FunctionName is the name of the function at the current breakpoint, and 65 // may not always be available. 66 FunctionName string `json:"functionName,omitempty"` 67 68 GoroutineID int `json:"goroutineID"` 69 70 InputParams []Variable `json:"inputParams,omitempty"` 71 ReturnParams []Variable `json:"returnParams,omitempty"` 72 } 73 74 // Breakpoint addresses a set of locations at which process execution may be 75 // suspended. 76 type Breakpoint struct { 77 // ID is a unique identifier for the breakpoint. 78 ID int `json:"id"` 79 // User defined name of the breakpoint. 80 Name string `json:"name"` 81 // Addr is deprecated, use Addrs. 82 Addr uint64 `json:"addr"` 83 // Addrs is the list of addresses for this breakpoint. 84 Addrs []uint64 `json:"addrs"` 85 // AddrPid[i] is the PID associated with by Addrs[i], when debugging a 86 // single target process this is optional, otherwise it is mandatory. 87 AddrPid []int `json:"addrpid"` 88 // File is the source file for the breakpoint. 89 File string `json:"file"` 90 // Line is a line in File for the breakpoint. 91 Line int `json:"line"` 92 // FunctionName is the name of the function at the current breakpoint, and 93 // may not always be available. 94 FunctionName string `json:"functionName,omitempty"` 95 // ExprString is the string that will be used to set a suspended breakpoint. 96 ExprString string 97 98 // Breakpoint condition 99 Cond string 100 // Breakpoint hit count condition. 101 // Supported hit count conditions are "NUMBER" and "OP NUMBER". 102 HitCond string 103 // HitCondPerG use per goroutine hitcount as HitCond operand, instead of total hitcount 104 HitCondPerG bool 105 106 // Tracepoint flag, signifying this is a tracepoint. 107 Tracepoint bool `json:"continue"` 108 // TraceReturn flag signifying this is a breakpoint set at a return 109 // statement in a traced function. 110 TraceReturn bool `json:"traceReturn"` 111 // retrieve goroutine information 112 Goroutine bool `json:"goroutine"` 113 // number of stack frames to retrieve 114 Stacktrace int `json:"stacktrace"` 115 // expressions to evaluate 116 Variables []string `json:"variables,omitempty"` 117 // LoadArgs requests loading function arguments when the breakpoint is hit 118 LoadArgs *LoadConfig 119 // LoadLocals requests loading function locals when the breakpoint is hit 120 LoadLocals *LoadConfig 121 122 // WatchExpr is the expression used to create this watchpoint 123 WatchExpr string 124 WatchType WatchType 125 126 VerboseDescr []string `json:"VerboseDescr,omitempty"` 127 128 // number of times a breakpoint has been reached in a certain goroutine 129 HitCount map[string]uint64 `json:"hitCount"` 130 // number of times a breakpoint has been reached 131 TotalHitCount uint64 `json:"totalHitCount"` 132 // Disabled flag, signifying the state of the breakpoint 133 Disabled bool `json:"disabled"` 134 135 UserData interface{} `json:"-"` 136 } 137 138 // ValidBreakpointName returns an error if 139 // the name to be chosen for a breakpoint is invalid. 140 // The name can not be just a number, and must contain a series 141 // of letters or numbers. 142 func ValidBreakpointName(name string) error { 143 if _, err := strconv.Atoi(name); err == nil { 144 return errors.New("breakpoint name can not be a number") 145 } 146 147 for _, ch := range name { 148 if !(unicode.IsLetter(ch) || unicode.IsDigit(ch)) { 149 return fmt.Errorf("invalid character in breakpoint name '%c'", ch) 150 } 151 } 152 153 return nil 154 } 155 156 // WatchType is the watchpoint type 157 type WatchType uint8 158 159 const ( 160 WatchRead WatchType = 1 << iota 161 WatchWrite 162 ) 163 164 // Thread is a thread within the debugged process. 165 type Thread struct { 166 // ID is a unique identifier for the thread. 167 ID int `json:"id"` 168 // PC is the current program counter for the thread. 169 PC uint64 `json:"pc"` 170 // File is the file for the program counter. 171 File string `json:"file"` 172 // Line is the line number for the program counter. 173 Line int `json:"line"` 174 // Function is function information at the program counter. May be nil. 175 Function *Function `json:"function,omitempty"` 176 177 // ID of the goroutine running on this thread 178 GoroutineID int64 `json:"goroutineID"` 179 180 // Breakpoint this thread is stopped at 181 Breakpoint *Breakpoint `json:"breakPoint,omitempty"` 182 // Information requested by the current breakpoint 183 BreakpointInfo *BreakpointInfo `json:"breakPointInfo,omitempty"` 184 185 // ReturnValues contains the return values of the function we just stepped out of 186 ReturnValues []Variable 187 // CallReturn is true if ReturnValues are the return values of an injected call. 188 CallReturn bool 189 } 190 191 // Location holds program location information. 192 // In most cases a Location object will represent a physical location, with 193 // a single PC address held in the PC field. 194 // FindLocations however returns logical locations that can either have 195 // multiple PC addresses each (due to inlining) or no PC address at all. 196 type Location struct { 197 PC uint64 `json:"pc"` 198 File string `json:"file"` 199 Line int `json:"line"` 200 Function *Function `json:"function,omitempty"` 201 PCs []uint64 `json:"pcs,omitempty"` 202 PCPids []int `json:"pcpids,omitempty"` 203 } 204 205 // Stackframe describes one frame in a stack trace. 206 type Stackframe struct { 207 Location 208 Locals []Variable 209 Arguments []Variable 210 211 FrameOffset int64 212 FramePointerOffset int64 213 214 Defers []Defer 215 216 Bottom bool `json:"Bottom,omitempty"` // Bottom is true if this is the bottom frame of the stack 217 218 Err string 219 } 220 221 // Defer describes a deferred function. 222 type Defer struct { 223 DeferredLoc Location // deferred function 224 DeferLoc Location // location of the defer statement 225 SP uint64 // value of SP when the function was deferred 226 Unreadable string 227 } 228 229 // Var will return the variable described by 'name' within 230 // this stack frame. 231 func (frame *Stackframe) Var(name string) *Variable { 232 for i := range frame.Locals { 233 if frame.Locals[i].Name == name { 234 return &frame.Locals[i] 235 } 236 } 237 for i := range frame.Arguments { 238 if frame.Arguments[i].Name == name { 239 return &frame.Arguments[i] 240 } 241 } 242 return nil 243 } 244 245 // Function represents thread-scoped function information. 246 type Function struct { 247 // Name is the function name. 248 Name_ string `json:"name"` 249 Value uint64 `json:"value"` 250 Type byte `json:"type"` 251 GoType uint64 `json:"goType"` 252 // Optimized is true if the function was optimized 253 Optimized bool `json:"optimized"` 254 } 255 256 // Name will return the function name. 257 func (fn *Function) Name() string { 258 if fn == nil { 259 return "???" 260 } 261 return fn.Name_ 262 } 263 264 // VariableFlags is the type of the Flags field of Variable. 265 type VariableFlags uint16 266 267 const ( 268 // VariableEscaped is set for local variables that escaped to the heap 269 // 270 // The compiler performs escape analysis on local variables, the variables 271 // that may outlive the stack frame are allocated on the heap instead and 272 // only the address is recorded on the stack. These variables will be 273 // marked with this flag. 274 VariableEscaped = 1 << iota 275 276 // VariableShadowed is set for local variables that are shadowed by a 277 // variable with the same name in another scope 278 VariableShadowed 279 280 // VariableConstant means this variable is a constant value 281 VariableConstant 282 283 // VariableArgument means this variable is a function argument 284 VariableArgument 285 286 // VariableReturnArgument means this variable is a function return value 287 VariableReturnArgument 288 289 // VariableFakeAddress means the address of this variable is either fake 290 // (i.e. the variable is partially or completely stored in a CPU register 291 // and doesn't have a real address) or possibly no longer available (because 292 // the variable is the return value of a function call and allocated on a 293 // frame that no longer exists) 294 VariableFakeAddress 295 296 // VariableCPtr means the variable is a C pointer 297 VariableCPtr 298 299 // VariableCPURegister means this variable is a CPU register. 300 VariableCPURegister 301 ) 302 303 // Variable describes a variable. 304 type Variable struct { 305 // Name of the variable or struct member 306 Name string `json:"name"` 307 // Address of the variable or struct member 308 Addr uint64 `json:"addr"` 309 // Only the address field is filled (result of evaluating expressions like &<expr>) 310 OnlyAddr bool `json:"onlyAddr"` 311 // Go type of the variable 312 Type string `json:"type"` 313 // Type of the variable after resolving any typedefs 314 RealType string `json:"realType"` 315 316 Flags VariableFlags `json:"flags"` 317 318 Kind reflect.Kind `json:"kind"` 319 320 // Strings have their length capped at proc.maxArrayValues, use Len for the real length of a string 321 // Function variables will store the name of the function in this field 322 Value string `json:"value"` 323 324 // Number of elements in an array or a slice, number of keys for a map, number of struct members for a struct, length of strings, number of captured variables for functions 325 Len int64 `json:"len"` 326 // Cap value for slices 327 Cap int64 `json:"cap"` 328 329 // Array and slice elements, member fields of structs, key/value pairs of maps, value of complex numbers, captured variables of functions. 330 // The Name field in this slice will always be the empty string except for structs (when it will be the field name) and for complex numbers (when it will be "real" and "imaginary") 331 // For maps each map entry will have to items in this slice, even numbered items will represent map keys and odd numbered items will represent their values 332 // This field's length is capped at proc.maxArrayValues for slices and arrays and 2*proc.maxArrayValues for maps, in the circumstances where the cap takes effect len(Children) != Len 333 // The other length cap applied to this field is related to maximum recursion depth, when the maximum recursion depth is reached this field is left empty, contrary to the previous one this cap also applies to structs (otherwise structs will always have all their member fields returned) 334 Children []Variable `json:"children"` 335 336 // Base address of arrays, Base address of the backing array for slices (0 for nil slices) 337 // Base address of the backing byte array for strings 338 // address of the struct backing chan and map variables 339 // address of the function entry point for function variables (0 for nil function pointers) 340 Base uint64 `json:"base"` 341 342 // Unreadable addresses will have this field set 343 Unreadable string `json:"unreadable"` 344 345 // LocationExpr describes the location expression of this variable's address 346 LocationExpr string 347 // DeclLine is the line number of this variable's declaration 348 DeclLine int64 349 } 350 351 // LoadConfig describes how to load values from target's memory 352 type LoadConfig struct { 353 // FollowPointers requests pointers to be automatically dereferenced. 354 FollowPointers bool 355 // MaxVariableRecurse is how far to recurse when evaluating nested types. 356 MaxVariableRecurse int 357 // MaxStringLen is the maximum number of bytes read from a string 358 MaxStringLen int 359 // MaxArrayValues is the maximum number of elements read from an array, a slice or a map. 360 MaxArrayValues int 361 // MaxStructFields is the maximum number of fields read from a struct, -1 will read all fields. 362 MaxStructFields int 363 } 364 365 // Goroutine represents the information relevant to Delve from the runtime's 366 // internal G structure. 367 type Goroutine struct { 368 // ID is a unique identifier for the goroutine. 369 ID int64 `json:"id"` 370 // Current location of the goroutine 371 CurrentLoc Location `json:"currentLoc"` 372 // Current location of the goroutine, excluding calls inside runtime 373 UserCurrentLoc Location `json:"userCurrentLoc"` 374 // Location of the go instruction that started this goroutine 375 GoStatementLoc Location `json:"goStatementLoc"` 376 // Location of the starting function 377 StartLoc Location `json:"startLoc"` 378 // ID of the associated thread for running goroutines 379 ThreadID int `json:"threadID"` 380 Status uint64 `json:"status"` 381 WaitSince int64 `json:"waitSince"` 382 WaitReason int64 `json:"waitReason"` 383 Unreadable string `json:"unreadable"` 384 // Goroutine's pprof labels 385 Labels map[string]string `json:"labels,omitempty"` 386 } 387 388 const ( 389 GoroutineWaiting = proc.Gwaiting 390 GoroutineSyscall = proc.Gsyscall 391 ) 392 393 // DebuggerCommand is a command which changes the debugger's execution state. 394 type DebuggerCommand struct { 395 // Name is the command to run. 396 Name string `json:"name"` 397 // ThreadID is used to specify which thread to use with the SwitchThread 398 // command. 399 ThreadID int `json:"threadID,omitempty"` 400 // GoroutineID is used to specify which thread to use with the SwitchGoroutine 401 // and Call commands. 402 GoroutineID int64 `json:"goroutineID,omitempty"` 403 // When ReturnInfoLoadConfig is not nil it will be used to load the value 404 // of any return variables. 405 ReturnInfoLoadConfig *LoadConfig 406 // Expr is the expression argument for a Call command 407 Expr string `json:"expr,omitempty"` 408 409 // UnsafeCall disables parameter escape checking for function calls. 410 // Go objects can be allocated on the stack or on the heap. Heap objects 411 // can be used by any goroutine; stack objects can only be used by the 412 // goroutine that owns the stack they are allocated on and can not survive 413 // the stack frame of allocation. 414 // The Go compiler will use escape analysis to determine whether to 415 // allocate an object on the stack or the heap. 416 // When injecting a function call Delve will check that no address of a 417 // stack allocated object is passed to the called function: this ensures 418 // the rules for stack objects will not be violated. 419 // If you are absolutely sure that the function you are calling will not 420 // violate the rules about stack objects you can disable this safety check 421 // by setting UnsafeCall to true. 422 UnsafeCall bool `json:"unsafeCall,omitempty"` 423 } 424 425 // BreakpointInfo contains information about the current breakpoint 426 type BreakpointInfo struct { 427 Stacktrace []Stackframe `json:"stacktrace,omitempty"` 428 Goroutine *Goroutine `json:"goroutine,omitempty"` 429 Variables []Variable `json:"variables,omitempty"` 430 Arguments []Variable `json:"arguments,omitempty"` 431 Locals []Variable `json:"locals,omitempty"` 432 } 433 434 // EvalScope is the scope a command should 435 // be evaluated in. Describes the goroutine and frame number. 436 type EvalScope struct { 437 GoroutineID int64 438 Frame int 439 DeferredCall int // when DeferredCall is n > 0 this eval scope is relative to the n-th deferred call in the current frame 440 } 441 442 const ( 443 // Continue resumes process execution. 444 Continue = "continue" 445 // Rewind resumes process execution backwards (target must be a recording). 446 Rewind = "rewind" 447 // DirectionCongruentContinue resumes process execution, if a reverse next, step or stepout operation is in progress it will resume execution backward. 448 DirectionCongruentContinue = "directionCongruentContinue" 449 // Step continues to next source line, entering function calls. 450 Step = "step" 451 // ReverseStep continues backward to the previous line of source code, entering function calls. 452 ReverseStep = "reverseStep" 453 // StepOut continues to the return address of the current function 454 StepOut = "stepOut" 455 // ReverseStepOut continues backward to the caller of the current function. 456 ReverseStepOut = "reverseStepOut" 457 // StepInstruction continues for exactly 1 cpu instruction. 458 StepInstruction = "stepInstruction" 459 // NextInstruction continues for 1 cpu instruction, skipping over CALL instructions. 460 NextInstruction = "nextInstruction" 461 // ReverseStepInstruction reverses execution for exactly 1 cpu instruction. 462 ReverseStepInstruction = "reverseStepInstruction" 463 // ReverseNextInstruction reverses execution for 1 cpu instruction, skipping over CALL instructions. 464 ReverseNextInstruction = "reverseNextInstruction" 465 // Next continues to the next source line, not entering function calls. 466 Next = "next" 467 // ReverseNext continues backward to the previous line of source code, not entering function calls. 468 ReverseNext = "reverseNext" 469 // SwitchThread switches the debugger's current thread context. 470 SwitchThread = "switchThread" 471 // SwitchGoroutine switches the debugger's current thread context to the thread running the specified goroutine 472 SwitchGoroutine = "switchGoroutine" 473 // Halt suspends the process. 474 // The effect of Halt while the target process is stopped, or in the 475 // process of stopping, is operating system and timing dependent. It will 476 // either have no effect or cause the following resume to stop immediately. 477 Halt = "halt" 478 // Call resumes process execution injecting a function call. 479 Call = "call" 480 ) 481 482 // AssemblyFlavour describes the output 483 // of disassembled code. 484 type AssemblyFlavour int 485 486 const ( 487 // GNUFlavour will disassemble using GNU assembly syntax. 488 GNUFlavour = AssemblyFlavour(proc.GNUFlavour) 489 // IntelFlavour will disassemble using Intel assembly syntax. 490 IntelFlavour = AssemblyFlavour(proc.IntelFlavour) 491 // GoFlavour will disassemble using Go assembly syntax. 492 GoFlavour = AssemblyFlavour(proc.GoFlavour) 493 ) 494 495 // AsmInstruction represents one assembly instruction at some address 496 type AsmInstruction struct { 497 // Loc is the location of this instruction 498 Loc Location 499 // Destination of CALL instructions 500 DestLoc *Location 501 // Text is the formatted representation of the instruction 502 Text string 503 // Bytes is the instruction as read from memory 504 Bytes []byte 505 // If Breakpoint is true a breakpoint is set at this instruction 506 Breakpoint bool 507 // In AtPC is true this is the instruction the current thread is stopped at 508 AtPC bool 509 } 510 511 // AsmInstructions is a slice of single instructions. 512 type AsmInstructions []AsmInstruction 513 514 // GetVersionIn is the argument for GetVersion. 515 type GetVersionIn struct { 516 } 517 518 // GetVersionOut is the result of GetVersion. 519 type GetVersionOut struct { 520 DelveVersion string 521 APIVersion int 522 Backend string // backend currently in use 523 TargetGoVersion string 524 525 MinSupportedVersionOfGo string 526 MaxSupportedVersionOfGo string 527 } 528 529 // SetAPIVersionIn is the input for SetAPIVersion. 530 type SetAPIVersionIn struct { 531 APIVersion int 532 } 533 534 // SetAPIVersionOut is the output for SetAPIVersion. 535 type SetAPIVersionOut struct { 536 } 537 538 // Register holds information on a CPU register. 539 type Register struct { 540 Name string 541 Value string 542 DwarfNumber int 543 } 544 545 // Registers is a list of CPU registers. 546 type Registers []Register 547 548 func (regs Registers) String() string { 549 maxlen := 0 550 for _, reg := range regs { 551 if n := len(reg.Name); n > maxlen { 552 maxlen = n 553 } 554 } 555 556 var buf bytes.Buffer 557 for _, reg := range regs { 558 fmt.Fprintf(&buf, "%*s = %s\n", maxlen, reg.Name, reg.Value) 559 } 560 return buf.String() 561 } 562 563 // DiscardedBreakpoint is a breakpoint that is not 564 // reinstated during a restart. 565 type DiscardedBreakpoint struct { 566 Breakpoint *Breakpoint 567 Reason string 568 } 569 570 // Checkpoint is a point in the program that 571 // can be returned to in certain execution modes. 572 type Checkpoint struct { 573 ID int 574 When string 575 Where string 576 } 577 578 // Image represents a loaded shared object (go plugin or shared library) 579 type Image struct { 580 Path string 581 Address uint64 582 LoadError string 583 } 584 585 // Ancestor represents a goroutine ancestor 586 type Ancestor struct { 587 ID int64 588 Stack []Stackframe 589 590 Unreadable string 591 } 592 593 // StacktraceOptions is the type of the Opts field of StacktraceIn that 594 // configures the stacktrace. 595 // Tracks proc.StacktraceOptions 596 type StacktraceOptions uint16 597 598 const ( 599 // StacktraceReadDefers requests a stacktrace decorated with deferred calls 600 // for each frame. 601 StacktraceReadDefers StacktraceOptions = 1 << iota 602 603 // StacktraceSimple requests a stacktrace where no stack switches will be 604 // attempted. 605 StacktraceSimple 606 607 // StacktraceG requests a stacktrace starting with the register 608 // values saved in the runtime.g structure. 609 StacktraceG 610 ) 611 612 // PackageBuildInfo maps an import path to a directory path. 613 type PackageBuildInfo struct { 614 ImportPath string 615 DirectoryPath string 616 Files []string 617 } 618 619 // DumpState describes the state of a core dump in progress 620 type DumpState struct { 621 Dumping bool 622 AllDone bool 623 624 ThreadsDone, ThreadsTotal int 625 MemDone, MemTotal uint64 626 627 Err string 628 } 629 630 // ListGoroutinesFilter describes a filtering condition for the 631 // ListGoroutines API call. 632 type ListGoroutinesFilter struct { 633 Kind GoroutineField 634 Negated bool 635 Arg string 636 } 637 638 // GoroutineField allows referring to a field of a goroutine object. 639 type GoroutineField uint8 640 641 const ( 642 GoroutineFieldNone GoroutineField = iota 643 GoroutineCurrentLoc // the goroutine's CurrentLoc 644 GoroutineUserLoc // the goroutine's UserLoc 645 GoroutineGoLoc // the goroutine's GoStatementLoc 646 GoroutineStartLoc // the goroutine's StartLoc 647 GoroutineLabel // the goroutine's label 648 GoroutineRunning // the goroutine is running 649 GoroutineUser // the goroutine is a user goroutine 650 GoroutineWaitingOnChannel // the goroutine is waiting on the channel specified by the argument 651 ) 652 653 // GoroutineGroup represents a group of goroutines in the return value of 654 // the ListGoroutines API call. 655 type GoroutineGroup struct { 656 Name string // name of this group 657 Offset int // start offset in the list of goroutines of this group 658 Count int // number of goroutines that belong to this group in the list of goroutines 659 Total int // total number of goroutines that belong to this group 660 } 661 662 type GoroutineGroupingOptions struct { 663 GroupBy GoroutineField 664 GroupByKey string 665 MaxGroupMembers int 666 MaxGroups int 667 } 668 669 // Target represents a debugging target. 670 type Target struct { 671 Pid int 672 CmdLine string 673 CurrentThread *Thread 674 }