diff --git a/build/build.go b/build/build.go index 12006a9da4b2..841c395ebaab 100644 --- a/build/build.go +++ b/build/build.go @@ -313,9 +313,12 @@ func toRepoOnly(in string) (string, error) { return strings.Join(out, ","), nil } -type Handler struct { - Evaluate func(ctx context.Context, c gateway.Client, res *gateway.Result) error -} +type ( + EvaluateFunc func(ctx context.Context, name string, c gateway.Client, res *gateway.Result) error + Handler struct { + Evaluate EvaluateFunc + } +) func Build(ctx context.Context, nodes []builder.Node, opts map[string]Options, docker *dockerutil.Client, cfg *confutil.Config, w progress.Writer) (resp map[string]*client.SolveResponse, err error) { return BuildWithResultHandler(ctx, nodes, opts, docker, cfg, w, nil) @@ -510,12 +513,25 @@ func BuildWithResultHandler(ctx context.Context, nodes []builder.Node, opts map[ rKey := resultKey(dp.driverIndex, k) results.Set(rKey, res) + forceEval := false if children := childTargets[rKey]; len(children) > 0 { - if err := waitForChildren(ctx, bh, c, res, results, children); err != nil { + // wait for the child targets to register their LLB before evaluating + _, err := results.Get(ctx, children...) + if err != nil { return nil, err } - } else if bh != nil && bh.Evaluate != nil { - if err := bh.Evaluate(ctx, c, res); err != nil { + forceEval = true + } + + // invoke custom evaluate handler if it is present + if bh != nil && bh.Evaluate != nil { + if err := bh.Evaluate(ctx, k, c, res); err != nil { + return nil, err + } + } else if forceEval { + if err := res.EachRef(func(ref gateway.Reference) error { + return ref.Evaluate(ctx) + }); err != nil { return nil, err } } @@ -1199,29 +1215,6 @@ func solve(ctx context.Context, c gateway.Client, req gateway.SolveRequest) (*ga return res, nil } -func waitForChildren(ctx context.Context, bh *Handler, c gateway.Client, res *gateway.Result, results *waitmap.Map, children []string) error { - // wait for the child targets to register their LLB before evaluating - _, err := results.Get(ctx, children...) - if err != nil { - return err - } - // we need to wait until the child targets have completed before we can release - eg, ctx := errgroup.WithContext(ctx) - eg.Go(func() error { - if bh != nil && bh.Evaluate != nil { - return bh.Evaluate(ctx, c, res) - } - return res.EachRef(func(ref gateway.Reference) error { - return ref.Evaluate(ctx) - }) - }) - eg.Go(func() error { - _, err := results.Get(ctx, children...) - return err - }) - return eg.Wait() -} - func catchFrontendError(retErr, frontendErr *error) { *frontendErr = *retErr if errors.Is(*retErr, ErrRestart) { diff --git a/build/invoke.go b/build/invoke.go index 1b79a987c2b6..70df846d7ea7 100644 --- a/build/invoke.go +++ b/build/invoke.go @@ -14,18 +14,18 @@ import ( ) type InvokeConfig struct { - Entrypoint []string - Cmd []string - NoCmd bool - Env []string - User string - NoUser bool - Cwd string - NoCwd bool - Tty bool - Rollback bool - Initial bool - SuspendOn SuspendOn + Entrypoint []string `json:"entrypoint,omitempty"` + Cmd []string `json:"cmd,omitempty"` + NoCmd bool `json:"noCmd,omitempty"` + Env []string `json:"env,omitempty"` + User string `json:"user,omitempty"` + NoUser bool `json:"noUser,omitempty"` + Cwd string `json:"cwd,omitempty"` + NoCwd bool `json:"noCwd,omitempty"` + Tty bool `json:"tty,omitempty"` + Rollback bool `json:"rollback,omitempty"` + Initial bool `json:"initial,omitempty"` + SuspendOn SuspendOn `json:"suspendOn,omitempty"` } func (cfg *InvokeConfig) NeedsDebug(err error) bool { @@ -43,6 +43,18 @@ func (s SuspendOn) DebugEnabled(err error) bool { return err != nil || s == SuspendAlways } +func (s *SuspendOn) UnmarshalText(text []byte) error { + switch string(text) { + case "error": + *s = SuspendError + case "always": + *s = SuspendAlways + default: + return errors.Errorf("unknown suspend name: %s", string(text)) + } + return nil +} + type Container struct { cancelOnce sync.Once containerCancel func(error) diff --git a/build/result.go b/build/result.go index 8e999944ad85..13fefba47eba 100644 --- a/build/result.go +++ b/build/result.go @@ -16,7 +16,7 @@ import ( "github.com/sirupsen/logrus" ) -// NewResultHandle stores a gateway client, gateway result, and the error from +// NewResultHandle stores a gateway client, gateway reference, and the error from // an evaluate call if it is present. // // This ResultHandle can be used to execute additional build steps in the same @@ -24,9 +24,10 @@ import ( // failures and successes. // // If the returned ResultHandle is not nil, the caller must call Done() on it. -func NewResultHandle(ctx context.Context, c gateway.Client, res *gateway.Result, err error) *ResultHandle { +func NewResultHandle(ctx context.Context, c gateway.Client, ref gateway.Reference, meta map[string][]byte, err error) *ResultHandle { rCtx := &ResultHandle{ - res: res, + ref: ref, + meta: meta, gwClient: c, } if err != nil && !errors.As(err, &rCtx.solveErr) { @@ -37,8 +38,9 @@ func NewResultHandle(ctx context.Context, c gateway.Client, res *gateway.Result, // ResultHandle is a build result with the client that built it. type ResultHandle struct { - res *gateway.Result + ref gateway.Reference solveErr *errdefs.SolveError + meta map[string][]byte gwClient gateway.Client doneOnce sync.Once @@ -74,9 +76,9 @@ func (r *ResultHandle) NewContainer(ctx context.Context, cfg *InvokeConfig) (gat } func (r *ResultHandle) getContainerConfig(cfg *InvokeConfig) (containerCfg gateway.NewContainerRequest, _ error) { - if r.res != nil && r.solveErr == nil { + if r.ref != nil && r.solveErr == nil { logrus.Debugf("creating container from successful build") - ccfg, err := containerConfigFromResult(r.res, cfg) + ccfg, err := containerConfigFromResult(r.ref, cfg) if err != nil { return containerCfg, err } @@ -94,9 +96,9 @@ func (r *ResultHandle) getContainerConfig(cfg *InvokeConfig) (containerCfg gatew func (r *ResultHandle) getProcessConfig(cfg *InvokeConfig, stdin io.ReadCloser, stdout io.WriteCloser, stderr io.WriteCloser) (_ gateway.StartRequest, err error) { processCfg := newStartRequest(stdin, stdout, stderr) - if r.res != nil && r.solveErr == nil { + if r.ref != nil && r.solveErr == nil { logrus.Debugf("creating container from successful build") - if err := populateProcessConfigFromResult(&processCfg, r.res, cfg); err != nil { + if err := populateProcessConfigFromResult(&processCfg, r.meta, cfg); err != nil { return processCfg, err } } else { @@ -108,20 +110,11 @@ func (r *ResultHandle) getProcessConfig(cfg *InvokeConfig, stdin io.ReadCloser, return processCfg, nil } -func containerConfigFromResult(res *gateway.Result, cfg *InvokeConfig) (*gateway.NewContainerRequest, error) { +func containerConfigFromResult(ref gateway.Reference, cfg *InvokeConfig) (*gateway.NewContainerRequest, error) { if cfg.Initial { return nil, errors.Errorf("starting from the container from the initial state of the step is supported only on the failed steps") } - ps, err := exptypes.ParsePlatforms(res.Metadata) - if err != nil { - return nil, err - } - ref, ok := res.FindRef(ps.Platforms[0].ID) - if !ok { - return nil, errors.Errorf("no reference found") - } - return &gateway.NewContainerRequest{ Mounts: []gateway.Mount{ { @@ -133,8 +126,8 @@ func containerConfigFromResult(res *gateway.Result, cfg *InvokeConfig) (*gateway }, nil } -func populateProcessConfigFromResult(req *gateway.StartRequest, res *gateway.Result, cfg *InvokeConfig) error { - imgData := res.Metadata[exptypes.ExporterImageConfigKey] +func populateProcessConfigFromResult(req *gateway.StartRequest, meta map[string][]byte, cfg *InvokeConfig) error { + imgData := meta[exptypes.ExporterImageConfigKey] var img *ocispecs.Image if len(imgData) > 0 { img = &ocispecs.Image{} diff --git a/commands/build.go b/commands/build.go index f2b126c3e5e9..cc791a543991 100644 --- a/commands/build.go +++ b/commands/build.go @@ -20,7 +20,6 @@ import ( "github.com/containerd/console" "github.com/docker/buildx/build" "github.com/docker/buildx/builder" - "github.com/docker/buildx/monitor" "github.com/docker/buildx/store" "github.com/docker/buildx/store/storeutil" "github.com/docker/buildx/util/buildflags" @@ -28,6 +27,7 @@ import ( "github.com/docker/buildx/util/confutil" "github.com/docker/buildx/util/desktop" "github.com/docker/buildx/util/dockerutil" + "github.com/docker/buildx/util/ioset" "github.com/docker/buildx/util/metricutil" "github.com/docker/buildx/util/osutil" "github.com/docker/buildx/util/platformutil" @@ -55,7 +55,6 @@ import ( "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" - "github.com/tonistiigi/go-csvvalue" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" "google.golang.org/grpc/codes" @@ -100,8 +99,6 @@ type buildOptions struct { pull bool exportPush bool exportLoad bool - - invokeConfig *invokeConfig } func (o *buildOptions) toOptions() (*BuildOptions, error) { @@ -276,7 +273,7 @@ func (o *buildOptionsHash) String() string { return o.result } -func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) (err error) { +func runBuild(ctx context.Context, dockerCli command.Cli, debugOpts debuggerOptions, options buildOptions) (err error) { mp := dockerCli.MeterProvider() ctx, end, err := tracing.TraceCurrentCommand(ctx, []string{"build", options.contextPath}, @@ -320,10 +317,6 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) } driverType := b.Driver - var term bool - if _, err := console.ConsoleFromFile(os.Stderr); err == nil { - term = true - } attributes := buildMetricAttributes(dockerCli, driverType, &options) ctx2, cancel := context.WithCancelCause(context.TODO()) @@ -332,8 +325,38 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) if err != nil { return err } + + var ( + out io.Writer = os.Stderr + dbg debuggerInstance + ) + + if debugOpts != nil { + if options.dockerfileName == "-" || options.contextPath == "-" { + // stdin must be usable for debugger + return errors.Errorf("Dockerfile or context from stdin is not supported with debugger") + } + + dbg, err = debugOpts.New(ioset.In{ + Stdin: io.NopCloser(dockerCli.In()), + Stdout: nopCloser{dockerCli.Out()}, + Stderr: nopCloser{dockerCli.Err()}, + }) + if err != nil { + return err + } + out = dbg.Out() + } + + var term bool + if c, ok := out.(console.File); ok { + if _, err := console.ConsoleFromFile(c); err == nil { + term = true + } + } + var printer *progress.Printer - printer, err = progress.NewPrinter(ctx2, os.Stderr, progressMode, + printer, err = progress.NewPrinter(ctx2, out, progressMode, progress.WithDesc( fmt.Sprintf("building with %q instance using %s driver", b.Name, b.Driver), fmt.Sprintf("%s:%s", b.Driver, b.Name), @@ -348,7 +371,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) } done := timeBuildCommand(mp, attributes) - resp, inputs, retErr := runBuildWithOptions(ctx, dockerCli, opts, options, printer) + resp, inputs, retErr := runBuildWithOptions(ctx, dockerCli, opts, dbg, printer) if err := printer.Wait(); retErr == nil { retErr = err @@ -406,26 +429,19 @@ func getImageID(resp map[string]string) string { return dgst } -func runBuildWithOptions(ctx context.Context, dockerCli command.Cli, opts *BuildOptions, options buildOptions, printer *progress.Printer) (_ *client.SolveResponse, _ *build.Inputs, retErr error) { - if options.invokeConfig != nil && (options.dockerfileName == "-" || options.contextPath == "-") { - // stdin must be usable for monitor - return nil, nil, errors.Errorf("Dockerfile or context from stdin is not supported with invoke") - } - - var ( - in io.ReadCloser - m *monitor.Monitor - bh build.Handler - ) - if options.invokeConfig == nil { - in = dockerCli.In() - } else { - m = monitor.New(&options.invokeConfig.InvokeConfig, dockerCli.In(), os.Stdout, os.Stderr, printer) - defer m.Close() +func runBuildWithOptions(ctx context.Context, dockerCli command.Cli, opts *BuildOptions, dbg debuggerInstance, printer *progress.Printer) (_ *client.SolveResponse, _ *build.Inputs, retErr error) { + var bh build.Handler + if dbg != nil { + if err := dbg.Start(printer, opts); err != nil { + return nil, nil, err + } + defer dbg.Stop() - bh = m.Handler() + bh = dbg.Handler() + dockerCli.SetIn(nil) } + in := dockerCli.In() for { resp, inputs, err := RunBuild(ctx, dockerCli, opts, in, printer, &bh) if err != nil { @@ -440,7 +456,7 @@ func runBuildWithOptions(ctx context.Context, dockerCli command.Cli, opts *Build } } -func buildCmd(dockerCli command.Cli, rootOpts *rootOptions, debugConfig *debugOptions) *cobra.Command { +func buildCmd(dockerCli command.Cli, rootOpts *rootOptions, debugger debuggerOptions) *cobra.Command { cFlags := &commonFlags{} options := &buildOptions{} @@ -453,7 +469,9 @@ func buildCmd(dockerCli command.Cli, rootOpts *rootOptions, debugConfig *debugOp "aliases": "docker build, docker builder build, docker image build, docker buildx b", }, RunE: func(cmd *cobra.Command, args []string) error { - options.contextPath = args[0] + if len(args) > 0 { + options.contextPath = args[0] + } options.builder = rootOpts.builder options.metadataFile = cFlags.metadataFile options.noCache = false @@ -467,15 +485,7 @@ func buildCmd(dockerCli command.Cli, rootOpts *rootOptions, debugConfig *debugOp options.progress = cFlags.progress cmd.Flags().VisitAll(checkWarnedFlags) - if debugConfig != nil && (debugConfig.InvokeFlag != "" || debugConfig.OnFlag != "") { - iConfig := new(invokeConfig) - if err := iConfig.parseInvokeConfig(debugConfig.InvokeFlag, debugConfig.OnFlag); err != nil { - return err - } - options.invokeConfig = iConfig - } - - return runBuild(cmd.Context(), dockerCli, *options) + return runBuild(cmd.Context(), dockerCli, debugger, *options) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return nil, cobra.ShellCompDirectiveFilterDirs @@ -866,96 +876,6 @@ func printValue(w io.Writer, printer callFunc, version string, format string, re return printer([]byte(res["result.json"]), w) } -type invokeConfig struct { - build.InvokeConfig - invokeFlag string -} - -func (cfg *invokeConfig) parseInvokeConfig(invoke, on string) error { - switch on { - case "always": - cfg.SuspendOn = build.SuspendAlways - case "error": - cfg.SuspendOn = build.SuspendError - default: - if invoke != "" { - cfg.SuspendOn = build.SuspendAlways - } - } - - cfg.invokeFlag = invoke - cfg.Tty = true - cfg.NoCmd = true - switch invoke { - case "default", "": - return nil - case "on-error": - // NOTE: we overwrite the command to run because the original one should fail on the failed step. - // TODO: make this configurable via flags or restorable from LLB. - // Discussion: https://github.com/docker/buildx/pull/1640#discussion_r1113295900 - cfg.Cmd = []string{"/bin/sh"} - cfg.NoCmd = false - return nil - } - - csvParser := csvvalue.NewParser() - csvParser.LazyQuotes = true - fields, err := csvParser.Fields(invoke, nil) - if err != nil { - return err - } - if len(fields) == 1 && !strings.Contains(fields[0], "=") { - cfg.Cmd = []string{fields[0]} - cfg.NoCmd = false - return nil - } - cfg.NoUser = true - cfg.NoCwd = true - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - if len(parts) != 2 { - return errors.Errorf("invalid value %s", field) - } - key := strings.ToLower(parts[0]) - value := parts[1] - switch key { - case "args": - cfg.Cmd = append(cfg.Cmd, maybeJSONArray(value)...) - cfg.NoCmd = false - case "entrypoint": - cfg.Entrypoint = append(cfg.Entrypoint, maybeJSONArray(value)...) - if cfg.Cmd == nil { - cfg.Cmd = []string{} - cfg.NoCmd = false - } - case "env": - cfg.Env = append(cfg.Env, maybeJSONArray(value)...) - case "user": - cfg.User = value - cfg.NoUser = false - case "cwd": - cfg.Cwd = value - cfg.NoCwd = false - case "tty": - cfg.Tty, err = strconv.ParseBool(value) - if err != nil { - return errors.Errorf("failed to parse tty: %v", err) - } - default: - return errors.Errorf("unknown key %q", key) - } - } - return nil -} - -func maybeJSONArray(v string) []string { - var list []string - if err := json.Unmarshal([]byte(v), &list); err == nil { - return list - } - return []string{v} -} - func callAlias(target *string, value string) cobrautil.BoolFuncValue { return func(s string) error { v, err := strconv.ParseBool(s) @@ -1210,3 +1130,11 @@ func RunBuild(ctx context.Context, dockerCli command.Cli, in *BuildOptions, inSt } return resp[defaultTargetName], inputs, nil } + +type nopCloser struct { + io.Writer +} + +func (nopCloser) Close() error { + return nil +} diff --git a/commands/dap.go b/commands/dap.go new file mode 100644 index 000000000000..5817251924ae --- /dev/null +++ b/commands/dap.go @@ -0,0 +1,81 @@ +package commands + +import ( + "context" + + "github.com/docker/buildx/dap" + "github.com/docker/buildx/util/cobrautil" + "github.com/docker/buildx/util/ioset" + "github.com/docker/buildx/util/progress" + "github.com/docker/cli/cli/command" + "github.com/pkg/errors" + "github.com/spf13/cobra" +) + +func dapCmd(dockerCli command.Cli, rootOpts *rootOptions) *cobra.Command { + var options dapOptions + cmd := &cobra.Command{ + Use: "dap", + Short: "Start debug adapter protocol compatible debugger", + } + cobrautil.MarkCommandExperimental(cmd) + + flags := cmd.Flags() + flags.StringVar(&options.OnFlag, "on", "error", "When to pause the adapter ([always, error])") + + cobrautil.MarkFlagsExperimental(flags, "on") + + dapBuildCmd := buildCmd(dockerCli, rootOpts, &options) + dapBuildCmd.Args = cobra.RangeArgs(0, 1) + cmd.AddCommand(dapBuildCmd) + return cmd +} + +type dapOptions struct { + // OnFlag is a flag to configure the timing of launching the debugger. + OnFlag string +} + +func (d *dapOptions) New(in ioset.In) (debuggerInstance, error) { + invokeConfig, err := parseInvokeConfig("", d.OnFlag) + if err != nil { + return nil, err + } + + conn := dap.NewConn(in.Stdin, in.Stdout) + return &adapterProtocolDebugger{ + Adapter: dap.New[LaunchConfig](invokeConfig), + conn: conn, + }, nil +} + +type LaunchConfig struct { + Dockerfile string `json:"dockerfile,omitempty"` + ContextPath string `json:"contextPath,omitempty"` + Target string `json:"target,omitempty"` +} + +type adapterProtocolDebugger struct { + *dap.Adapter[LaunchConfig] + conn dap.Conn +} + +func (d *adapterProtocolDebugger) Start(printer *progress.Printer, opts *BuildOptions) error { + cfg, err := d.Adapter.Start(context.Background(), d.conn) + if err != nil { + return errors.Wrap(err, "debug adapter did not start") + } + + if cfg.Dockerfile != "" { + opts.DockerfileName = cfg.Dockerfile + } + if cfg.ContextPath != "" { + opts.ContextPath = cfg.ContextPath + } + return nil +} + +func (d *adapterProtocolDebugger) Stop() error { + defer d.conn.Close() + return d.Adapter.Stop() +} diff --git a/commands/debug.go b/commands/debug.go index 1779b47a9248..0a39cbe0f4ce 100644 --- a/commands/debug.go +++ b/commands/debug.go @@ -1,9 +1,21 @@ package commands import ( + "encoding/json" + "io" + "os" + "strconv" + "strings" + + "github.com/docker/buildx/build" + "github.com/docker/buildx/monitor" "github.com/docker/buildx/util/cobrautil" + "github.com/docker/buildx/util/ioset" + "github.com/docker/buildx/util/progress" "github.com/docker/cli/cli/command" + "github.com/pkg/errors" "github.com/spf13/cobra" + "github.com/tonistiigi/go-csvvalue" ) type debugOptions struct { @@ -14,9 +26,21 @@ type debugOptions struct { OnFlag string } +// debuggerOptions will start a debuggerOptions instance. +type debuggerOptions interface { + New(in ioset.In) (debuggerInstance, error) +} + +// debuggerInstance is an instance of a Debugger that has been started. +type debuggerInstance interface { + Start(printer *progress.Printer, opts *BuildOptions) error + Handler() build.Handler + Stop() error + Out() io.Writer +} + func debugCmd(dockerCli command.Cli, rootOpts *rootOptions) *cobra.Command { var options debugOptions - cmd := &cobra.Command{ Use: "debug", Short: "Start debugger", @@ -32,3 +56,123 @@ func debugCmd(dockerCli command.Cli, rootOpts *rootOptions) *cobra.Command { cmd.AddCommand(buildCmd(dockerCli, rootOpts, &options)) return cmd } + +func (d *debugOptions) New(in ioset.In) (debuggerInstance, error) { + cfg, err := parseInvokeConfig(d.InvokeFlag, d.OnFlag) + if err != nil { + return nil, err + } + + return &monitorDebuggerInstance{ + cfg: cfg, + in: in.Stdin, + }, nil +} + +type monitorDebuggerInstance struct { + cfg *build.InvokeConfig + in io.ReadCloser + m *monitor.Monitor +} + +func (d *monitorDebuggerInstance) Start(printer *progress.Printer, opts *BuildOptions) error { + d.m = monitor.New(d.cfg, d.in, os.Stdout, os.Stderr, printer) + return nil +} + +func (d *monitorDebuggerInstance) Handler() build.Handler { + return d.m.Handler() +} + +func (d *monitorDebuggerInstance) Stop() error { + return d.m.Close() +} + +func (d *monitorDebuggerInstance) Out() io.Writer { + return os.Stderr +} + +func parseInvokeConfig(invoke, on string) (*build.InvokeConfig, error) { + cfg := &build.InvokeConfig{} + switch on { + case "always": + cfg.SuspendOn = build.SuspendAlways + case "error": + cfg.SuspendOn = build.SuspendError + default: + if invoke != "" { + cfg.SuspendOn = build.SuspendAlways + } + } + + cfg.Tty = true + cfg.NoCmd = true + switch invoke { + case "default", "": + return cfg, nil + case "on-error": + // NOTE: we overwrite the command to run because the original one should fail on the failed step. + // TODO: make this configurable via flags or restorable from LLB. + // Discussion: https://github.com/docker/buildx/pull/1640#discussion_r1113295900 + cfg.Cmd = []string{"/bin/sh"} + cfg.NoCmd = false + return cfg, nil + } + + csvParser := csvvalue.NewParser() + csvParser.LazyQuotes = true + fields, err := csvParser.Fields(invoke, nil) + if err != nil { + return nil, err + } + if len(fields) == 1 && !strings.Contains(fields[0], "=") { + cfg.Cmd = []string{fields[0]} + cfg.NoCmd = false + return cfg, nil + } + cfg.NoUser = true + cfg.NoCwd = true + for _, field := range fields { + parts := strings.SplitN(field, "=", 2) + if len(parts) != 2 { + return nil, errors.Errorf("invalid value %s", field) + } + key := strings.ToLower(parts[0]) + value := parts[1] + switch key { + case "args": + cfg.Cmd = append(cfg.Cmd, maybeJSONArray(value)...) + cfg.NoCmd = false + case "entrypoint": + cfg.Entrypoint = append(cfg.Entrypoint, maybeJSONArray(value)...) + if cfg.Cmd == nil { + cfg.Cmd = []string{} + cfg.NoCmd = false + } + case "env": + cfg.Env = append(cfg.Env, maybeJSONArray(value)...) + case "user": + cfg.User = value + cfg.NoUser = false + case "cwd": + cfg.Cwd = value + cfg.NoCwd = false + case "tty": + cfg.Tty, err = strconv.ParseBool(value) + if err != nil { + return nil, errors.Errorf("failed to parse tty: %v", err) + } + default: + return nil, errors.Errorf("unknown key %q", key) + } + } + return cfg, nil +} + +func maybeJSONArray(v string) []string { + var list []string + if err := json.Unmarshal([]byte(v), &list); err == nil { + return list + } + return []string{v} +} diff --git a/commands/root.go b/commands/root.go index d34d5ed110f5..654e89e4bff4 100644 --- a/commands/root.go +++ b/commands/root.go @@ -120,6 +120,7 @@ func addCommands(cmd *cobra.Command, opts *rootOptions, dockerCli command.Cli) { ) if confutil.IsExperimental() { cmd.AddCommand(debugCmd(dockerCli, opts)) + cmd.AddCommand(dapCmd(dockerCli, opts)) } cmd.RegisterFlagCompletionFunc( //nolint:errcheck diff --git a/dap/adapter.go b/dap/adapter.go new file mode 100644 index 000000000000..3be497da0383 --- /dev/null +++ b/dap/adapter.go @@ -0,0 +1,456 @@ +package dap + +import ( + "context" + "encoding/json" + "fmt" + "io" + "sync" + + "github.com/docker/buildx/build" + "github.com/google/go-dap" + gateway "github.com/moby/buildkit/frontend/gateway/client" + "github.com/pkg/errors" + "golang.org/x/sync/errgroup" +) + +type Adapter[T any] struct { + srv *Server + eg *errgroup.Group + cfg build.InvokeConfig + + initialized chan struct{} + started chan launchResponse[T] + configuration chan struct{} + + evaluateReqCh chan *evaluateRequest + + threads map[int]*thread + threadsMu sync.RWMutex + nextThreadID int +} + +func New[T any](cfg *build.InvokeConfig) *Adapter[T] { + d := &Adapter[T]{ + initialized: make(chan struct{}), + started: make(chan launchResponse[T], 1), + configuration: make(chan struct{}), + evaluateReqCh: make(chan *evaluateRequest), + threads: make(map[int]*thread), + nextThreadID: 1, + } + if cfg != nil { + d.cfg = *cfg + } + d.srv = NewServer(d.dapHandler()) + return d +} + +func (d *Adapter[T]) Start(ctx context.Context, conn Conn) (T, error) { + d.eg, _ = errgroup.WithContext(ctx) + d.eg.Go(func() error { + return d.srv.Serve(ctx, conn) + }) + + <-d.initialized + + resp, ok := <-d.started + if !ok { + resp.Error = context.Canceled + } + return resp.Config, resp.Error +} + +func (d *Adapter[T]) Stop() error { + if d.eg == nil { + return nil + } + + d.srv.Go(func(c Context) { + c.C() <- &dap.TerminatedEvent{ + Event: dap.Event{ + Event: "terminated", + }, + } + // TODO: detect exit code from threads + // c.C() <- &dap.ExitedEvent{ + // Event: dap.Event{ + // Event: "exited", + // }, + // Body: dap.ExitedEventBody{ + // ExitCode: exitCode, + // }, + // } + }) + d.srv.Stop() + + err := d.eg.Wait() + d.eg = nil + return err +} + +func (d *Adapter[T]) Initialize(c Context, req *dap.InitializeRequest, resp *dap.InitializeResponse) error { + close(d.initialized) + + // Set capabilities. + resp.Body.SupportsConfigurationDoneRequest = true + return nil +} + +type launchResponse[T any] struct { + Config T + Error error +} + +func (d *Adapter[T]) Launch(c Context, req *dap.LaunchRequest, resp *dap.LaunchResponse) error { + defer close(d.started) + + var cfg T + if err := json.Unmarshal(req.Arguments, &cfg); err != nil { + d.started <- launchResponse[T]{Error: err} + return err + } + + d.start(c) + + d.started <- launchResponse[T]{Config: cfg} + return nil +} + +func (d *Adapter[T]) Disconnect(c Context, req *dap.DisconnectRequest, resp *dap.DisconnectResponse) error { + close(d.evaluateReqCh) + return nil +} + +func (d *Adapter[T]) start(c Context) { + c.Go(d.launch) +} + +func (d *Adapter[T]) Continue(c Context, req *dap.ContinueRequest, resp *dap.ContinueResponse) error { + d.threadsMu.RLock() + t := d.threads[req.Arguments.ThreadId] + d.threadsMu.RUnlock() + + t.Resume(c) + return nil +} + +func (d *Adapter[T]) SetBreakpoints(c Context, req *dap.SetBreakpointsRequest, resp *dap.SetBreakpointsResponse) error { + // TODO: implement breakpoints + for range req.Arguments.Breakpoints { + // Fail to create all breakpoints that were requested. + resp.Body.Breakpoints = append(resp.Body.Breakpoints, dap.Breakpoint{ + Verified: false, + Message: "breakpoints unsupported", + }) + } + return nil +} + +func (d *Adapter[T]) ConfigurationDone(c Context, req *dap.ConfigurationDoneRequest, resp *dap.ConfigurationDoneResponse) error { + d.configuration <- struct{}{} + close(d.configuration) + return nil +} + +func (d *Adapter[T]) launch(c Context) { + // Send initialized event. + c.C() <- &dap.InitializedEvent{ + Event: dap.Event{ + Event: "initialized", + }, + } + + // Wait for configuration. + select { + case <-c.Done(): + return + case <-d.configuration: + // TODO: actual configuration + } + + for { + select { + case <-c.Done(): + return + case req, ok := <-d.evaluateReqCh: + if !ok { + return + } + + t := d.newThread(c, req.name) + started := c.Go(func(c Context) { + defer d.deleteThread(c, t) + defer close(req.errCh) + req.errCh <- t.Evaluate(c, req.c, req.ref, req.meta, d.cfg) + }) + + if !started { + req.errCh <- context.Canceled + close(req.errCh) + } + } + } +} + +func (d *Adapter[T]) newThread(ctx Context, name string) (t *thread) { + d.threadsMu.Lock() + id := d.nextThreadID + t = &thread{ + id: id, + name: name, + } + d.threads[t.id] = t + d.nextThreadID++ + d.threadsMu.Unlock() + + ctx.C() <- &dap.ThreadEvent{ + Event: dap.Event{Event: "thread"}, + Body: dap.ThreadEventBody{ + Reason: "started", + ThreadId: t.id, + }, + } + return t +} + +func (d *Adapter[T]) getThread(id int) (t *thread) { + d.threadsMu.Lock() + t = d.threads[id] + d.threadsMu.Unlock() + return t +} + +func (d *Adapter[T]) deleteThread(ctx Context, t *thread) { + d.threadsMu.Lock() + delete(d.threads, t.id) + d.threadsMu.Unlock() + + ctx.C() <- &dap.ThreadEvent{ + Event: dap.Event{Event: "thread"}, + Body: dap.ThreadEventBody{ + Reason: "exited", + ThreadId: t.id, + }, + } +} + +type evaluateRequest struct { + name string + c gateway.Client + ref gateway.Reference + meta map[string][]byte + errCh chan<- error +} + +func (d *Adapter[T]) EvaluateResult(ctx context.Context, name string, c gateway.Client, res *gateway.Result) error { + eg, _ := errgroup.WithContext(ctx) + if res.Ref != nil { + eg.Go(func() error { + return d.evaluateRef(ctx, name, c, res.Ref, res.Metadata) + }) + } + + for k, ref := range res.Refs { + refName := fmt.Sprintf("%s (%s)", name, k) + eg.Go(func() error { + return d.evaluateRef(ctx, refName, c, ref, res.Metadata) + }) + } + return eg.Wait() +} + +func (d *Adapter[T]) evaluateRef(ctx context.Context, name string, c gateway.Client, ref gateway.Reference, meta map[string][]byte) error { + errCh := make(chan error, 1) + + // Send a solve request to the launch routine + // which will perform the solve in the context of the server. + ereq := &evaluateRequest{ + name: name, + c: c, + ref: ref, + meta: meta, + errCh: errCh, + } + select { + case d.evaluateReqCh <- ereq: + case <-ctx.Done(): + return context.Cause(ctx) + } + + // Wait for the response. + select { + case err := <-errCh: + return err + case <-ctx.Done(): + return context.Cause(ctx) + } +} + +func (d *Adapter[T]) Threads(c Context, req *dap.ThreadsRequest, resp *dap.ThreadsResponse) error { + d.threadsMu.RLock() + defer d.threadsMu.RUnlock() + + resp.Body.Threads = []dap.Thread{} + for _, t := range d.threads { + resp.Body.Threads = append(resp.Body.Threads, dap.Thread{ + Id: t.id, + Name: t.name, + }) + } + return nil +} + +func (d *Adapter[T]) StackTrace(c Context, req *dap.StackTraceRequest, resp *dap.StackTraceResponse) error { + t := d.getThread(req.Arguments.ThreadId) + if t == nil { + return errors.Errorf("no such thread: %d", req.Arguments.ThreadId) + } + + resp.Body.StackFrames = t.StackFrames() + return nil +} + +func (d *Adapter[T]) evaluate(ctx context.Context, name string, c gateway.Client, res *gateway.Result) error { + errCh := make(chan error, 1) + + started := d.srv.Go(func(ctx Context) { + defer close(errCh) + errCh <- d.EvaluateResult(ctx, name, c, res) + }) + if !started { + return context.Canceled + } + + select { + case err := <-errCh: + return err + case <-ctx.Done(): + return context.Cause(ctx) + } +} + +func (d *Adapter[T]) Handler() build.Handler { + return build.Handler{ + Evaluate: d.evaluate, + } +} + +func (d *Adapter[T]) dapHandler() Handler { + return Handler{ + Initialize: d.Initialize, + Launch: d.Launch, + Continue: d.Continue, + SetBreakpoints: d.SetBreakpoints, + ConfigurationDone: d.ConfigurationDone, + Disconnect: d.Disconnect, + Threads: d.Threads, + StackTrace: d.StackTrace, + } +} + +type thread struct { + id int + name string + + paused chan struct{} + rCtx *build.ResultHandle + mu sync.Mutex +} + +func (t *thread) Evaluate(ctx Context, c gateway.Client, ref gateway.Reference, meta map[string][]byte, cfg build.InvokeConfig) error { + err := ref.Evaluate(ctx) + if reason, desc := t.needsDebug(cfg, err); reason != "" { + rCtx := build.NewResultHandle(ctx, c, ref, meta, err) + + select { + case <-t.pause(ctx, rCtx, reason, desc): + case <-ctx.Done(): + t.Resume(ctx) + return context.Cause(ctx) + } + } + return err +} + +func (t *thread) needsDebug(cfg build.InvokeConfig, err error) (reason, desc string) { + if !cfg.NeedsDebug(err) { + return + } + + if err != nil { + reason = "exception" + desc = "Encountered an error during result evaluation" + } else { + reason = "pause" + desc = "Result evaluation completed" + } + return +} + +func (t *thread) pause(c Context, rCtx *build.ResultHandle, reason, desc string) <-chan struct{} { + if t.paused == nil { + t.paused = make(chan struct{}) + } + t.rCtx = rCtx + + c.C() <- &dap.StoppedEvent{ + Event: dap.Event{Event: "stopped"}, + Body: dap.StoppedEventBody{ + Reason: reason, + Description: desc, + ThreadId: t.id, + }, + } + return t.paused +} + +func (t *thread) Resume(c Context) { + t.mu.Lock() + defer t.mu.Unlock() + + if t.paused == nil { + return + } + + if t.rCtx != nil { + t.rCtx.Done() + t.rCtx = nil + } + + close(t.paused) + t.paused = nil +} + +// TODO: return a suitable stack frame for the thread. +// For now, just returns nothing. +func (t *thread) StackFrames() []dap.StackFrame { + return []dap.StackFrame{} +} + +func (d *Adapter[T]) Out() io.Writer { + return &adapterWriter[T]{d} +} + +type adapterWriter[T any] struct { + *Adapter[T] +} + +func (d *adapterWriter[T]) Write(p []byte) (n int, err error) { + started := d.srv.Go(func(c Context) { + <-d.initialized + + c.C() <- &dap.OutputEvent{ + Event: dap.Event{Event: "output"}, + Body: dap.OutputEventBody{ + Category: "stdout", + Output: string(p), + }, + } + }) + + if !started { + return 0, io.ErrClosedPipe + } + return n, nil +} diff --git a/dap/adapter_test.go b/dap/adapter_test.go new file mode 100644 index 000000000000..43ac9791e261 --- /dev/null +++ b/dap/adapter_test.go @@ -0,0 +1,129 @@ +package dap + +import ( + "context" + "encoding/json" + "io" + "testing" + "time" + + "github.com/google/go-dap" + "github.com/stretchr/testify/assert" + "golang.org/x/sync/errgroup" +) + +func TestLaunch(t *testing.T) { + adapter, conn, client := NewTestAdapter[any](t) + + ctx, cancel := context.WithTimeoutCause(context.Background(), 10*time.Second, context.DeadlineExceeded) + defer cancel() + + eg, _ := errgroup.WithContext(ctx) + eg.Go(func() error { + _, err := adapter.Start(ctx, conn) + assert.NoError(t, err) + return nil + }) + + var ( + initialized = make(chan struct{}) + configurationDone <-chan *dap.ConfigurationDoneResponse + ) + + client.RegisterEvent("initialized", func(em dap.EventMessage) { + // Send configuration done since we don't do any configuration. + configurationDone = DoRequest[*dap.ConfigurationDoneResponse](t, client, &dap.ConfigurationDoneRequest{ + Request: dap.Request{Command: "configurationDone"}, + }) + close(initialized) + }) + + eg.Go(func() error { + initializeResp := <-DoRequest[*dap.InitializeResponse](t, client, &dap.InitializeRequest{ + Request: dap.Request{Command: "initialize"}, + }) + assert.True(t, initializeResp.Success) + assert.True(t, initializeResp.Body.SupportsConfigurationDoneRequest) + + launchResp := <-DoRequest[*dap.LaunchResponse](t, client, &dap.LaunchRequest{ + Request: dap.Request{Command: "launch"}, + }) + assert.True(t, launchResp.Success) + + // We should have received the initialized event. + select { + case <-initialized: + default: + assert.Fail(t, "did not receive initialized event") + } + + select { + case <-configurationDone: + case <-time.After(time.Second): + assert.Fail(t, "did not receive configurationDone response") + } + return nil + }) + + eg.Wait() +} + +func NewTestAdapter[T any](t *testing.T) (*Adapter[T], Conn, *Client) { + t.Helper() + + rd1, wr1 := io.Pipe() + rd2, wr2 := io.Pipe() + + srvConn := logConn(t, "server", NewConn(rd1, wr2)) + t.Cleanup(func() { + srvConn.Close() + }) + + clientConn := logConn(t, "client", NewConn(rd2, wr1)) + t.Cleanup(func() { + clientConn.Close() + }) + + adapter := New[T](nil) + t.Cleanup(func() { adapter.Stop() }) + + client := NewClient(clientConn) + return adapter, srvConn, client +} + +func logConn(t *testing.T, prefix string, conn Conn) Conn { + return &loggingConn{ + Conn: conn, + t: t, + prefix: prefix, + } +} + +type loggingConn struct { + Conn + t *testing.T + prefix string +} + +func (c *loggingConn) SendMsg(m dap.Message) error { + b, _ := json.Marshal(m) + c.t.Logf("[%s] send: %v", c.prefix, string(b)) + + err := c.Conn.SendMsg(m) + if err != nil { + c.t.Logf("[%s] send error: %v", c.prefix, err) + } + return err +} + +func (c *loggingConn) RecvMsg(ctx context.Context) (dap.Message, error) { + m, err := c.Conn.RecvMsg(ctx) + if err != nil { + c.t.Logf("[%s] recv error: %v", c.prefix, err) + return nil, err + } + + b, _ := json.Marshal(m) + c.t.Logf("[%s] recv: %v", c.prefix, string(b)) + return m, nil +} diff --git a/dap/client_test.go b/dap/client_test.go new file mode 100644 index 000000000000..d2a48a04e24f --- /dev/null +++ b/dap/client_test.go @@ -0,0 +1,135 @@ +package dap + +import ( + "context" + "sync" + "sync/atomic" + "testing" + + "github.com/google/go-dap" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "golang.org/x/sync/errgroup" +) + +type Client struct { + conn Conn + + requests map[int]chan<- dap.ResponseMessage + requestsMu sync.Mutex + + events map[string]func(dap.EventMessage) + eventsMu sync.RWMutex + + seq atomic.Int64 + eg *errgroup.Group + cancel context.CancelCauseFunc +} + +func NewClient(conn Conn) *Client { + c := &Client{ + conn: conn, + requests: make(map[int]chan<- dap.ResponseMessage), + events: make(map[string]func(dap.EventMessage)), + } + + var ctx context.Context + ctx, c.cancel = context.WithCancelCause(context.Background()) + + c.eg, _ = errgroup.WithContext(context.Background()) + c.eg.Go(func() error { + for { + m, err := conn.RecvMsg(ctx) + if err != nil { + if errors.Is(err, context.Canceled) { + return nil + } + return err + } + + switch m := m.(type) { + case dap.RequestMessage: + // TODO: no reverse requests are currently supported + conn.SendMsg(&dap.Response{ + ProtocolMessage: dap.ProtocolMessage{ + Seq: c.nextSeq(), + Type: "response", + }, + RequestSeq: m.GetRequest().GetSeq(), + Success: false, + Command: m.GetRequest().Command, + Message: "not implemented", + }) + case dap.ResponseMessage: + c.requestsMu.Lock() + req := m.GetResponse().GetResponse().RequestSeq + ch := c.requests[req] + delete(c.requests, req) + c.requestsMu.Unlock() + + if ch != nil { + ch <- m + } + case dap.EventMessage: + c.invokeEventCallback(m) + } + } + }) + return c +} + +func (c *Client) Do(t *testing.T, req dap.RequestMessage) <-chan dap.ResponseMessage { + req.GetRequest().Type = "request" + req.GetRequest().Seq = c.nextSeq() + + ch := make(chan dap.ResponseMessage, 1) + if err := c.conn.SendMsg(req); err != nil { + assert.NoError(t, err) + close(ch) + return ch + } + + c.requestsMu.Lock() + c.requests[req.GetSeq()] = ch + c.requestsMu.Unlock() + return ch +} + +func DoRequest[ResponseMessage dap.ResponseMessage, RequestMessage dap.RequestMessage](t *testing.T, c *Client, req RequestMessage) <-chan ResponseMessage { + ch := make(chan ResponseMessage, 1) + go func() { + defer close(ch) + + if m := <-c.Do(t, req); m != nil { + ch <- m.(ResponseMessage) + } + }() + return ch +} + +func (c *Client) RegisterEvent(event string, fn func(dap.EventMessage)) { + c.eventsMu.Lock() + defer c.eventsMu.Unlock() + + c.events[event] = fn +} + +func (c *Client) invokeEventCallback(event dap.EventMessage) { + c.eventsMu.RLock() + fn := c.events[event.GetEvent().Event] + c.eventsMu.RUnlock() + + if fn != nil { + fn(event) + } +} + +func (c *Client) Close() error { + c.cancel(context.Canceled) + return c.eg.Wait() +} + +func (c *Client) nextSeq() int { + seq := c.seq.Add(1) + return int(seq) +} diff --git a/dap/conn.go b/dap/conn.go new file mode 100644 index 000000000000..6d9ca2d89321 --- /dev/null +++ b/dap/conn.go @@ -0,0 +1,109 @@ +package dap + +import ( + "bufio" + "context" + "io" + "sync" + + "github.com/google/go-dap" + "github.com/pkg/errors" + "golang.org/x/sync/errgroup" +) + +type Conn interface { + SendMsg(m dap.Message) error + RecvMsg(ctx context.Context) (dap.Message, error) + io.Closer +} + +type conn struct { + recvCh <-chan dap.Message + sendCh chan<- dap.Message + + ctx context.Context + cancel context.CancelCauseFunc + + eg *errgroup.Group + once sync.Once +} + +func NewConn(rd io.Reader, wr io.Writer) Conn { + recvCh := make(chan dap.Message, 100) + sendCh := make(chan dap.Message, 100) + errCh := make(chan error, 1) + + // Reader input may never close so this is an orphaned goroutine. + // It's ok if it does actually close but not necessary for the + // proper functioning of this connection. + // + // The reason this might not close is because stdin close is controlled + // by the OS and can't be closed from within the program. + go func() { + defer close(errCh) + defer close(recvCh) + + rd := bufio.NewReader(rd) + for { + m, err := dap.ReadProtocolMessage(rd) + if err != nil { + if !errors.Is(err, io.EOF) { + // TODO: not actually using this yet + errCh <- err + } + return + } + recvCh <- m + } + }() + + eg, _ := errgroup.WithContext(context.Background()) + eg.Go(func() error { + for m := range sendCh { + if err := dap.WriteProtocolMessage(wr, m); err != nil { + return err + } + } + return nil + }) + + ctx, cancel := context.WithCancelCause(context.Background()) + return &conn{ + recvCh: recvCh, + sendCh: sendCh, + ctx: ctx, + cancel: cancel, + eg: eg, + } +} + +func (c *conn) SendMsg(m dap.Message) error { + select { + case c.sendCh <- m: + return nil + default: + return errors.New("send channel full") + } +} + +func (c *conn) RecvMsg(ctx context.Context) (dap.Message, error) { + select { + case m, ok := <-c.recvCh: + if !ok { + return nil, io.EOF + } + return m, nil + case <-ctx.Done(): + return nil, context.Cause(ctx) + case <-c.ctx.Done(): + return nil, c.ctx.Err() + } +} + +func (c *conn) Close() error { + c.cancel(context.Canceled) + c.once.Do(func() { + close(c.sendCh) + }) + return c.eg.Wait() +} diff --git a/dap/handler.go b/dap/handler.go new file mode 100644 index 000000000000..bf0bf7059b9d --- /dev/null +++ b/dap/handler.go @@ -0,0 +1,58 @@ +package dap + +import ( + "context" + "reflect" + + "github.com/google/go-dap" + "github.com/pkg/errors" +) + +type Context interface { + context.Context + C() chan<- dap.Message + Go(f func(c Context)) bool +} + +type dispatchContext struct { + context.Context + srv *Server + ch chan<- dap.Message +} + +func (c *dispatchContext) C() chan<- dap.Message { + return c.ch +} + +func (c *dispatchContext) Go(f func(c Context)) bool { + return c.srv.Go(f) +} + +type HandlerFunc[Req dap.RequestMessage, Resp dap.ResponseMessage] func(c Context, req Req, resp Resp) error + +func (h HandlerFunc[Req, Resp]) Do(c Context, req Req) (resp Resp, err error) { + if h == nil { + return resp, errors.New("not implemented") + } + + respT := reflect.TypeFor[Resp]() + rv := reflect.New(respT.Elem()) + resp = rv.Interface().(Resp) + err = h(c, req, resp) + return resp, err +} + +type Handler struct { + Initialize HandlerFunc[*dap.InitializeRequest, *dap.InitializeResponse] + Launch HandlerFunc[*dap.LaunchRequest, *dap.LaunchResponse] + Attach HandlerFunc[*dap.AttachRequest, *dap.AttachResponse] + SetBreakpoints HandlerFunc[*dap.SetBreakpointsRequest, *dap.SetBreakpointsResponse] + ConfigurationDone HandlerFunc[*dap.ConfigurationDoneRequest, *dap.ConfigurationDoneResponse] + Disconnect HandlerFunc[*dap.DisconnectRequest, *dap.DisconnectResponse] + Terminate HandlerFunc[*dap.TerminateRequest, *dap.TerminateResponse] + Continue HandlerFunc[*dap.ContinueRequest, *dap.ContinueResponse] + Restart HandlerFunc[*dap.RestartRequest, *dap.RestartResponse] + Threads HandlerFunc[*dap.ThreadsRequest, *dap.ThreadsResponse] + StackTrace HandlerFunc[*dap.StackTraceRequest, *dap.StackTraceResponse] + Evaluate HandlerFunc[*dap.EvaluateRequest, *dap.EvaluateResponse] +} diff --git a/dap/server.go b/dap/server.go new file mode 100644 index 000000000000..faeb5139a63c --- /dev/null +++ b/dap/server.go @@ -0,0 +1,205 @@ +package dap + +import ( + "context" + "sync" + + "github.com/google/go-dap" + "github.com/pkg/errors" + "golang.org/x/sync/errgroup" +) + +var ErrServerStopped = errors.New("dap: server stopped") + +type Server struct { + h Handler + + mu sync.RWMutex + ch chan dap.Message + + eg *errgroup.Group + ctx context.Context + cancel context.CancelCauseFunc + + initialized bool +} + +func NewServer(h Handler) *Server { + return &Server{h: h} +} + +func (s *Server) Serve(ctx context.Context, conn Conn) error { + writeCh := make(chan dap.Message) + s.ch = writeCh + + s.ctx, s.cancel = context.WithCancelCause(ctx) + + // Start an error group to handle server-initiated tasks. + s.eg, _ = errgroup.WithContext(s.ctx) + s.eg.Go(func() error { + <-s.ctx.Done() + return s.ctx.Err() + }) + + eg, _ := errgroup.WithContext(s.ctx) + eg.Go(func() error { + return s.readLoop(conn) + }) + + eg.Go(func() error { + return s.writeLoop(conn, writeCh) + }) + + eg.Go(func() error { + // TODO: reevaluate this logic for shutting down + defer close(writeCh) + err := s.eg.Wait() + + s.mu.Lock() + s.ch = nil + s.mu.Unlock() + return err + }) + + return eg.Wait() +} + +func (s *Server) readLoop(conn Conn) error { + for { + m, err := conn.RecvMsg(s.ctx) + if err != nil { + return nil + } + + switch m := m.(type) { + case dap.RequestMessage: + if ok := s.dispatch(m); !ok { + return nil + } + } + } +} + +func (s *Server) dispatch(m dap.RequestMessage) bool { + fn := func(c Context) { + rmsg, err := s.handleMessage(c, m) + if err != nil { + rmsg = &dap.Response{} + rmsg.GetResponse().Message = err.Error() + } + rmsg.GetResponse().RequestSeq = m.GetSeq() + rmsg.GetResponse().Command = m.GetRequest().Command + rmsg.GetResponse().Success = err == nil + c.C() <- rmsg + } + return s.Go(fn) +} + +func (s *Server) handleMessage(c Context, m dap.Message) (dap.ResponseMessage, error) { + switch req := m.(type) { + case *dap.InitializeRequest: + resp, err := s.handleInitialize(c, req) + if err != nil { + return nil, err + } + return resp, nil + case *dap.LaunchRequest: + return s.h.Launch.Do(c, req) + case *dap.AttachRequest: + return s.h.Attach.Do(c, req) + case *dap.SetBreakpointsRequest: + return s.h.SetBreakpoints.Do(c, req) + case *dap.ConfigurationDoneRequest: + return s.h.ConfigurationDone.Do(c, req) + case *dap.DisconnectRequest: + return s.h.Disconnect.Do(c, req) + case *dap.TerminateRequest: + return s.h.Terminate.Do(c, req) + case *dap.ContinueRequest: + return s.h.Continue.Do(c, req) + case *dap.RestartRequest: + return s.h.Restart.Do(c, req) + case *dap.ThreadsRequest: + return s.h.Threads.Do(c, req) + case *dap.StackTraceRequest: + return s.h.StackTrace.Do(c, req) + case *dap.EvaluateRequest: + return s.h.Evaluate.Do(c, req) + default: + return nil, errors.New("not implemented") + } +} + +func (s *Server) handleInitialize(c Context, req *dap.InitializeRequest) (*dap.InitializeResponse, error) { + if s.initialized { + return nil, errors.New("already initialized") + } + + resp, err := s.h.Initialize.Do(c, req) + if err != nil { + return nil, err + } + s.initialized = true + return resp, nil +} + +func (s *Server) writeLoop(conn Conn, respCh <-chan dap.Message) error { + var seq int + for m := range respCh { + switch m := m.(type) { + case dap.RequestMessage: + m.GetRequest().Seq = seq + m.GetRequest().Type = "request" + case dap.EventMessage: + m.GetEvent().Seq = seq + m.GetEvent().Type = "event" + case dap.ResponseMessage: + m.GetResponse().Seq = seq + m.GetResponse().Type = "response" + } + seq++ + + if err := conn.SendMsg(m); err != nil { + return err + } + } + return nil +} + +func (s *Server) Go(fn func(c Context)) bool { + acquireChannel := func() (chan<- dap.Message, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + + return s.ch, s.ch != nil + } + + ctx, cancel := context.WithCancelCause(s.ctx) + c := &dispatchContext{ + Context: ctx, + srv: s, + } + + started := make(chan bool, 1) + s.eg.Go(func() error { + var ok bool + c.ch, ok = acquireChannel() + started <- ok + + if c.ch == nil { + return nil + } + + defer cancel(context.Canceled) + fn(c) + return nil + }) + return <-started +} + +func (s *Server) Stop() { + s.mu.Lock() + s.ch = nil + s.mu.Unlock() + s.cancel(ErrServerStopped) +} diff --git a/docs/reference/buildx.md b/docs/reference/buildx.md index 6e060ce5c631..39d2e7e6693f 100644 --- a/docs/reference/buildx.md +++ b/docs/reference/buildx.md @@ -9,23 +9,24 @@ Extended build capabilities with BuildKit ### Subcommands -| Name | Description | -|:-------------------------------------|:------------------------------------------------| -| [`bake`](buildx_bake.md) | Build from a file | -| [`build`](buildx_build.md) | Start a build | -| [`create`](buildx_create.md) | Create a new builder instance | -| [`debug`](buildx_debug.md) | Start debugger (EXPERIMENTAL) | -| [`dial-stdio`](buildx_dial-stdio.md) | Proxy current stdio streams to builder instance | -| [`du`](buildx_du.md) | Disk usage | -| [`history`](buildx_history.md) | Commands to work on build records | -| [`imagetools`](buildx_imagetools.md) | Commands to work on images in registry | -| [`inspect`](buildx_inspect.md) | Inspect current builder instance | -| [`ls`](buildx_ls.md) | List builder instances | -| [`prune`](buildx_prune.md) | Remove build cache | -| [`rm`](buildx_rm.md) | Remove one or more builder instances | -| [`stop`](buildx_stop.md) | Stop builder instance | -| [`use`](buildx_use.md) | Set the current builder instance | -| [`version`](buildx_version.md) | Show buildx version information | +| Name | Description | +|:-------------------------------------|:----------------------------------------------------------------| +| [`bake`](buildx_bake.md) | Build from a file | +| [`build`](buildx_build.md) | Start a build | +| [`create`](buildx_create.md) | Create a new builder instance | +| [`dap`](buildx_dap.md) | Start debug adapter protocol compatible debugger (EXPERIMENTAL) | +| [`debug`](buildx_debug.md) | Start debugger (EXPERIMENTAL) | +| [`dial-stdio`](buildx_dial-stdio.md) | Proxy current stdio streams to builder instance | +| [`du`](buildx_du.md) | Disk usage | +| [`history`](buildx_history.md) | Commands to work on build records | +| [`imagetools`](buildx_imagetools.md) | Commands to work on images in registry | +| [`inspect`](buildx_inspect.md) | Inspect current builder instance | +| [`ls`](buildx_ls.md) | List builder instances | +| [`prune`](buildx_prune.md) | Remove build cache | +| [`rm`](buildx_rm.md) | Remove one or more builder instances | +| [`stop`](buildx_stop.md) | Stop builder instance | +| [`use`](buildx_use.md) | Set the current builder instance | +| [`version`](buildx_version.md) | Show buildx version information | ### Options diff --git a/docs/reference/buildx_dap.md b/docs/reference/buildx_dap.md new file mode 100644 index 000000000000..669aba0bf4dc --- /dev/null +++ b/docs/reference/buildx_dap.md @@ -0,0 +1,23 @@ +# docker buildx dap + + +Start debug adapter protocol compatible debugger (EXPERIMENTAL) + +### Subcommands + +| Name | Description | +|:-------------------------------|:--------------| +| [`build`](buildx_dap_build.md) | Start a build | + + +### Options + +| Name | Type | Default | Description | +|:----------------|:---------|:--------|:-----------------------------------------------------------| +| `--builder` | `string` | | Override the configured builder instance | +| `-D`, `--debug` | `bool` | | Enable debug logging | +| `--on` | `string` | `error` | When to pause the adapter ([always, error]) (EXPERIMENTAL) | + + + + diff --git a/docs/reference/buildx_dap_build.md b/docs/reference/buildx_dap_build.md new file mode 100644 index 000000000000..01c708759cd5 --- /dev/null +++ b/docs/reference/buildx_dap_build.md @@ -0,0 +1,52 @@ +# docker buildx dap build + + +Start a build + +### Aliases + +`docker build`, `docker builder build`, `docker image build`, `docker buildx b` + +### Options + +| Name | Type | Default | Description | +|:--------------------|:--------------|:----------|:-------------------------------------------------------------------------------------------------------------| +| `--add-host` | `stringSlice` | | Add a custom host-to-IP mapping (format: `host:ip`) | +| `--allow` | `stringArray` | | Allow extra privileged entitlement (e.g., `network.host`, `security.insecure`) | +| `--annotation` | `stringArray` | | Add annotation to the image | +| `--attest` | `stringArray` | | Attestation parameters (format: `type=sbom,generator=image`) | +| `--build-arg` | `stringArray` | | Set build-time variables | +| `--build-context` | `stringArray` | | Additional build contexts (e.g., name=path) | +| `--builder` | `string` | | Override the configured builder instance | +| `--cache-from` | `stringArray` | | External cache sources (e.g., `user/app:cache`, `type=local,src=path/to/dir`) | +| `--cache-to` | `stringArray` | | Cache export destinations (e.g., `user/app:cache`, `type=local,dest=path/to/dir`) | +| `--call` | `string` | `build` | Set method for evaluating build (`check`, `outline`, `targets`) | +| `--cgroup-parent` | `string` | | Set the parent cgroup for the `RUN` instructions during build | +| `--check` | `bool` | | Shorthand for `--call=check` | +| `-D`, `--debug` | `bool` | | Enable debug logging | +| `-f`, `--file` | `string` | | Name of the Dockerfile (default: `PATH/Dockerfile`) | +| `--iidfile` | `string` | | Write the image ID to a file | +| `--label` | `stringArray` | | Set metadata for an image | +| `--load` | `bool` | | Shorthand for `--output=type=docker` | +| `--metadata-file` | `string` | | Write build result metadata to a file | +| `--network` | `string` | `default` | Set the networking mode for the `RUN` instructions during build | +| `--no-cache` | `bool` | | Do not use cache when building the image | +| `--no-cache-filter` | `stringArray` | | Do not cache specified stages | +| `-o`, `--output` | `stringArray` | | Output destination (format: `type=local,dest=path`) | +| `--platform` | `stringArray` | | Set target platform for build | +| `--progress` | `string` | `auto` | Set type of progress output (`auto`, `quiet`, `plain`, `tty`, `rawjson`). Use plain to show container output | +| `--provenance` | `string` | | Shorthand for `--attest=type=provenance` | +| `--pull` | `bool` | | Always attempt to pull all referenced images | +| `--push` | `bool` | | Shorthand for `--output=type=registry` | +| `-q`, `--quiet` | `bool` | | Suppress the build output and print image ID on success | +| `--sbom` | `string` | | Shorthand for `--attest=type=sbom` | +| `--secret` | `stringArray` | | Secret to expose to the build (format: `id=mysecret[,src=/local/secret]`) | +| `--shm-size` | `bytes` | `0` | Shared memory size for build containers | +| `--ssh` | `stringArray` | | SSH agent socket or keys to expose to the build (format: `default\|[=\|[,]]`) | +| `-t`, `--tag` | `stringArray` | | Name and optionally a tag (format: `name:tag`) | +| `--target` | `string` | | Set the target build stage to build | +| `--ulimit` | `ulimit` | | Ulimit options | + + + + diff --git a/go.mod b/go.mod index 0f473e9eb7cf..d9580ea98fda 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/docker/docker v28.2.2+incompatible github.com/docker/go-units v0.5.0 github.com/gofrs/flock v0.12.1 + github.com/google/go-dap v0.12.0 github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/google/uuid v1.6.0 github.com/hashicorp/go-cty-funcs v0.0.0-20250210171435-dda779884a9f diff --git a/go.sum b/go.sum index bf8e7885afac..2bd6b049cdd7 100644 --- a/go.sum +++ b/go.sum @@ -177,6 +177,8 @@ github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYu github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-dap v0.12.0 h1:rVcjv3SyMIrpaOoTAdFDyHs99CwVOItIJGKLQFQhNeM= +github.com/google/go-dap v0.12.0/go.mod h1:tNjCASCm5cqePi/RVXXWEVqtnNLV1KTWtYOqu6rZNzc= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= diff --git a/monitor/monitor.go b/monitor/monitor.go index 6981c5ccbd7c..f5a866b4c238 100644 --- a/monitor/monitor.go +++ b/monitor/monitor.go @@ -19,6 +19,7 @@ import ( "github.com/docker/buildx/util/ioset" "github.com/docker/buildx/util/progress" "github.com/google/shlex" + "github.com/moby/buildkit/exporter/containerimage/exptypes" gateway "github.com/moby/buildkit/frontend/gateway/client" "github.com/moby/buildkit/identity" "github.com/moby/buildkit/solver/errdefs" @@ -56,7 +57,7 @@ func (m *Monitor) Handler() build.Handler { } } -func (m *Monitor) Evaluate(ctx context.Context, c gateway.Client, res *gateway.Result) error { +func (m *Monitor) Evaluate(ctx context.Context, _ string, c gateway.Client, res *gateway.Result) error { buildErr := res.EachRef(func(ref gateway.Reference) error { return ref.Evaluate(ctx) }) @@ -70,7 +71,17 @@ func (m *Monitor) Evaluate(ctx context.Context, c gateway.Client, res *gateway.R logrus.Warnf("failed to print error information: %v", err) } - rCtx := build.NewResultHandle(ctx, c, res, buildErr) + ps, err := exptypes.ParsePlatforms(res.Metadata) + if err != nil { + return err + } + + ref, ok := res.FindRef(ps.Platforms[0].ID) + if !ok { + return errors.Errorf("no reference found for %s", ps.Platforms[0].ID) + } + + rCtx := build.NewResultHandle(ctx, c, ref, res.Metadata, buildErr) if monitorErr := m.Run(ctx, rCtx); monitorErr != nil { if errors.Is(monitorErr, build.ErrRestart) { return build.ErrRestart diff --git a/util/progress/printer.go b/util/progress/printer.go index 85208b7e200e..73a75bd6ada9 100644 --- a/util/progress/printer.go +++ b/util/progress/printer.go @@ -2,10 +2,10 @@ package progress import ( "context" + "io" "os" "sync" - "github.com/containerd/console" "github.com/docker/buildx/util/logutil" "github.com/mitchellh/hashstructure/v2" "github.com/moby/buildkit/client" @@ -25,7 +25,7 @@ const ( ) type Printer struct { - out console.File + out io.Writer mode progressui.DisplayMode opt *printerOpts @@ -121,7 +121,7 @@ func (p *Printer) ClearLogSource(v any) { } } -func NewPrinter(ctx context.Context, out console.File, mode progressui.DisplayMode, opts ...PrinterOpt) (*Printer, error) { +func NewPrinter(ctx context.Context, out io.Writer, mode progressui.DisplayMode, opts ...PrinterOpt) (*Printer, error) { opt := &printerOpts{} for _, o := range opts { o(opt) diff --git a/vendor/github.com/google/go-dap/LICENSE b/vendor/github.com/google/go-dap/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/google/go-dap/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/google/go-dap/README.md b/vendor/github.com/google/go-dap/README.md new file mode 100644 index 000000000000..fbbe01e68efd --- /dev/null +++ b/vendor/github.com/google/go-dap/README.md @@ -0,0 +1,20 @@ +# go-dap: Go implementation of the Debug Adapter Protocol + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/google/go-dap)](https://pkg.go.dev/github.com/google/go-dap) +[![Build Status](https://github.com/google/go-dap/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/google/go-dap/actions) +[![Go Report Card](https://goreportcard.com/badge/github.com/google/go-dap)](https://goreportcard.com/report/github.com/google/go-dap) + +For an overview of DAP, see +https://microsoft.github.io/debug-adapter-protocol/overview + +## Contributing + +We'd love to accept your patches and contributions to this project. See +[docs/contributing](https://github.com/google/go-dap/blob/master/docs/contributing.md) +for more details. + +## License + +This project is licensed under the Apache License 2.0 + +This is not an officially supported Google product. diff --git a/vendor/github.com/google/go-dap/codec.go b/vendor/github.com/google/go-dap/codec.go new file mode 100644 index 000000000000..79a43b44c906 --- /dev/null +++ b/vendor/github.com/google/go-dap/codec.go @@ -0,0 +1,188 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file contains utilities for decoding JSON-encoded bytes into DAP message. + +package dap + +import ( + "encoding/json" + "fmt" +) + +// DecodeProtocolMessageFieldError describes which JSON attribute +// has an unsupported value that the decoding cannot handle. +type DecodeProtocolMessageFieldError struct { + Seq int + SubType string + FieldName string + FieldValue string + Message json.RawMessage +} + +func (e *DecodeProtocolMessageFieldError) Error() string { + return fmt.Sprintf("%s %s '%s' is not supported (seq: %d)", e.SubType, e.FieldName, e.FieldValue, e.Seq) +} + +// defaultCodec is used to decode vanilla DAP messages. +var defaultCodec = NewCodec() + +// Codec is responsible for turning byte blobs into DAP messages. +type Codec struct { + eventCtor map[string]messageCtor + requestCtor map[string]messageCtor + responseCtor map[string]messageCtor +} + +// NewCodec constructs a new codec that extends the vanilla DAP protocol. +// Unless you need to register custom DAP messages, use +// DecodeProtocolMessage instead. +func NewCodec() *Codec { + ret := &Codec{ + eventCtor: make(map[string]messageCtor), + requestCtor: make(map[string]messageCtor), + responseCtor: make(map[string]messageCtor), + } + for k, v := range eventCtor { + ret.eventCtor[k] = v + } + for k, v := range requestCtor { + ret.requestCtor[k] = v + } + for k, v := range responseCtor { + ret.responseCtor[k] = v + } + return ret +} + +// RegisterRequest registers a new custom DAP command, so that it can be +// unmarshalled by DecodeMessage. Returns an error when the command already +// exists. +// +// The ctor functions need to return a new instance of the underlying DAP +// message type. A typical usage looks like this: +// +// reqCtor := func() Message { return &LaunchRequest{} } +// respCtor := func() Message { return &LaunchResponse{} } +// codec.RegisterRequest("launch", reqCtor, respCtor) +func (c *Codec) RegisterRequest(command string, requestCtor, responseCtor func() Message) error { + _, hasReqCtor := c.requestCtor[command] + _, hasRespCtor := c.responseCtor[command] + if hasReqCtor || hasRespCtor { + return fmt.Errorf("command %q is already registered", command) + } + c.requestCtor[command] = requestCtor + c.responseCtor[command] = responseCtor + return nil +} + +// RegisterEvent registers a new custom DAP event, so that it can be +// unmarshalled by DecodeMessage. Returns an error when the event already +// exists. +// +// The ctor function needs to return a new instance of the underlying DAP +// message type. A typical usage looks like this: +// +// ctor := func() Message { return &StoppedEvent{} } +// codec.RegisterEvent("stopped", ctor) +func (c *Codec) RegisterEvent(event string, ctor func() Message) error { + if _, hasEventCtor := c.eventCtor[event]; hasEventCtor { + return fmt.Errorf("event %q is already registered", event) + } + c.eventCtor[event] = ctor + return nil +} + +// DecodeMessage parses the JSON-encoded data and returns the result of +// the appropriate type within the ProtocolMessage hierarchy. If message type, +// command, etc cannot be cast, returns DecodeProtocolMessageFieldError. +// See also godoc for json.Unmarshal, which is used for underlying decoding. +func (c *Codec) DecodeMessage(data []byte) (Message, error) { + // This struct is the union of the ResponseMessage, RequestMessage, and + // EventMessage types. It is an optimization that saves an additional + // json.Unmarshal call. + var m struct { + ProtocolMessage + Command string `json:"command"` + Event string `json:"event"` + Success bool `json:"success"` + } + if err := json.Unmarshal(data, &m); err != nil { + return nil, err + } + switch m.Type { + case "request": + return c.decodeRequest(m.Command, m.Seq, data) + case "response": + return c.decodeResponse(m.Command, m.Seq, m.Success, data) + case "event": + return c.decodeEvent(m.Event, m.Seq, data) + default: + return nil, &DecodeProtocolMessageFieldError{m.Seq, "ProtocolMessage", "type", m.Type, json.RawMessage(data)} + } +} + +// decodeRequest determines what request type in the ProtocolMessage hierarchy +// data corresponds to and uses json.Unmarshal to populate the corresponding +// struct to be returned. +func (c *Codec) decodeRequest(command string, seq int, data []byte) (Message, error) { + ctor, ok := c.requestCtor[command] + if !ok { + return nil, &DecodeProtocolMessageFieldError{seq, "Request", "command", command, json.RawMessage(data)} + } + requestPtr := ctor() + err := json.Unmarshal(data, requestPtr) + return requestPtr, err +} + +// decodeResponse determines what response type in the ProtocolMessage hierarchy +// data corresponds to and uses json.Unmarshal to populate the corresponding +// struct to be returned. +func (c *Codec) decodeResponse(command string, seq int, success bool, data []byte) (Message, error) { + if !success { + var er ErrorResponse + err := json.Unmarshal(data, &er) + return &er, err + } + ctor, ok := c.responseCtor[command] + if !ok { + return nil, &DecodeProtocolMessageFieldError{seq, "Response", "command", command, json.RawMessage(data)} + } + responsePtr := ctor() + err := json.Unmarshal(data, responsePtr) + return responsePtr, err +} + +// decodeEvent determines what event type in the ProtocolMessage hierarchy +// data corresponds to and uses json.Unmarshal to populate the corresponding +// struct to be returned. +func (c *Codec) decodeEvent(event string, seq int, data []byte) (Message, error) { + ctor, ok := c.eventCtor[event] + if !ok { + return nil, &DecodeProtocolMessageFieldError{seq, "Event", "event", event, json.RawMessage(data)} + } + eventPtr := ctor() + err := json.Unmarshal(data, eventPtr) + return eventPtr, err +} + +// DecodeProtocolMessage parses the JSON-encoded ProtocolMessage and returns +// the message embedded in it. If message type, command, etc cannot be cast, +// returns DecodeProtocolMessageFieldError. See also godoc for json.Unmarshal, +// which is used for underlying decoding. +func DecodeProtocolMessage(data []byte) (Message, error) { + return defaultCodec.DecodeMessage(data) +} + +type messageCtor func() Message diff --git a/vendor/github.com/google/go-dap/doc.go b/vendor/github.com/google/go-dap/doc.go new file mode 100644 index 000000000000..95cb28f9ca24 --- /dev/null +++ b/vendor/github.com/google/go-dap/doc.go @@ -0,0 +1,20 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package dap contains data types and code for Debug Adapter Protocol (DAP) specification. +// https://github.com/microsoft/vscode-debugadapter-node/blob/main/debugProtocol.json +package dap + +//go:generate go run ./cmd/gentypes/gentypes.go -o schematypes.go -u cmd/gentypes/debugProtocol.json + diff --git a/vendor/github.com/google/go-dap/io.go b/vendor/github.com/google/go-dap/io.go new file mode 100644 index 000000000000..87125ef24ffc --- /dev/null +++ b/vendor/github.com/google/go-dap/io.go @@ -0,0 +1,137 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file contains utilities for DAP Base protocol I/O. +// For additional information, see "Base protocol" section in +// https://microsoft.github.io/debug-adapter-protocol/overview. + +package dap + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "regexp" + "strconv" + "strings" +) + +// BaseProtocolError represents base protocol error, which occurs when the raw +// message does not conform to the header+content format of the base protocol. +type BaseProtocolError struct { + Err string +} + +func (bpe *BaseProtocolError) Error() string { return bpe.Err } + +var ( + // ErrHeaderDelimiterNotCrLfCrLf is returned when only partial header + // delimiter \r\n\r\n is encountered. + ErrHeaderDelimiterNotCrLfCrLf = &BaseProtocolError{fmt.Sprintf("header delimiter is not %q", crLfcrLf)} + + // ErrHeaderNotContentLength is returned when the parsed header is + // not of valid Content-Length format. + ErrHeaderNotContentLength = &BaseProtocolError{fmt.Sprintf("header format is not %q", contentLengthHeaderRegex)} + + // ErrHeaderContentTooLong is returned when the content length specified in + // the header is above contentMaxLength. + ErrHeaderContentTooLong = &BaseProtocolError{fmt.Sprintf("content length over %v bytes", contentMaxLength)} +) + +const ( + crLfcrLf = "\r\n\r\n" + contentLengthHeaderFmt = "Content-Length: %d\r\n\r\n" + contentMaxLength = 4 * 1024 * 1024 +) + +var ( + contentLengthHeaderRegex = regexp.MustCompile("^Content-Length: ([0-9]+)$") +) + +// WriteBaseMessage formats content with Content-Length header and delimiters +// as per the base protocol and writes the resulting message to w. +func WriteBaseMessage(w io.Writer, content []byte) error { + header := fmt.Sprintf(contentLengthHeaderFmt, len(content)) + if _, err := w.Write([]byte(header)); err != nil { + return err + } + _, err := w.Write(content) + return err +} + +// ReadBaseMessage reads one message from r consisting of a Content-Length +// header and a content part. It parses the header to determine the size of +// the content part and extracts and returns the actual content of the message. +// Returns nil bytes on error, which can be one of the standard IO errors or +// a BaseProtocolError defined in this package. +func ReadBaseMessage(r *bufio.Reader) ([]byte, error) { + contentLength, err := readContentLengthHeader(r) + if err != nil { + return nil, err + } + if contentLength > contentMaxLength { + return nil, ErrHeaderContentTooLong + } + content := make([]byte, contentLength) + if _, err = io.ReadFull(r, content); err != nil { + return nil, err + } + return content, nil +} + +// readContentLengthHeader looks for the only header field that is supported +// and required: +// Content-Length: [0-9]+\r\n\r\n +// Extracts and returns the content length. +func readContentLengthHeader(r *bufio.Reader) (contentLength int64, err error) { + // Look for \r\n\r\n + headerWithCr, err := r.ReadString('\r') + if err != nil { + return 0, err + } + nextThree := make([]byte, 3) + if _, err = io.ReadFull(r, nextThree); err != nil { + return 0, err + } + if string(nextThree) != "\n\r\n" { + return 0, ErrHeaderDelimiterNotCrLfCrLf + } + + // If header is in the right format, get the length + header := strings.TrimSuffix(headerWithCr, "\r") + headerAndLength := contentLengthHeaderRegex.FindStringSubmatch(header) + if len(headerAndLength) < 2 { + return 0, ErrHeaderNotContentLength + } + return strconv.ParseInt(headerAndLength[1], 10, 64) +} + +// WriteProtocolMessage encodes message and writes it to w. +func WriteProtocolMessage(w io.Writer, message Message) error { + b, err := json.Marshal(message) + if err != nil { + return err + } + return WriteBaseMessage(w, b) +} + +// ReadProtocolMessage reads a message from r, decodes and returns it. +func ReadProtocolMessage(r *bufio.Reader) (Message, error) { + content, err := ReadBaseMessage(r) + if err != nil { + return nil, err + } + return DecodeProtocolMessage(content) +} diff --git a/vendor/github.com/google/go-dap/schematypes.go b/vendor/github.com/google/go-dap/schematypes.go new file mode 100644 index 000000000000..1f360c9a8b6b --- /dev/null +++ b/vendor/github.com/google/go-dap/schematypes.go @@ -0,0 +1,1917 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by "cmd/gentypes/gentypes.go"; DO NOT EDIT. +// DAP spec: https://microsoft.github.io/debug-adapter-protocol/specification +// See cmd/gentypes/README.md for additional details. + +package dap + +import "encoding/json" + +// Message is an interface that all DAP message types implement with pointer +// receivers. It's not part of the protocol but is used to enforce static +// typing in Go code and provide some common accessors. +// +// Note: the DAP type "Message" (which is used in the body of ErrorResponse) +// is renamed to ErrorMessage to avoid collision with this interface. +type Message interface { + GetSeq() int +} + +// RequestMessage is an interface implemented by all Request-types. +type RequestMessage interface { + Message + // GetRequest provides access to the embedded Request. + GetRequest() *Request +} + +// ResponseMessage is an interface implemented by all Response-types. +type ResponseMessage interface { + Message + // GetResponse provides access to the embedded Response. + GetResponse() *Response +} + +// EventMessage is an interface implemented by all Event-types. +type EventMessage interface { + Message + // GetEvent provides access to the embedded Event. + GetEvent() *Event +} + +// LaunchAttachRequest is an interface implemented by +// LaunchRequest and AttachRequest as they contain shared +// implementation specific arguments that are not part of +// the specification. +type LaunchAttachRequest interface { + RequestMessage + // GetArguments provides access to the Arguments map. + GetArguments() json.RawMessage +} + +// ProtocolMessage: Base class of requests, responses, and events. +type ProtocolMessage struct { + Seq int `json:"seq"` + Type string `json:"type"` +} + +func (m *ProtocolMessage) GetSeq() int { return m.Seq } + +// Request: A client or debug adapter initiated request. +type Request struct { + ProtocolMessage + + Command string `json:"command"` +} + +func (r *Request) GetRequest() *Request { return r } + +// Event: A debug adapter initiated event. +type Event struct { + ProtocolMessage + + Event string `json:"event"` +} + +func (e *Event) GetEvent() *Event { return e } + +// Response: Response for a request. +type Response struct { + ProtocolMessage + + RequestSeq int `json:"request_seq"` + Success bool `json:"success"` + Command string `json:"command"` + Message string `json:"message,omitempty"` +} + +func (r *Response) GetResponse() *Response { return r } + +// ErrorResponse: On error (whenever `success` is false), the body can provide more details. +type ErrorResponse struct { + Response + + Body ErrorResponseBody `json:"body"` +} + +type ErrorResponseBody struct { + Error *ErrorMessage `json:"error,omitempty"` +} + +// CancelRequest: The `cancel` request is used by the client in two situations: +// - to indicate that it is no longer interested in the result produced by a specific request issued earlier +// - to cancel a progress sequence. Clients should only call this request if the corresponding capability `supportsCancelRequest` is true. +// This request has a hint characteristic: a debug adapter can only be expected to make a 'best effort' in honoring this request but there are no guarantees. +// The `cancel` request may return an error if it could not cancel an operation but a client should refrain from presenting this error to end users. +// The request that got cancelled still needs to send a response back. This can either be a normal result (`success` attribute true) or an error response (`success` attribute false and the `message` set to `cancelled`). +// Returning partial results from a cancelled request is possible but please note that a client has no generic way for detecting that a response is partial or not. +// The progress that got cancelled still needs to send a `progressEnd` event back. +// +// A client should not assume that progress just got cancelled after sending the `cancel` request. +type CancelRequest struct { + Request + + Arguments *CancelArguments `json:"arguments,omitempty"` +} + +// CancelArguments: Arguments for `cancel` request. +type CancelArguments struct { + RequestId int `json:"requestId,omitempty"` + ProgressId string `json:"progressId,omitempty"` +} + +// CancelResponse: Response to `cancel` request. This is just an acknowledgement, so no body field is required. +type CancelResponse struct { + Response +} + +// InitializedEvent: This event indicates that the debug adapter is ready to accept configuration requests (e.g. `setBreakpoints`, `setExceptionBreakpoints`). +// A debug adapter is expected to send this event when it is ready to accept configuration requests (but not before the `initialize` request has finished). +// The sequence of events/requests is as follows: +// - adapters sends `initialized` event (after the `initialize` request has returned) +// - client sends zero or more `setBreakpoints` requests +// - client sends one `setFunctionBreakpoints` request (if corresponding capability `supportsFunctionBreakpoints` is true) +// - client sends a `setExceptionBreakpoints` request if one or more `exceptionBreakpointFilters` have been defined (or if `supportsConfigurationDoneRequest` is not true) +// - client sends other future configuration requests +// - client sends one `configurationDone` request to indicate the end of the configuration. +type InitializedEvent struct { + Event +} + +// StoppedEvent: The event indicates that the execution of the debuggee has stopped due to some condition. +// This can be caused by a breakpoint previously set, a stepping request has completed, by executing a debugger statement etc. +type StoppedEvent struct { + Event + + Body StoppedEventBody `json:"body"` +} + +type StoppedEventBody struct { + Reason string `json:"reason"` + Description string `json:"description,omitempty"` + ThreadId int `json:"threadId,omitempty"` + PreserveFocusHint bool `json:"preserveFocusHint,omitempty"` + Text string `json:"text,omitempty"` + AllThreadsStopped bool `json:"allThreadsStopped,omitempty"` + HitBreakpointIds []int `json:"hitBreakpointIds,omitempty"` +} + +// ContinuedEvent: The event indicates that the execution of the debuggee has continued. +// Please note: a debug adapter is not expected to send this event in response to a request that implies that execution continues, e.g. `launch` or `continue`. +// It is only necessary to send a `continued` event if there was no previous request that implied this. +type ContinuedEvent struct { + Event + + Body ContinuedEventBody `json:"body"` +} + +type ContinuedEventBody struct { + ThreadId int `json:"threadId"` + AllThreadsContinued bool `json:"allThreadsContinued,omitempty"` +} + +// ExitedEvent: The event indicates that the debuggee has exited and returns its exit code. +type ExitedEvent struct { + Event + + Body ExitedEventBody `json:"body"` +} + +type ExitedEventBody struct { + ExitCode int `json:"exitCode"` +} + +// TerminatedEvent: The event indicates that debugging of the debuggee has terminated. This does **not** mean that the debuggee itself has exited. +type TerminatedEvent struct { + Event + + Body TerminatedEventBody `json:"body,omitempty"` +} + +type TerminatedEventBody struct { + Restart json.RawMessage `json:"restart,omitempty"` +} + +// ThreadEvent: The event indicates that a thread has started or exited. +type ThreadEvent struct { + Event + + Body ThreadEventBody `json:"body"` +} + +type ThreadEventBody struct { + Reason string `json:"reason"` + ThreadId int `json:"threadId"` +} + +// OutputEvent: The event indicates that the target has produced some output. +type OutputEvent struct { + Event + + Body OutputEventBody `json:"body"` +} + +type OutputEventBody struct { + Category string `json:"category,omitempty"` + Output string `json:"output"` + Group string `json:"group,omitempty"` + VariablesReference int `json:"variablesReference,omitempty"` + Source *Source `json:"source,omitempty"` + Line int `json:"line,omitempty"` + Column int `json:"column,omitempty"` + Data json.RawMessage `json:"data,omitempty"` +} + +// BreakpointEvent: The event indicates that some information about a breakpoint has changed. +type BreakpointEvent struct { + Event + + Body BreakpointEventBody `json:"body"` +} + +type BreakpointEventBody struct { + Reason string `json:"reason"` + Breakpoint Breakpoint `json:"breakpoint"` +} + +// ModuleEvent: The event indicates that some information about a module has changed. +type ModuleEvent struct { + Event + + Body ModuleEventBody `json:"body"` +} + +type ModuleEventBody struct { + Reason string `json:"reason"` + Module Module `json:"module"` +} + +// LoadedSourceEvent: The event indicates that some source has been added, changed, or removed from the set of all loaded sources. +type LoadedSourceEvent struct { + Event + + Body LoadedSourceEventBody `json:"body"` +} + +type LoadedSourceEventBody struct { + Reason string `json:"reason"` + Source Source `json:"source"` +} + +// ProcessEvent: The event indicates that the debugger has begun debugging a new process. Either one that it has launched, or one that it has attached to. +type ProcessEvent struct { + Event + + Body ProcessEventBody `json:"body"` +} + +type ProcessEventBody struct { + Name string `json:"name"` + SystemProcessId int `json:"systemProcessId,omitempty"` + IsLocalProcess bool `json:"isLocalProcess,omitempty"` + StartMethod string `json:"startMethod,omitempty"` + PointerSize int `json:"pointerSize,omitempty"` +} + +// CapabilitiesEvent: The event indicates that one or more capabilities have changed. +// Since the capabilities are dependent on the client and its UI, it might not be possible to change that at random times (or too late). +// Consequently this event has a hint characteristic: a client can only be expected to make a 'best effort' in honoring individual capabilities but there are no guarantees. +// Only changed capabilities need to be included, all other capabilities keep their values. +type CapabilitiesEvent struct { + Event + + Body CapabilitiesEventBody `json:"body"` +} + +type CapabilitiesEventBody struct { + Capabilities Capabilities `json:"capabilities"` +} + +// ProgressStartEvent: The event signals that a long running operation is about to start and provides additional information for the client to set up a corresponding progress and cancellation UI. +// The client is free to delay the showing of the UI in order to reduce flicker. +// This event should only be sent if the corresponding capability `supportsProgressReporting` is true. +type ProgressStartEvent struct { + Event + + Body ProgressStartEventBody `json:"body"` +} + +type ProgressStartEventBody struct { + ProgressId string `json:"progressId"` + Title string `json:"title"` + RequestId int `json:"requestId,omitempty"` + Cancellable bool `json:"cancellable,omitempty"` + Message string `json:"message,omitempty"` + Percentage int `json:"percentage,omitempty"` +} + +// ProgressUpdateEvent: The event signals that the progress reporting needs to be updated with a new message and/or percentage. +// The client does not have to update the UI immediately, but the clients needs to keep track of the message and/or percentage values. +// This event should only be sent if the corresponding capability `supportsProgressReporting` is true. +type ProgressUpdateEvent struct { + Event + + Body ProgressUpdateEventBody `json:"body"` +} + +type ProgressUpdateEventBody struct { + ProgressId string `json:"progressId"` + Message string `json:"message,omitempty"` + Percentage int `json:"percentage,omitempty"` +} + +// ProgressEndEvent: The event signals the end of the progress reporting with a final message. +// This event should only be sent if the corresponding capability `supportsProgressReporting` is true. +type ProgressEndEvent struct { + Event + + Body ProgressEndEventBody `json:"body"` +} + +type ProgressEndEventBody struct { + ProgressId string `json:"progressId"` + Message string `json:"message,omitempty"` +} + +// InvalidatedEvent: This event signals that some state in the debug adapter has changed and requires that the client needs to re-render the data snapshot previously requested. +// Debug adapters do not have to emit this event for runtime changes like stopped or thread events because in that case the client refetches the new state anyway. But the event can be used for example to refresh the UI after rendering formatting has changed in the debug adapter. +// This event should only be sent if the corresponding capability `supportsInvalidatedEvent` is true. +type InvalidatedEvent struct { + Event + + Body InvalidatedEventBody `json:"body"` +} + +type InvalidatedEventBody struct { + Areas []InvalidatedAreas `json:"areas,omitempty"` + ThreadId int `json:"threadId,omitempty"` + StackFrameId int `json:"stackFrameId,omitempty"` +} + +// MemoryEvent: This event indicates that some memory range has been updated. It should only be sent if the corresponding capability `supportsMemoryEvent` is true. +// Clients typically react to the event by re-issuing a `readMemory` request if they show the memory identified by the `memoryReference` and if the updated memory range overlaps the displayed range. Clients should not make assumptions how individual memory references relate to each other, so they should not assume that they are part of a single continuous address range and might overlap. +// Debug adapters can use this event to indicate that the contents of a memory range has changed due to some other request like `setVariable` or `setExpression`. Debug adapters are not expected to emit this event for each and every memory change of a running program, because that information is typically not available from debuggers and it would flood clients with too many events. +type MemoryEvent struct { + Event + + Body MemoryEventBody `json:"body"` +} + +type MemoryEventBody struct { + MemoryReference string `json:"memoryReference"` + Offset int `json:"offset"` + Count int `json:"count"` +} + +// RunInTerminalRequest: This request is sent from the debug adapter to the client to run a command in a terminal. +// This is typically used to launch the debuggee in a terminal provided by the client. +// This request should only be called if the corresponding client capability `supportsRunInTerminalRequest` is true. +// Client implementations of `runInTerminal` are free to run the command however they choose including issuing the command to a command line interpreter (aka 'shell'). Argument strings passed to the `runInTerminal` request must arrive verbatim in the command to be run. As a consequence, clients which use a shell are responsible for escaping any special shell characters in the argument strings to prevent them from being interpreted (and modified) by the shell. +// Some users may wish to take advantage of shell processing in the argument strings. For clients which implement `runInTerminal` using an intermediary shell, the `argsCanBeInterpretedByShell` property can be set to true. In this case the client is requested not to escape any special shell characters in the argument strings. +type RunInTerminalRequest struct { + Request + + Arguments RunInTerminalRequestArguments `json:"arguments"` +} + +// RunInTerminalRequestArguments: Arguments for `runInTerminal` request. +type RunInTerminalRequestArguments struct { + Kind string `json:"kind,omitempty"` + Title string `json:"title,omitempty"` + Cwd string `json:"cwd"` + Args []string `json:"args"` + Env map[string]any `json:"env,omitempty"` + ArgsCanBeInterpretedByShell bool `json:"argsCanBeInterpretedByShell,omitempty"` +} + +// RunInTerminalResponse: Response to `runInTerminal` request. +type RunInTerminalResponse struct { + Response + + Body RunInTerminalResponseBody `json:"body"` +} + +type RunInTerminalResponseBody struct { + ProcessId int `json:"processId,omitempty"` + ShellProcessId int `json:"shellProcessId,omitempty"` +} + +// StartDebuggingRequest: This request is sent from the debug adapter to the client to start a new debug session of the same type as the caller. +// This request should only be sent if the corresponding client capability `supportsStartDebuggingRequest` is true. +// A client implementation of `startDebugging` should start a new debug session (of the same type as the caller) in the same way that the caller's session was started. If the client supports hierarchical debug sessions, the newly created session can be treated as a child of the caller session. +type StartDebuggingRequest struct { + Request + + Arguments StartDebuggingRequestArguments `json:"arguments"` +} + +// StartDebuggingRequestArguments: Arguments for `startDebugging` request. +type StartDebuggingRequestArguments struct { + Configuration map[string]any `json:"configuration"` + Request string `json:"request"` +} + +// StartDebuggingResponse: Response to `startDebugging` request. This is just an acknowledgement, so no body field is required. +type StartDebuggingResponse struct { + Response +} + +// InitializeRequest: The `initialize` request is sent as the first request from the client to the debug adapter in order to configure it with client capabilities and to retrieve capabilities from the debug adapter. +// Until the debug adapter has responded with an `initialize` response, the client must not send any additional requests or events to the debug adapter. +// In addition the debug adapter is not allowed to send any requests or events to the client until it has responded with an `initialize` response. +// The `initialize` request may only be sent once. +type InitializeRequest struct { + Request + + Arguments InitializeRequestArguments `json:"arguments"` +} + +// InitializeRequestArguments: Arguments for `initialize` request. +type InitializeRequestArguments struct { + ClientID string `json:"clientID,omitempty"` + ClientName string `json:"clientName,omitempty"` + AdapterID string `json:"adapterID"` + Locale string `json:"locale,omitempty"` + LinesStartAt1 bool `json:"linesStartAt1"` + ColumnsStartAt1 bool `json:"columnsStartAt1"` + PathFormat string `json:"pathFormat,omitempty"` + SupportsVariableType bool `json:"supportsVariableType,omitempty"` + SupportsVariablePaging bool `json:"supportsVariablePaging,omitempty"` + SupportsRunInTerminalRequest bool `json:"supportsRunInTerminalRequest,omitempty"` + SupportsMemoryReferences bool `json:"supportsMemoryReferences,omitempty"` + SupportsProgressReporting bool `json:"supportsProgressReporting,omitempty"` + SupportsInvalidatedEvent bool `json:"supportsInvalidatedEvent,omitempty"` + SupportsMemoryEvent bool `json:"supportsMemoryEvent,omitempty"` + SupportsArgsCanBeInterpretedByShell bool `json:"supportsArgsCanBeInterpretedByShell,omitempty"` + SupportsStartDebuggingRequest bool `json:"supportsStartDebuggingRequest,omitempty"` +} + +// InitializeResponse: Response to `initialize` request. +type InitializeResponse struct { + Response + + Body Capabilities `json:"body,omitempty"` +} + +// ConfigurationDoneRequest: This request indicates that the client has finished initialization of the debug adapter. +// So it is the last request in the sequence of configuration requests (which was started by the `initialized` event). +// Clients should only call this request if the corresponding capability `supportsConfigurationDoneRequest` is true. +type ConfigurationDoneRequest struct { + Request + + Arguments *ConfigurationDoneArguments `json:"arguments,omitempty"` +} + +// ConfigurationDoneArguments: Arguments for `configurationDone` request. +type ConfigurationDoneArguments struct { +} + +// ConfigurationDoneResponse: Response to `configurationDone` request. This is just an acknowledgement, so no body field is required. +type ConfigurationDoneResponse struct { + Response +} + +// LaunchRequest: This launch request is sent from the client to the debug adapter to start the debuggee with or without debugging (if `noDebug` is true). +// Since launching is debugger/runtime specific, the arguments for this request are not part of this specification. +type LaunchRequest struct { + Request + + Arguments json.RawMessage `json:"arguments"` +} + +func (r *LaunchRequest) GetArguments() json.RawMessage { return r.Arguments } + +// LaunchResponse: Response to `launch` request. This is just an acknowledgement, so no body field is required. +type LaunchResponse struct { + Response +} + +// AttachRequest: The `attach` request is sent from the client to the debug adapter to attach to a debuggee that is already running. +// Since attaching is debugger/runtime specific, the arguments for this request are not part of this specification. +type AttachRequest struct { + Request + + Arguments json.RawMessage `json:"arguments"` +} + +func (r *AttachRequest) GetArguments() json.RawMessage { return r.Arguments } + +// AttachResponse: Response to `attach` request. This is just an acknowledgement, so no body field is required. +type AttachResponse struct { + Response +} + +// RestartRequest: Restarts a debug session. Clients should only call this request if the corresponding capability `supportsRestartRequest` is true. +// If the capability is missing or has the value false, a typical client emulates `restart` by terminating the debug adapter first and then launching it anew. +type RestartRequest struct { + Request + + Arguments json.RawMessage `json:"arguments"` +} + +// RestartResponse: Response to `restart` request. This is just an acknowledgement, so no body field is required. +type RestartResponse struct { + Response +} + +// DisconnectRequest: The `disconnect` request asks the debug adapter to disconnect from the debuggee (thus ending the debug session) and then to shut down itself (the debug adapter). +// In addition, the debug adapter must terminate the debuggee if it was started with the `launch` request. If an `attach` request was used to connect to the debuggee, then the debug adapter must not terminate the debuggee. +// This implicit behavior of when to terminate the debuggee can be overridden with the `terminateDebuggee` argument (which is only supported by a debug adapter if the corresponding capability `supportTerminateDebuggee` is true). +type DisconnectRequest struct { + Request + + Arguments *DisconnectArguments `json:"arguments,omitempty"` +} + +// DisconnectArguments: Arguments for `disconnect` request. +type DisconnectArguments struct { + Restart bool `json:"restart,omitempty"` + TerminateDebuggee bool `json:"terminateDebuggee,omitempty"` + SuspendDebuggee bool `json:"suspendDebuggee,omitempty"` +} + +// DisconnectResponse: Response to `disconnect` request. This is just an acknowledgement, so no body field is required. +type DisconnectResponse struct { + Response +} + +// TerminateRequest: The `terminate` request is sent from the client to the debug adapter in order to shut down the debuggee gracefully. Clients should only call this request if the capability `supportsTerminateRequest` is true. +// Typically a debug adapter implements `terminate` by sending a software signal which the debuggee intercepts in order to clean things up properly before terminating itself. +// Please note that this request does not directly affect the state of the debug session: if the debuggee decides to veto the graceful shutdown for any reason by not terminating itself, then the debug session just continues. +// Clients can surface the `terminate` request as an explicit command or they can integrate it into a two stage Stop command that first sends `terminate` to request a graceful shutdown, and if that fails uses `disconnect` for a forceful shutdown. +type TerminateRequest struct { + Request + + Arguments *TerminateArguments `json:"arguments,omitempty"` +} + +// TerminateArguments: Arguments for `terminate` request. +type TerminateArguments struct { + Restart bool `json:"restart,omitempty"` +} + +// TerminateResponse: Response to `terminate` request. This is just an acknowledgement, so no body field is required. +type TerminateResponse struct { + Response +} + +// BreakpointLocationsRequest: The `breakpointLocations` request returns all possible locations for source breakpoints in a given range. +// Clients should only call this request if the corresponding capability `supportsBreakpointLocationsRequest` is true. +type BreakpointLocationsRequest struct { + Request + + Arguments *BreakpointLocationsArguments `json:"arguments,omitempty"` +} + +// BreakpointLocationsArguments: Arguments for `breakpointLocations` request. +type BreakpointLocationsArguments struct { + Source Source `json:"source"` + Line int `json:"line"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` +} + +// BreakpointLocationsResponse: Response to `breakpointLocations` request. +// Contains possible locations for source breakpoints. +type BreakpointLocationsResponse struct { + Response + + Body BreakpointLocationsResponseBody `json:"body"` +} + +type BreakpointLocationsResponseBody struct { + Breakpoints []BreakpointLocation `json:"breakpoints"` +} + +// SetBreakpointsRequest: Sets multiple breakpoints for a single source and clears all previous breakpoints in that source. +// To clear all breakpoint for a source, specify an empty array. +// When a breakpoint is hit, a `stopped` event (with reason `breakpoint`) is generated. +type SetBreakpointsRequest struct { + Request + + Arguments SetBreakpointsArguments `json:"arguments"` +} + +// SetBreakpointsArguments: Arguments for `setBreakpoints` request. +type SetBreakpointsArguments struct { + Source Source `json:"source"` + Breakpoints []SourceBreakpoint `json:"breakpoints,omitempty"` + Lines []int `json:"lines,omitempty"` + SourceModified bool `json:"sourceModified,omitempty"` +} + +// SetBreakpointsResponse: Response to `setBreakpoints` request. +// Returned is information about each breakpoint created by this request. +// This includes the actual code location and whether the breakpoint could be verified. +// The breakpoints returned are in the same order as the elements of the `breakpoints` +// (or the deprecated `lines`) array in the arguments. +type SetBreakpointsResponse struct { + Response + + Body SetBreakpointsResponseBody `json:"body"` +} + +type SetBreakpointsResponseBody struct { + Breakpoints []Breakpoint `json:"breakpoints"` +} + +// SetFunctionBreakpointsRequest: Replaces all existing function breakpoints with new function breakpoints. +// To clear all function breakpoints, specify an empty array. +// When a function breakpoint is hit, a `stopped` event (with reason `function breakpoint`) is generated. +// Clients should only call this request if the corresponding capability `supportsFunctionBreakpoints` is true. +type SetFunctionBreakpointsRequest struct { + Request + + Arguments SetFunctionBreakpointsArguments `json:"arguments"` +} + +// SetFunctionBreakpointsArguments: Arguments for `setFunctionBreakpoints` request. +type SetFunctionBreakpointsArguments struct { + Breakpoints []FunctionBreakpoint `json:"breakpoints"` +} + +// SetFunctionBreakpointsResponse: Response to `setFunctionBreakpoints` request. +// Returned is information about each breakpoint created by this request. +type SetFunctionBreakpointsResponse struct { + Response + + Body SetFunctionBreakpointsResponseBody `json:"body"` +} + +type SetFunctionBreakpointsResponseBody struct { + Breakpoints []Breakpoint `json:"breakpoints"` +} + +// SetExceptionBreakpointsRequest: The request configures the debugger's response to thrown exceptions. +// If an exception is configured to break, a `stopped` event is fired (with reason `exception`). +// Clients should only call this request if the corresponding capability `exceptionBreakpointFilters` returns one or more filters. +type SetExceptionBreakpointsRequest struct { + Request + + Arguments SetExceptionBreakpointsArguments `json:"arguments"` +} + +// SetExceptionBreakpointsArguments: Arguments for `setExceptionBreakpoints` request. +type SetExceptionBreakpointsArguments struct { + Filters []string `json:"filters"` + FilterOptions []ExceptionFilterOptions `json:"filterOptions,omitempty"` + ExceptionOptions []ExceptionOptions `json:"exceptionOptions,omitempty"` +} + +// SetExceptionBreakpointsResponse: Response to `setExceptionBreakpoints` request. +// The response contains an array of `Breakpoint` objects with information about each exception breakpoint or filter. The `Breakpoint` objects are in the same order as the elements of the `filters`, `filterOptions`, `exceptionOptions` arrays given as arguments. If both `filters` and `filterOptions` are given, the returned array must start with `filters` information first, followed by `filterOptions` information. +// The `verified` property of a `Breakpoint` object signals whether the exception breakpoint or filter could be successfully created and whether the condition or hit count expressions are valid. In case of an error the `message` property explains the problem. The `id` property can be used to introduce a unique ID for the exception breakpoint or filter so that it can be updated subsequently by sending breakpoint events. +// For backward compatibility both the `breakpoints` array and the enclosing `body` are optional. If these elements are missing a client is not able to show problems for individual exception breakpoints or filters. +type SetExceptionBreakpointsResponse struct { + Response + + Body SetExceptionBreakpointsResponseBody `json:"body,omitempty"` +} + +type SetExceptionBreakpointsResponseBody struct { + Breakpoints []Breakpoint `json:"breakpoints,omitempty"` +} + +// DataBreakpointInfoRequest: Obtains information on a possible data breakpoint that could be set on an expression or variable. +// Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. +type DataBreakpointInfoRequest struct { + Request + + Arguments DataBreakpointInfoArguments `json:"arguments"` +} + +// DataBreakpointInfoArguments: Arguments for `dataBreakpointInfo` request. +type DataBreakpointInfoArguments struct { + VariablesReference int `json:"variablesReference,omitempty"` + Name string `json:"name"` + FrameId int `json:"frameId,omitempty"` +} + +// DataBreakpointInfoResponse: Response to `dataBreakpointInfo` request. +type DataBreakpointInfoResponse struct { + Response + + Body DataBreakpointInfoResponseBody `json:"body"` +} + +type DataBreakpointInfoResponseBody struct { + DataId any `json:"dataId"` + Description string `json:"description"` + AccessTypes []DataBreakpointAccessType `json:"accessTypes,omitempty"` + CanPersist bool `json:"canPersist,omitempty"` +} + +// SetDataBreakpointsRequest: Replaces all existing data breakpoints with new data breakpoints. +// To clear all data breakpoints, specify an empty array. +// When a data breakpoint is hit, a `stopped` event (with reason `data breakpoint`) is generated. +// Clients should only call this request if the corresponding capability `supportsDataBreakpoints` is true. +type SetDataBreakpointsRequest struct { + Request + + Arguments SetDataBreakpointsArguments `json:"arguments"` +} + +// SetDataBreakpointsArguments: Arguments for `setDataBreakpoints` request. +type SetDataBreakpointsArguments struct { + Breakpoints []DataBreakpoint `json:"breakpoints"` +} + +// SetDataBreakpointsResponse: Response to `setDataBreakpoints` request. +// Returned is information about each breakpoint created by this request. +type SetDataBreakpointsResponse struct { + Response + + Body SetDataBreakpointsResponseBody `json:"body"` +} + +type SetDataBreakpointsResponseBody struct { + Breakpoints []Breakpoint `json:"breakpoints"` +} + +// SetInstructionBreakpointsRequest: Replaces all existing instruction breakpoints. Typically, instruction breakpoints would be set from a disassembly window. +// To clear all instruction breakpoints, specify an empty array. +// When an instruction breakpoint is hit, a `stopped` event (with reason `instruction breakpoint`) is generated. +// Clients should only call this request if the corresponding capability `supportsInstructionBreakpoints` is true. +type SetInstructionBreakpointsRequest struct { + Request + + Arguments SetInstructionBreakpointsArguments `json:"arguments"` +} + +// SetInstructionBreakpointsArguments: Arguments for `setInstructionBreakpoints` request +type SetInstructionBreakpointsArguments struct { + Breakpoints []InstructionBreakpoint `json:"breakpoints"` +} + +// SetInstructionBreakpointsResponse: Response to `setInstructionBreakpoints` request +type SetInstructionBreakpointsResponse struct { + Response + + Body SetInstructionBreakpointsResponseBody `json:"body"` +} + +type SetInstructionBreakpointsResponseBody struct { + Breakpoints []Breakpoint `json:"breakpoints"` +} + +// ContinueRequest: The request resumes execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. +type ContinueRequest struct { + Request + + Arguments ContinueArguments `json:"arguments"` +} + +// ContinueArguments: Arguments for `continue` request. +type ContinueArguments struct { + ThreadId int `json:"threadId"` + SingleThread bool `json:"singleThread,omitempty"` +} + +// ContinueResponse: Response to `continue` request. +type ContinueResponse struct { + Response + + Body ContinueResponseBody `json:"body"` +} + +type ContinueResponseBody struct { + AllThreadsContinued bool `json:"allThreadsContinued"` +} + +// NextRequest: The request executes one step (in the given granularity) for the specified thread and allows all other threads to run freely by resuming them. +// If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. +// The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. +type NextRequest struct { + Request + + Arguments NextArguments `json:"arguments"` +} + +// NextArguments: Arguments for `next` request. +type NextArguments struct { + ThreadId int `json:"threadId"` + SingleThread bool `json:"singleThread,omitempty"` + Granularity SteppingGranularity `json:"granularity,omitempty"` +} + +// NextResponse: Response to `next` request. This is just an acknowledgement, so no body field is required. +type NextResponse struct { + Response +} + +// StepInRequest: The request resumes the given thread to step into a function/method and allows all other threads to run freely by resuming them. +// If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. +// If the request cannot step into a target, `stepIn` behaves like the `next` request. +// The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. +// If there are multiple function/method calls (or other targets) on the source line, +// the argument `targetId` can be used to control into which target the `stepIn` should occur. +// The list of possible targets for a given source line can be retrieved via the `stepInTargets` request. +type StepInRequest struct { + Request + + Arguments StepInArguments `json:"arguments"` +} + +// StepInArguments: Arguments for `stepIn` request. +type StepInArguments struct { + ThreadId int `json:"threadId"` + SingleThread bool `json:"singleThread,omitempty"` + TargetId int `json:"targetId,omitempty"` + Granularity SteppingGranularity `json:"granularity,omitempty"` +} + +// StepInResponse: Response to `stepIn` request. This is just an acknowledgement, so no body field is required. +type StepInResponse struct { + Response +} + +// StepOutRequest: The request resumes the given thread to step out (return) from a function/method and allows all other threads to run freely by resuming them. +// If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. +// The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. +type StepOutRequest struct { + Request + + Arguments StepOutArguments `json:"arguments"` +} + +// StepOutArguments: Arguments for `stepOut` request. +type StepOutArguments struct { + ThreadId int `json:"threadId"` + SingleThread bool `json:"singleThread,omitempty"` + Granularity SteppingGranularity `json:"granularity,omitempty"` +} + +// StepOutResponse: Response to `stepOut` request. This is just an acknowledgement, so no body field is required. +type StepOutResponse struct { + Response +} + +// StepBackRequest: The request executes one backward step (in the given granularity) for the specified thread and allows all other threads to run backward freely by resuming them. +// If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true prevents other suspended threads from resuming. +// The debug adapter first sends the response and then a `stopped` event (with reason `step`) after the step has completed. +// Clients should only call this request if the corresponding capability `supportsStepBack` is true. +type StepBackRequest struct { + Request + + Arguments StepBackArguments `json:"arguments"` +} + +// StepBackArguments: Arguments for `stepBack` request. +type StepBackArguments struct { + ThreadId int `json:"threadId"` + SingleThread bool `json:"singleThread,omitempty"` + Granularity SteppingGranularity `json:"granularity,omitempty"` +} + +// StepBackResponse: Response to `stepBack` request. This is just an acknowledgement, so no body field is required. +type StepBackResponse struct { + Response +} + +// ReverseContinueRequest: The request resumes backward execution of all threads. If the debug adapter supports single thread execution (see capability `supportsSingleThreadExecutionRequests`), setting the `singleThread` argument to true resumes only the specified thread. If not all threads were resumed, the `allThreadsContinued` attribute of the response should be set to false. +// Clients should only call this request if the corresponding capability `supportsStepBack` is true. +type ReverseContinueRequest struct { + Request + + Arguments ReverseContinueArguments `json:"arguments"` +} + +// ReverseContinueArguments: Arguments for `reverseContinue` request. +type ReverseContinueArguments struct { + ThreadId int `json:"threadId"` + SingleThread bool `json:"singleThread,omitempty"` +} + +// ReverseContinueResponse: Response to `reverseContinue` request. This is just an acknowledgement, so no body field is required. +type ReverseContinueResponse struct { + Response +} + +// RestartFrameRequest: The request restarts execution of the specified stack frame. +// The debug adapter first sends the response and then a `stopped` event (with reason `restart`) after the restart has completed. +// Clients should only call this request if the corresponding capability `supportsRestartFrame` is true. +type RestartFrameRequest struct { + Request + + Arguments RestartFrameArguments `json:"arguments"` +} + +// RestartFrameArguments: Arguments for `restartFrame` request. +type RestartFrameArguments struct { + FrameId int `json:"frameId"` +} + +// RestartFrameResponse: Response to `restartFrame` request. This is just an acknowledgement, so no body field is required. +type RestartFrameResponse struct { + Response +} + +// GotoRequest: The request sets the location where the debuggee will continue to run. +// This makes it possible to skip the execution of code or to execute code again. +// The code between the current location and the goto target is not executed but skipped. +// The debug adapter first sends the response and then a `stopped` event with reason `goto`. +// Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true (because only then goto targets exist that can be passed as arguments). +type GotoRequest struct { + Request + + Arguments GotoArguments `json:"arguments"` +} + +// GotoArguments: Arguments for `goto` request. +type GotoArguments struct { + ThreadId int `json:"threadId"` + TargetId int `json:"targetId"` +} + +// GotoResponse: Response to `goto` request. This is just an acknowledgement, so no body field is required. +type GotoResponse struct { + Response +} + +// PauseRequest: The request suspends the debuggee. +// The debug adapter first sends the response and then a `stopped` event (with reason `pause`) after the thread has been paused successfully. +type PauseRequest struct { + Request + + Arguments PauseArguments `json:"arguments"` +} + +// PauseArguments: Arguments for `pause` request. +type PauseArguments struct { + ThreadId int `json:"threadId"` +} + +// PauseResponse: Response to `pause` request. This is just an acknowledgement, so no body field is required. +type PauseResponse struct { + Response +} + +// StackTraceRequest: The request returns a stacktrace from the current execution state of a given thread. +// A client can request all stack frames by omitting the startFrame and levels arguments. For performance-conscious clients and if the corresponding capability `supportsDelayedStackTraceLoading` is true, stack frames can be retrieved in a piecemeal way with the `startFrame` and `levels` arguments. The response of the `stackTrace` request may contain a `totalFrames` property that hints at the total number of frames in the stack. If a client needs this total number upfront, it can issue a request for a single (first) frame and depending on the value of `totalFrames` decide how to proceed. In any case a client should be prepared to receive fewer frames than requested, which is an indication that the end of the stack has been reached. +type StackTraceRequest struct { + Request + + Arguments StackTraceArguments `json:"arguments"` +} + +// StackTraceArguments: Arguments for `stackTrace` request. +type StackTraceArguments struct { + ThreadId int `json:"threadId"` + StartFrame int `json:"startFrame,omitempty"` + Levels int `json:"levels,omitempty"` + Format *StackFrameFormat `json:"format,omitempty"` +} + +// StackTraceResponse: Response to `stackTrace` request. +type StackTraceResponse struct { + Response + + Body StackTraceResponseBody `json:"body"` +} + +type StackTraceResponseBody struct { + StackFrames []StackFrame `json:"stackFrames"` + TotalFrames int `json:"totalFrames,omitempty"` +} + +// ScopesRequest: The request returns the variable scopes for a given stack frame ID. +type ScopesRequest struct { + Request + + Arguments ScopesArguments `json:"arguments"` +} + +// ScopesArguments: Arguments for `scopes` request. +type ScopesArguments struct { + FrameId int `json:"frameId"` +} + +// ScopesResponse: Response to `scopes` request. +type ScopesResponse struct { + Response + + Body ScopesResponseBody `json:"body"` +} + +type ScopesResponseBody struct { + Scopes []Scope `json:"scopes"` +} + +// VariablesRequest: Retrieves all child variables for the given variable reference. +// A filter can be used to limit the fetched children to either named or indexed children. +type VariablesRequest struct { + Request + + Arguments VariablesArguments `json:"arguments"` +} + +// VariablesArguments: Arguments for `variables` request. +type VariablesArguments struct { + VariablesReference int `json:"variablesReference"` + Filter string `json:"filter,omitempty"` + Start int `json:"start,omitempty"` + Count int `json:"count,omitempty"` + Format *ValueFormat `json:"format,omitempty"` +} + +// VariablesResponse: Response to `variables` request. +type VariablesResponse struct { + Response + + Body VariablesResponseBody `json:"body"` +} + +type VariablesResponseBody struct { + Variables []Variable `json:"variables"` +} + +// SetVariableRequest: Set the variable with the given name in the variable container to a new value. Clients should only call this request if the corresponding capability `supportsSetVariable` is true. +// If a debug adapter implements both `setVariable` and `setExpression`, a client will only use `setExpression` if the variable has an `evaluateName` property. +type SetVariableRequest struct { + Request + + Arguments SetVariableArguments `json:"arguments"` +} + +// SetVariableArguments: Arguments for `setVariable` request. +type SetVariableArguments struct { + VariablesReference int `json:"variablesReference"` + Name string `json:"name"` + Value string `json:"value"` + Format *ValueFormat `json:"format,omitempty"` +} + +// SetVariableResponse: Response to `setVariable` request. +type SetVariableResponse struct { + Response + + Body SetVariableResponseBody `json:"body"` +} + +type SetVariableResponseBody struct { + Value string `json:"value"` + Type string `json:"type,omitempty"` + VariablesReference int `json:"variablesReference,omitempty"` + NamedVariables int `json:"namedVariables,omitempty"` + IndexedVariables int `json:"indexedVariables,omitempty"` +} + +// SourceRequest: The request retrieves the source code for a given source reference. +type SourceRequest struct { + Request + + Arguments SourceArguments `json:"arguments"` +} + +// SourceArguments: Arguments for `source` request. +type SourceArguments struct { + Source *Source `json:"source,omitempty"` + SourceReference int `json:"sourceReference"` +} + +// SourceResponse: Response to `source` request. +type SourceResponse struct { + Response + + Body SourceResponseBody `json:"body"` +} + +type SourceResponseBody struct { + Content string `json:"content"` + MimeType string `json:"mimeType,omitempty"` +} + +// ThreadsRequest: The request retrieves a list of all threads. +type ThreadsRequest struct { + Request +} + +// ThreadsResponse: Response to `threads` request. +type ThreadsResponse struct { + Response + + Body ThreadsResponseBody `json:"body"` +} + +type ThreadsResponseBody struct { + Threads []Thread `json:"threads"` +} + +// TerminateThreadsRequest: The request terminates the threads with the given ids. +// Clients should only call this request if the corresponding capability `supportsTerminateThreadsRequest` is true. +type TerminateThreadsRequest struct { + Request + + Arguments TerminateThreadsArguments `json:"arguments"` +} + +// TerminateThreadsArguments: Arguments for `terminateThreads` request. +type TerminateThreadsArguments struct { + ThreadIds []int `json:"threadIds,omitempty"` +} + +// TerminateThreadsResponse: Response to `terminateThreads` request. This is just an acknowledgement, no body field is required. +type TerminateThreadsResponse struct { + Response +} + +// ModulesRequest: Modules can be retrieved from the debug adapter with this request which can either return all modules or a range of modules to support paging. +// Clients should only call this request if the corresponding capability `supportsModulesRequest` is true. +type ModulesRequest struct { + Request + + Arguments ModulesArguments `json:"arguments"` +} + +// ModulesArguments: Arguments for `modules` request. +type ModulesArguments struct { + StartModule int `json:"startModule,omitempty"` + ModuleCount int `json:"moduleCount,omitempty"` +} + +// ModulesResponse: Response to `modules` request. +type ModulesResponse struct { + Response + + Body ModulesResponseBody `json:"body"` +} + +type ModulesResponseBody struct { + Modules []Module `json:"modules"` + TotalModules int `json:"totalModules,omitempty"` +} + +// LoadedSourcesRequest: Retrieves the set of all sources currently loaded by the debugged process. +// Clients should only call this request if the corresponding capability `supportsLoadedSourcesRequest` is true. +type LoadedSourcesRequest struct { + Request + + Arguments *LoadedSourcesArguments `json:"arguments,omitempty"` +} + +// LoadedSourcesArguments: Arguments for `loadedSources` request. +type LoadedSourcesArguments struct { +} + +// LoadedSourcesResponse: Response to `loadedSources` request. +type LoadedSourcesResponse struct { + Response + + Body LoadedSourcesResponseBody `json:"body"` +} + +type LoadedSourcesResponseBody struct { + Sources []Source `json:"sources"` +} + +// EvaluateRequest: Evaluates the given expression in the context of the topmost stack frame. +// The expression has access to any variables and arguments that are in scope. +type EvaluateRequest struct { + Request + + Arguments EvaluateArguments `json:"arguments"` +} + +// EvaluateArguments: Arguments for `evaluate` request. +type EvaluateArguments struct { + Expression string `json:"expression"` + FrameId int `json:"frameId,omitempty"` + Context string `json:"context,omitempty"` + Format *ValueFormat `json:"format,omitempty"` +} + +// EvaluateResponse: Response to `evaluate` request. +type EvaluateResponse struct { + Response + + Body EvaluateResponseBody `json:"body"` +} + +type EvaluateResponseBody struct { + Result string `json:"result"` + Type string `json:"type,omitempty"` + PresentationHint *VariablePresentationHint `json:"presentationHint,omitempty"` + VariablesReference int `json:"variablesReference"` + NamedVariables int `json:"namedVariables,omitempty"` + IndexedVariables int `json:"indexedVariables,omitempty"` + MemoryReference string `json:"memoryReference,omitempty"` +} + +// SetExpressionRequest: Evaluates the given `value` expression and assigns it to the `expression` which must be a modifiable l-value. +// The expressions have access to any variables and arguments that are in scope of the specified frame. +// Clients should only call this request if the corresponding capability `supportsSetExpression` is true. +// If a debug adapter implements both `setExpression` and `setVariable`, a client uses `setExpression` if the variable has an `evaluateName` property. +type SetExpressionRequest struct { + Request + + Arguments SetExpressionArguments `json:"arguments"` +} + +// SetExpressionArguments: Arguments for `setExpression` request. +type SetExpressionArguments struct { + Expression string `json:"expression"` + Value string `json:"value"` + FrameId int `json:"frameId,omitempty"` + Format *ValueFormat `json:"format,omitempty"` +} + +// SetExpressionResponse: Response to `setExpression` request. +type SetExpressionResponse struct { + Response + + Body SetExpressionResponseBody `json:"body"` +} + +type SetExpressionResponseBody struct { + Value string `json:"value"` + Type string `json:"type,omitempty"` + PresentationHint *VariablePresentationHint `json:"presentationHint,omitempty"` + VariablesReference int `json:"variablesReference,omitempty"` + NamedVariables int `json:"namedVariables,omitempty"` + IndexedVariables int `json:"indexedVariables,omitempty"` +} + +// StepInTargetsRequest: This request retrieves the possible step-in targets for the specified stack frame. +// These targets can be used in the `stepIn` request. +// Clients should only call this request if the corresponding capability `supportsStepInTargetsRequest` is true. +type StepInTargetsRequest struct { + Request + + Arguments StepInTargetsArguments `json:"arguments"` +} + +// StepInTargetsArguments: Arguments for `stepInTargets` request. +type StepInTargetsArguments struct { + FrameId int `json:"frameId"` +} + +// StepInTargetsResponse: Response to `stepInTargets` request. +type StepInTargetsResponse struct { + Response + + Body StepInTargetsResponseBody `json:"body"` +} + +type StepInTargetsResponseBody struct { + Targets []StepInTarget `json:"targets"` +} + +// GotoTargetsRequest: This request retrieves the possible goto targets for the specified source location. +// These targets can be used in the `goto` request. +// Clients should only call this request if the corresponding capability `supportsGotoTargetsRequest` is true. +type GotoTargetsRequest struct { + Request + + Arguments GotoTargetsArguments `json:"arguments"` +} + +// GotoTargetsArguments: Arguments for `gotoTargets` request. +type GotoTargetsArguments struct { + Source Source `json:"source"` + Line int `json:"line"` + Column int `json:"column,omitempty"` +} + +// GotoTargetsResponse: Response to `gotoTargets` request. +type GotoTargetsResponse struct { + Response + + Body GotoTargetsResponseBody `json:"body"` +} + +type GotoTargetsResponseBody struct { + Targets []GotoTarget `json:"targets"` +} + +// CompletionsRequest: Returns a list of possible completions for a given caret position and text. +// Clients should only call this request if the corresponding capability `supportsCompletionsRequest` is true. +type CompletionsRequest struct { + Request + + Arguments CompletionsArguments `json:"arguments"` +} + +// CompletionsArguments: Arguments for `completions` request. +type CompletionsArguments struct { + FrameId int `json:"frameId,omitempty"` + Text string `json:"text"` + Column int `json:"column"` + Line int `json:"line,omitempty"` +} + +// CompletionsResponse: Response to `completions` request. +type CompletionsResponse struct { + Response + + Body CompletionsResponseBody `json:"body"` +} + +type CompletionsResponseBody struct { + Targets []CompletionItem `json:"targets"` +} + +// ExceptionInfoRequest: Retrieves the details of the exception that caused this event to be raised. +// Clients should only call this request if the corresponding capability `supportsExceptionInfoRequest` is true. +type ExceptionInfoRequest struct { + Request + + Arguments ExceptionInfoArguments `json:"arguments"` +} + +// ExceptionInfoArguments: Arguments for `exceptionInfo` request. +type ExceptionInfoArguments struct { + ThreadId int `json:"threadId"` +} + +// ExceptionInfoResponse: Response to `exceptionInfo` request. +type ExceptionInfoResponse struct { + Response + + Body ExceptionInfoResponseBody `json:"body"` +} + +type ExceptionInfoResponseBody struct { + ExceptionId string `json:"exceptionId"` + Description string `json:"description,omitempty"` + BreakMode ExceptionBreakMode `json:"breakMode"` + Details *ExceptionDetails `json:"details,omitempty"` +} + +// ReadMemoryRequest: Reads bytes from memory at the provided location. +// Clients should only call this request if the corresponding capability `supportsReadMemoryRequest` is true. +type ReadMemoryRequest struct { + Request + + Arguments ReadMemoryArguments `json:"arguments"` +} + +// ReadMemoryArguments: Arguments for `readMemory` request. +type ReadMemoryArguments struct { + MemoryReference string `json:"memoryReference"` + Offset int `json:"offset,omitempty"` + Count int `json:"count"` +} + +// ReadMemoryResponse: Response to `readMemory` request. +type ReadMemoryResponse struct { + Response + + Body ReadMemoryResponseBody `json:"body,omitempty"` +} + +type ReadMemoryResponseBody struct { + Address string `json:"address"` + UnreadableBytes int `json:"unreadableBytes,omitempty"` + Data string `json:"data,omitempty"` +} + +// WriteMemoryRequest: Writes bytes to memory at the provided location. +// Clients should only call this request if the corresponding capability `supportsWriteMemoryRequest` is true. +type WriteMemoryRequest struct { + Request + + Arguments WriteMemoryArguments `json:"arguments"` +} + +// WriteMemoryArguments: Arguments for `writeMemory` request. +type WriteMemoryArguments struct { + MemoryReference string `json:"memoryReference"` + Offset int `json:"offset,omitempty"` + AllowPartial bool `json:"allowPartial,omitempty"` + Data string `json:"data"` +} + +// WriteMemoryResponse: Response to `writeMemory` request. +type WriteMemoryResponse struct { + Response + + Body WriteMemoryResponseBody `json:"body,omitempty"` +} + +type WriteMemoryResponseBody struct { + Offset int `json:"offset,omitempty"` + BytesWritten int `json:"bytesWritten,omitempty"` +} + +// DisassembleRequest: Disassembles code stored at the provided location. +// Clients should only call this request if the corresponding capability `supportsDisassembleRequest` is true. +type DisassembleRequest struct { + Request + + Arguments DisassembleArguments `json:"arguments"` +} + +// DisassembleArguments: Arguments for `disassemble` request. +type DisassembleArguments struct { + MemoryReference string `json:"memoryReference"` + Offset int `json:"offset,omitempty"` + InstructionOffset int `json:"instructionOffset,omitempty"` + InstructionCount int `json:"instructionCount"` + ResolveSymbols bool `json:"resolveSymbols,omitempty"` +} + +// DisassembleResponse: Response to `disassemble` request. +type DisassembleResponse struct { + Response + + Body DisassembleResponseBody `json:"body,omitempty"` +} + +type DisassembleResponseBody struct { + Instructions []DisassembledInstruction `json:"instructions"` +} + +// Capabilities: Information about the capabilities of a debug adapter. +type Capabilities struct { + SupportsConfigurationDoneRequest bool `json:"supportsConfigurationDoneRequest,omitempty"` + SupportsFunctionBreakpoints bool `json:"supportsFunctionBreakpoints,omitempty"` + SupportsConditionalBreakpoints bool `json:"supportsConditionalBreakpoints,omitempty"` + SupportsHitConditionalBreakpoints bool `json:"supportsHitConditionalBreakpoints,omitempty"` + SupportsEvaluateForHovers bool `json:"supportsEvaluateForHovers,omitempty"` + ExceptionBreakpointFilters []ExceptionBreakpointsFilter `json:"exceptionBreakpointFilters,omitempty"` + SupportsStepBack bool `json:"supportsStepBack,omitempty"` + SupportsSetVariable bool `json:"supportsSetVariable,omitempty"` + SupportsRestartFrame bool `json:"supportsRestartFrame,omitempty"` + SupportsGotoTargetsRequest bool `json:"supportsGotoTargetsRequest,omitempty"` + SupportsStepInTargetsRequest bool `json:"supportsStepInTargetsRequest,omitempty"` + SupportsCompletionsRequest bool `json:"supportsCompletionsRequest,omitempty"` + CompletionTriggerCharacters []string `json:"completionTriggerCharacters,omitempty"` + SupportsModulesRequest bool `json:"supportsModulesRequest,omitempty"` + AdditionalModuleColumns []ColumnDescriptor `json:"additionalModuleColumns,omitempty"` + SupportedChecksumAlgorithms []ChecksumAlgorithm `json:"supportedChecksumAlgorithms,omitempty"` + SupportsRestartRequest bool `json:"supportsRestartRequest,omitempty"` + SupportsExceptionOptions bool `json:"supportsExceptionOptions,omitempty"` + SupportsValueFormattingOptions bool `json:"supportsValueFormattingOptions,omitempty"` + SupportsExceptionInfoRequest bool `json:"supportsExceptionInfoRequest,omitempty"` + SupportTerminateDebuggee bool `json:"supportTerminateDebuggee,omitempty"` + SupportSuspendDebuggee bool `json:"supportSuspendDebuggee,omitempty"` + SupportsDelayedStackTraceLoading bool `json:"supportsDelayedStackTraceLoading,omitempty"` + SupportsLoadedSourcesRequest bool `json:"supportsLoadedSourcesRequest,omitempty"` + SupportsLogPoints bool `json:"supportsLogPoints,omitempty"` + SupportsTerminateThreadsRequest bool `json:"supportsTerminateThreadsRequest,omitempty"` + SupportsSetExpression bool `json:"supportsSetExpression,omitempty"` + SupportsTerminateRequest bool `json:"supportsTerminateRequest,omitempty"` + SupportsDataBreakpoints bool `json:"supportsDataBreakpoints,omitempty"` + SupportsReadMemoryRequest bool `json:"supportsReadMemoryRequest,omitempty"` + SupportsWriteMemoryRequest bool `json:"supportsWriteMemoryRequest,omitempty"` + SupportsDisassembleRequest bool `json:"supportsDisassembleRequest,omitempty"` + SupportsCancelRequest bool `json:"supportsCancelRequest,omitempty"` + SupportsBreakpointLocationsRequest bool `json:"supportsBreakpointLocationsRequest,omitempty"` + SupportsClipboardContext bool `json:"supportsClipboardContext,omitempty"` + SupportsSteppingGranularity bool `json:"supportsSteppingGranularity,omitempty"` + SupportsInstructionBreakpoints bool `json:"supportsInstructionBreakpoints,omitempty"` + SupportsExceptionFilterOptions bool `json:"supportsExceptionFilterOptions,omitempty"` + SupportsSingleThreadExecutionRequests bool `json:"supportsSingleThreadExecutionRequests,omitempty"` +} + +// ExceptionBreakpointsFilter: An `ExceptionBreakpointsFilter` is shown in the UI as an filter option for configuring how exceptions are dealt with. +type ExceptionBreakpointsFilter struct { + Filter string `json:"filter"` + Label string `json:"label"` + Description string `json:"description,omitempty"` + Default bool `json:"default,omitempty"` + SupportsCondition bool `json:"supportsCondition,omitempty"` + ConditionDescription string `json:"conditionDescription,omitempty"` +} + +// ErrorMessage: A structured message object. Used to return errors from requests. +type ErrorMessage struct { + Id int `json:"id"` + Format string `json:"format"` + Variables map[string]string `json:"variables,omitempty"` + SendTelemetry bool `json:"sendTelemetry,omitempty"` + ShowUser bool `json:"showUser"` + Url string `json:"url,omitempty"` + UrlLabel string `json:"urlLabel,omitempty"` +} + +// Module: A Module object represents a row in the modules view. +// The `id` attribute identifies a module in the modules view and is used in a `module` event for identifying a module for adding, updating or deleting. +// The `name` attribute is used to minimally render the module in the UI. +// +// Additional attributes can be added to the module. They show up in the module view if they have a corresponding `ColumnDescriptor`. +// +// To avoid an unnecessary proliferation of additional attributes with similar semantics but different names, we recommend to re-use attributes from the 'recommended' list below first, and only introduce new attributes if nothing appropriate could be found. +type Module struct { + Id any `json:"id"` + Name string `json:"name"` + Path string `json:"path,omitempty"` + IsOptimized bool `json:"isOptimized,omitempty"` + IsUserCode bool `json:"isUserCode,omitempty"` + Version string `json:"version,omitempty"` + SymbolStatus string `json:"symbolStatus,omitempty"` + SymbolFilePath string `json:"symbolFilePath,omitempty"` + DateTimeStamp string `json:"dateTimeStamp,omitempty"` + AddressRange string `json:"addressRange,omitempty"` +} + +// ColumnDescriptor: A `ColumnDescriptor` specifies what module attribute to show in a column of the modules view, how to format it, +// and what the column's label should be. +// It is only used if the underlying UI actually supports this level of customization. +type ColumnDescriptor struct { + AttributeName string `json:"attributeName"` + Label string `json:"label"` + Format string `json:"format,omitempty"` + Type string `json:"type,omitempty"` + Width int `json:"width,omitempty"` +} + +// ModulesViewDescriptor: The ModulesViewDescriptor is the container for all declarative configuration options of a module view. +// For now it only specifies the columns to be shown in the modules view. +type ModulesViewDescriptor struct { + Columns []ColumnDescriptor `json:"columns"` +} + +// Thread: A Thread +type Thread struct { + Id int `json:"id"` + Name string `json:"name"` +} + +// Source: A `Source` is a descriptor for source code. +// It is returned from the debug adapter as part of a `StackFrame` and it is used by clients when specifying breakpoints. +type Source struct { + Name string `json:"name,omitempty"` + Path string `json:"path,omitempty"` + SourceReference int `json:"sourceReference,omitempty"` + PresentationHint string `json:"presentationHint,omitempty"` + Origin string `json:"origin,omitempty"` + Sources []Source `json:"sources,omitempty"` + AdapterData json.RawMessage `json:"adapterData,omitempty"` + Checksums []Checksum `json:"checksums,omitempty"` +} + +// StackFrame: A Stackframe contains the source location. +type StackFrame struct { + Id int `json:"id"` + Name string `json:"name"` + Source *Source `json:"source,omitempty"` + Line int `json:"line"` + Column int `json:"column"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` + CanRestart bool `json:"canRestart,omitempty"` + InstructionPointerReference string `json:"instructionPointerReference,omitempty"` + ModuleId any `json:"moduleId,omitempty"` + PresentationHint string `json:"presentationHint,omitempty"` +} + +// Scope: A `Scope` is a named container for variables. Optionally a scope can map to a source or a range within a source. +type Scope struct { + Name string `json:"name"` + PresentationHint string `json:"presentationHint,omitempty"` + VariablesReference int `json:"variablesReference"` + NamedVariables int `json:"namedVariables,omitempty"` + IndexedVariables int `json:"indexedVariables,omitempty"` + Expensive bool `json:"expensive"` + Source *Source `json:"source,omitempty"` + Line int `json:"line,omitempty"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` +} + +// Variable: A Variable is a name/value pair. +// The `type` attribute is shown if space permits or when hovering over the variable's name. +// The `kind` attribute is used to render additional properties of the variable, e.g. different icons can be used to indicate that a variable is public or private. +// If the value is structured (has children), a handle is provided to retrieve the children with the `variables` request. +// If the number of named or indexed children is large, the numbers should be returned via the `namedVariables` and `indexedVariables` attributes. +// The client can use this information to present the children in a paged UI and fetch them in chunks. +type Variable struct { + Name string `json:"name"` + Value string `json:"value"` + Type string `json:"type,omitempty"` + PresentationHint *VariablePresentationHint `json:"presentationHint,omitempty"` + EvaluateName string `json:"evaluateName,omitempty"` + VariablesReference int `json:"variablesReference"` + NamedVariables int `json:"namedVariables,omitempty"` + IndexedVariables int `json:"indexedVariables,omitempty"` + MemoryReference string `json:"memoryReference,omitempty"` +} + +// VariablePresentationHint: Properties of a variable that can be used to determine how to render the variable in the UI. +type VariablePresentationHint struct { + Kind string `json:"kind,omitempty"` + Attributes []string `json:"attributes,omitempty"` + Visibility string `json:"visibility,omitempty"` + Lazy bool `json:"lazy,omitempty"` +} + +// BreakpointLocation: Properties of a breakpoint location returned from the `breakpointLocations` request. +type BreakpointLocation struct { + Line int `json:"line"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` +} + +// SourceBreakpoint: Properties of a breakpoint or logpoint passed to the `setBreakpoints` request. +type SourceBreakpoint struct { + Line int `json:"line"` + Column int `json:"column,omitempty"` + Condition string `json:"condition,omitempty"` + HitCondition string `json:"hitCondition,omitempty"` + LogMessage string `json:"logMessage,omitempty"` +} + +// FunctionBreakpoint: Properties of a breakpoint passed to the `setFunctionBreakpoints` request. +type FunctionBreakpoint struct { + Name string `json:"name"` + Condition string `json:"condition,omitempty"` + HitCondition string `json:"hitCondition,omitempty"` +} + +// DataBreakpointAccessType: This enumeration defines all possible access types for data breakpoints. +type DataBreakpointAccessType string + +// DataBreakpoint: Properties of a data breakpoint passed to the `setDataBreakpoints` request. +type DataBreakpoint struct { + DataId string `json:"dataId"` + AccessType DataBreakpointAccessType `json:"accessType,omitempty"` + Condition string `json:"condition,omitempty"` + HitCondition string `json:"hitCondition,omitempty"` +} + +// InstructionBreakpoint: Properties of a breakpoint passed to the `setInstructionBreakpoints` request +type InstructionBreakpoint struct { + InstructionReference string `json:"instructionReference"` + Offset int `json:"offset,omitempty"` + Condition string `json:"condition,omitempty"` + HitCondition string `json:"hitCondition,omitempty"` +} + +// Breakpoint: Information about a breakpoint created in `setBreakpoints`, `setFunctionBreakpoints`, `setInstructionBreakpoints`, or `setDataBreakpoints` requests. +type Breakpoint struct { + Id int `json:"id,omitempty"` + Verified bool `json:"verified"` + Message string `json:"message,omitempty"` + Source *Source `json:"source,omitempty"` + Line int `json:"line,omitempty"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` + InstructionReference string `json:"instructionReference,omitempty"` + Offset int `json:"offset,omitempty"` +} + +// SteppingGranularity: The granularity of one 'step' in the stepping requests `next`, `stepIn`, `stepOut`, and `stepBack`. +type SteppingGranularity string + +// StepInTarget: A `StepInTarget` can be used in the `stepIn` request and determines into which single target the `stepIn` request should step. +type StepInTarget struct { + Id int `json:"id"` + Label string `json:"label"` + Line int `json:"line,omitempty"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` +} + +// GotoTarget: A `GotoTarget` describes a code location that can be used as a target in the `goto` request. +// The possible goto targets can be determined via the `gotoTargets` request. +type GotoTarget struct { + Id int `json:"id"` + Label string `json:"label"` + Line int `json:"line"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` + InstructionPointerReference string `json:"instructionPointerReference,omitempty"` +} + +// CompletionItem: `CompletionItems` are the suggestions returned from the `completions` request. +type CompletionItem struct { + Label string `json:"label"` + Text string `json:"text,omitempty"` + SortText string `json:"sortText,omitempty"` + Detail string `json:"detail,omitempty"` + Type CompletionItemType `json:"type,omitempty"` + Start int `json:"start,omitempty"` + Length int `json:"length,omitempty"` + SelectionStart int `json:"selectionStart,omitempty"` + SelectionLength int `json:"selectionLength,omitempty"` +} + +// CompletionItemType: Some predefined types for the CompletionItem. Please note that not all clients have specific icons for all of them. +type CompletionItemType string + +// ChecksumAlgorithm: Names of checksum algorithms that may be supported by a debug adapter. +type ChecksumAlgorithm string + +// Checksum: The checksum of an item calculated by the specified algorithm. +type Checksum struct { + Algorithm ChecksumAlgorithm `json:"algorithm"` + Checksum string `json:"checksum"` +} + +// ValueFormat: Provides formatting information for a value. +type ValueFormat struct { + Hex bool `json:"hex,omitempty"` +} + +// StackFrameFormat: Provides formatting information for a stack frame. +type StackFrameFormat struct { + ValueFormat + + Parameters bool `json:"parameters,omitempty"` + ParameterTypes bool `json:"parameterTypes,omitempty"` + ParameterNames bool `json:"parameterNames,omitempty"` + ParameterValues bool `json:"parameterValues,omitempty"` + Line bool `json:"line,omitempty"` + Module bool `json:"module,omitempty"` + IncludeAll bool `json:"includeAll,omitempty"` +} + +// ExceptionFilterOptions: An `ExceptionFilterOptions` is used to specify an exception filter together with a condition for the `setExceptionBreakpoints` request. +type ExceptionFilterOptions struct { + FilterId string `json:"filterId"` + Condition string `json:"condition,omitempty"` +} + +// ExceptionOptions: An `ExceptionOptions` assigns configuration options to a set of exceptions. +type ExceptionOptions struct { + Path []ExceptionPathSegment `json:"path,omitempty"` + BreakMode ExceptionBreakMode `json:"breakMode"` +} + +// ExceptionBreakMode: This enumeration defines all possible conditions when a thrown exception should result in a break. +// never: never breaks, +// always: always breaks, +// unhandled: breaks when exception unhandled, +// userUnhandled: breaks if the exception is not handled by user code. +type ExceptionBreakMode string + +// ExceptionPathSegment: An `ExceptionPathSegment` represents a segment in a path that is used to match leafs or nodes in a tree of exceptions. +// If a segment consists of more than one name, it matches the names provided if `negate` is false or missing, or it matches anything except the names provided if `negate` is true. +type ExceptionPathSegment struct { + Negate bool `json:"negate,omitempty"` + Names []string `json:"names"` +} + +// ExceptionDetails: Detailed information about an exception that has occurred. +type ExceptionDetails struct { + Message string `json:"message,omitempty"` + TypeName string `json:"typeName,omitempty"` + FullTypeName string `json:"fullTypeName,omitempty"` + EvaluateName string `json:"evaluateName,omitempty"` + StackTrace string `json:"stackTrace,omitempty"` + InnerException []ExceptionDetails `json:"innerException,omitempty"` +} + +// DisassembledInstruction: Represents a single disassembled instruction. +type DisassembledInstruction struct { + Address string `json:"address"` + InstructionBytes string `json:"instructionBytes,omitempty"` + Instruction string `json:"instruction"` + Symbol string `json:"symbol,omitempty"` + Location *Source `json:"location,omitempty"` + Line int `json:"line,omitempty"` + Column int `json:"column,omitempty"` + EndLine int `json:"endLine,omitempty"` + EndColumn int `json:"endColumn,omitempty"` +} + +// InvalidatedAreas: Logical areas that can be invalidated by the `invalidated` event. +type InvalidatedAreas string + +// Mapping of request commands and corresponding struct constructors that +// can be passed to json.Unmarshal. +var requestCtor = map[string]messageCtor{ + "cancel": func() Message { return &CancelRequest{} }, + "runInTerminal": func() Message { return &RunInTerminalRequest{} }, + "startDebugging": func() Message { return &StartDebuggingRequest{} }, + "initialize": func() Message { + return &InitializeRequest{ + Arguments: InitializeRequestArguments{ + // Set the default values specified here: https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize. + LinesStartAt1: true, + ColumnsStartAt1: true, + PathFormat: "path", + }, + } + }, + "configurationDone": func() Message { return &ConfigurationDoneRequest{} }, + "launch": func() Message { return &LaunchRequest{} }, + "attach": func() Message { return &AttachRequest{} }, + "restart": func() Message { return &RestartRequest{} }, + "disconnect": func() Message { return &DisconnectRequest{} }, + "terminate": func() Message { return &TerminateRequest{} }, + "breakpointLocations": func() Message { return &BreakpointLocationsRequest{} }, + "setBreakpoints": func() Message { return &SetBreakpointsRequest{} }, + "setFunctionBreakpoints": func() Message { return &SetFunctionBreakpointsRequest{} }, + "setExceptionBreakpoints": func() Message { return &SetExceptionBreakpointsRequest{} }, + "dataBreakpointInfo": func() Message { return &DataBreakpointInfoRequest{} }, + "setDataBreakpoints": func() Message { return &SetDataBreakpointsRequest{} }, + "setInstructionBreakpoints": func() Message { return &SetInstructionBreakpointsRequest{} }, + "continue": func() Message { return &ContinueRequest{} }, + "next": func() Message { return &NextRequest{} }, + "stepIn": func() Message { return &StepInRequest{} }, + "stepOut": func() Message { return &StepOutRequest{} }, + "stepBack": func() Message { return &StepBackRequest{} }, + "reverseContinue": func() Message { return &ReverseContinueRequest{} }, + "restartFrame": func() Message { return &RestartFrameRequest{} }, + "goto": func() Message { return &GotoRequest{} }, + "pause": func() Message { return &PauseRequest{} }, + "stackTrace": func() Message { return &StackTraceRequest{} }, + "scopes": func() Message { return &ScopesRequest{} }, + "variables": func() Message { return &VariablesRequest{} }, + "setVariable": func() Message { return &SetVariableRequest{} }, + "source": func() Message { return &SourceRequest{} }, + "threads": func() Message { return &ThreadsRequest{} }, + "terminateThreads": func() Message { return &TerminateThreadsRequest{} }, + "modules": func() Message { return &ModulesRequest{} }, + "loadedSources": func() Message { return &LoadedSourcesRequest{} }, + "evaluate": func() Message { return &EvaluateRequest{} }, + "setExpression": func() Message { return &SetExpressionRequest{} }, + "stepInTargets": func() Message { return &StepInTargetsRequest{} }, + "gotoTargets": func() Message { return &GotoTargetsRequest{} }, + "completions": func() Message { return &CompletionsRequest{} }, + "exceptionInfo": func() Message { return &ExceptionInfoRequest{} }, + "readMemory": func() Message { return &ReadMemoryRequest{} }, + "writeMemory": func() Message { return &WriteMemoryRequest{} }, + "disassemble": func() Message { return &DisassembleRequest{} }, +} + +// Mapping of response commands and corresponding struct constructors that +// can be passed to json.Unmarshal. +var responseCtor = map[string]messageCtor{ + "cancel": func() Message { return &CancelResponse{} }, + "runInTerminal": func() Message { return &RunInTerminalResponse{} }, + "startDebugging": func() Message { return &StartDebuggingResponse{} }, + "initialize": func() Message { return &InitializeResponse{} }, + "configurationDone": func() Message { return &ConfigurationDoneResponse{} }, + "launch": func() Message { return &LaunchResponse{} }, + "attach": func() Message { return &AttachResponse{} }, + "restart": func() Message { return &RestartResponse{} }, + "disconnect": func() Message { return &DisconnectResponse{} }, + "terminate": func() Message { return &TerminateResponse{} }, + "breakpointLocations": func() Message { return &BreakpointLocationsResponse{} }, + "setBreakpoints": func() Message { return &SetBreakpointsResponse{} }, + "setFunctionBreakpoints": func() Message { return &SetFunctionBreakpointsResponse{} }, + "setExceptionBreakpoints": func() Message { return &SetExceptionBreakpointsResponse{} }, + "dataBreakpointInfo": func() Message { return &DataBreakpointInfoResponse{} }, + "setDataBreakpoints": func() Message { return &SetDataBreakpointsResponse{} }, + "setInstructionBreakpoints": func() Message { return &SetInstructionBreakpointsResponse{} }, + "continue": func() Message { return &ContinueResponse{} }, + "next": func() Message { return &NextResponse{} }, + "stepIn": func() Message { return &StepInResponse{} }, + "stepOut": func() Message { return &StepOutResponse{} }, + "stepBack": func() Message { return &StepBackResponse{} }, + "reverseContinue": func() Message { return &ReverseContinueResponse{} }, + "restartFrame": func() Message { return &RestartFrameResponse{} }, + "goto": func() Message { return &GotoResponse{} }, + "pause": func() Message { return &PauseResponse{} }, + "stackTrace": func() Message { return &StackTraceResponse{} }, + "scopes": func() Message { return &ScopesResponse{} }, + "variables": func() Message { return &VariablesResponse{} }, + "setVariable": func() Message { return &SetVariableResponse{} }, + "source": func() Message { return &SourceResponse{} }, + "threads": func() Message { return &ThreadsResponse{} }, + "terminateThreads": func() Message { return &TerminateThreadsResponse{} }, + "modules": func() Message { return &ModulesResponse{} }, + "loadedSources": func() Message { return &LoadedSourcesResponse{} }, + "evaluate": func() Message { return &EvaluateResponse{} }, + "setExpression": func() Message { return &SetExpressionResponse{} }, + "stepInTargets": func() Message { return &StepInTargetsResponse{} }, + "gotoTargets": func() Message { return &GotoTargetsResponse{} }, + "completions": func() Message { return &CompletionsResponse{} }, + "exceptionInfo": func() Message { return &ExceptionInfoResponse{} }, + "readMemory": func() Message { return &ReadMemoryResponse{} }, + "writeMemory": func() Message { return &WriteMemoryResponse{} }, + "disassemble": func() Message { return &DisassembleResponse{} }, +} + +// Mapping of event ids and corresponding struct constructors that +// can be passed to json.Unmarshal. +var eventCtor = map[string]messageCtor{ + "initialized": func() Message { return &InitializedEvent{} }, + "stopped": func() Message { return &StoppedEvent{} }, + "continued": func() Message { return &ContinuedEvent{} }, + "exited": func() Message { return &ExitedEvent{} }, + "terminated": func() Message { return &TerminatedEvent{} }, + "thread": func() Message { return &ThreadEvent{} }, + "output": func() Message { return &OutputEvent{} }, + "breakpoint": func() Message { return &BreakpointEvent{} }, + "module": func() Message { return &ModuleEvent{} }, + "loadedSource": func() Message { return &LoadedSourceEvent{} }, + "process": func() Message { return &ProcessEvent{} }, + "capabilities": func() Message { return &CapabilitiesEvent{} }, + "progressStart": func() Message { return &ProgressStartEvent{} }, + "progressUpdate": func() Message { return &ProgressUpdateEvent{} }, + "progressEnd": func() Message { return &ProgressEndEvent{} }, + "invalidated": func() Message { return &InvalidatedEvent{} }, + "memory": func() Message { return &MemoryEvent{} }, +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 406181a007db..abd2071ba62b 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -360,6 +360,9 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value +# github.com/google/go-dap v0.12.0 +## explicit; go 1.18 +github.com/google/go-dap # github.com/google/gofuzz v1.2.0 ## explicit; go 1.12 github.com/google/gofuzz