# Target Communication Framework Services - Run Control

- Commands
  - Get Context
  - Get Children
  - Suspend
  - Resume
  - Get State
  - Terminate
- Events
- API

# Run Control Service

The service provides basic run control operations for execution contexts on a target. Command and event parameters are encoded as zero terminated JSON strings.

The service uses standard format for error reports, see Error Report Format.

## Commands

All run control commands are fully asynchronous, which means they never wait until context is in a particular state. For example, if single step command arrives when context is running, it does not wait until it stops, but returns an error. If a command successfully resumed a context, it does not wait until instruction pointer reaches desired destination – from client point of view the command execution ends right after context was resumed. Various stepping commands can leave a context running in a special mode, which is different from normal execution, for example, it can leave temporary breakpoints to suspend the context when control reaches a particular place. Such execution mode ends when the context is suspended, even if it was suspended for reasons unrelated to the command and intended destination was not reached. Client can know when and why a context is suspended by listening to events.

### Get Context

    C • <token> • RunControl • getContext • <string: context ID> •

The command retrieves context properties for given context ID. Exact meaning of context depends on the target. A context can represent an execution thread, a process, an address space, etc. A context can belong to a parent context. Contexts hierarchy can be simple plain list or it can form a tree. It is up to target agent developers to choose layout that is most descriptive for a given target. Context IDs are valid across all services. In other words, all services access same hierarchy of contexts, with same IDs, however, each service accesses its own subset of context's attributes and functionality, which is relevant to that service.

Reply:

    R • <token> • <error report> • <context data> •

    <context data>
        Ø null
        Ø <object: context properties>

Context data object is collection of context properties. It should, at least, contain member "ID" : <string>. It can also contain arbitrary number of components describing context properties and capabilities. Context data is supposed to be cached by clients and it is not expected to change frequently. It can include, for example, context name or ability to perform single step command on the context. But, it should not include volatile data like current PC or running/suspended state. Service sends contextChanged event to notify changes in context data.

Predefined run control context properties are:

- `"ID" : <string>` - ID of the context, same as getContext command argument.
- `"ParentID" : <string>` - ID of a parent context.
- `"IsContainer" : <boolean>` - true if the context is a container. Executing resume or suspend command on a container causes all its children to resume or suspend.
- `"HasState" : <boolean>` - true if the context is an execution context, therefore has an execution state, like state of a program counter (PC). Only context that has a state can be resumed or suspended.
- `"CanSuspend" : <boolean>` - true if Suspend command is supported for this contex. It does not mean that the command can be executed successfully in the current state of the context. For example, the command still can fail if context is already suspended.
- `"CanResume" : <int: bitset of resume modes>` - for each resume mode, corresponding bit is '1' if Resume command mode is supported for this contex, and '0' otherwise. It does not mean that the command can be executed successfully in the current state of the context. For example, the command still can fail if context is already resumed.
- `"CanCount" : <int: bitset of resume modes>` - for each resume mode, corresponding bit is '1' if Resume command mode with count other then 1 is supported by the context.
- `"CanTerminate" : <boolean>` - true if Terminate command is supported by the context,

### Get Children

    C • <token> • RunControl • getChildren • <string: parent context ID> •

The command requests list of execution contexts available for run control commands.

Parent context ID can be null – to retrieve top level of the hierarchy, can be one of context IDs retrieved by previous getChildren commands, or it can be obtained from another service. Contexts hierarchy can be simple plain list or it can form a tree. It is up to target agent developers to choose layout that is most descriptive for a given target.

Reply:

    R • <token> • <error report> • <array of context IDs> •

    <array of context IDs>
        Ø null
        Ø [ <context ID list> ]

    <context ID list>
        Ø <string: context ID>
        Ø <context ID list> , <string: context ID>

### Suspend

    C • <token> • RunControl • suspend • <string: context ID> •

The command suspends execution of given context. The command should fail if CanSuspend property of the context is false. If context's IsContainer = true, the command is propagated to context's children. Only contexts with HasState = true can be suspended.

Result message:

    R • <token> • <error report> •

### Resume

    C • <token> • RunControl • resume • <string: context ID> • <int: mode> • <int: count> •

The command resumes execution of given context. The command should fail if CanResume property of the context is '0' for given mode. If context's IsContainer = true, the command is propagated to context's children. Only contexts with HasState = true can be resumed.

Resume modes:

- `RM_RESUME = 0` - rusume normal execution. Execution will continue until suspended by command or breakpoint.
- `RM_STEP_OVER = 1` - step over single instruction. If instruction is function call, execution continues until control returns from the function.
- `RM_STEP_INTO = 2` - single instruction in given context.
- `RM_STEP_OVER_LINE = 3` - resume execution of given context until control reaches instruction that belongs to a different line of source code, but runs any functions called at full speed. Error is returned if line number information not available.
- `RM_STEP_INTO_LINE = 4` - resumes execution of given context until control reaches instruction that belongs to a different line of source code. If a function is called, stop at first line of the function code. Error is returned if line number information not available.
- `RM_STEP_OUT = 5` - resume execution of given context until control returns from current function.

Result message:

    R • <token> • <error report> •

### Get State

    C • <token> • RunControl • getState • <string: context ID> •

The command retrieves current state of the context. The command should fail if HasState property of the context is false.

Result message:

    R • <token> • <error report> • <boolean: suspended> •
        <int: PC> • <string: last state change reason> • <state data> •

    <state data>
        Ø null
        Ø <object: context state properties>

State change reason can be any text, but if it is one of predefined strings, a generic client might be able to handle it better. Predefined reasons are:

- `REASON_USER_REQUEST = "Suspended"` - context suspended by command.
- `REASON_STEP = "Step"` - context resumed or suspended by step command.
- `REASON_BREAKPOINT = "Breakpoint"` - context suspended by breakpoint.
- `REASON_EXCEPTION = "Exception"` - context suspended by exception.
- `REASON_CONTAINER = "Container"` - context suspended or resumed as part of container.
- `REASON_WATCHPOINT = "Watchpoint"` - context suspended by watchpoint (data breakpoint).
- `REASON_SIGNAL = "Signal"` - context suspended because it received a signal.
- `REASON_SHAREDLIB = "Shared Library"` - context suspended because a shared library is loaded or unloaded.
- `REASON_ERROR = "Error"` - context suspended because of an error in execution environment.

Context state properties can contain any data relevant to context state. Defenition of state properties depends on a target.

### Terminate

    C • <token> • RunControl • terminate • <string: context ID> •

The command terminates execution of given context. The command should fail if CanTerminate property of the context is false.

Result message:

    R • <token> • <error report> •

## Events

    E • RunControl • contextAdded • <array of context data> •

    E • RunControl • contextChanged • <array of context data> •

    E • RunControl • contextRemoved • <array of context IDs> •

    E • RunControl • contextSuspended • <string: context ID> • <int: PC> •
            <string: reason> • <state data> •

    E • RunControl • contextResumed • <string: context ID> •

    E • RunControl • contextException • <string: context ID> • <string: description> •

    E • RunControl • containerSuspended • <string: context ID> • <int: PC> •
            <string: reason> • <state data> • <array of context IDs> •

    E • RunControl • containerResumed • <array of context IDs> •

    <array of context data>
        Ø null
        Ø [ <context data list> ]

    <context data list>
        Ø <object: context data>
        Ø <context data list> , <object: context data>

contextAdded
  is sent when new contexts are created or attached for debugging. The message contains array of context data. Context data is same as returned by Get Context command.
contextChanged
  is sent when context properties change. The message contains array of changed (new) context data. Context data is same as returned by Get Context command.
contextRemoved
  is sent when context is removed - terminated or dettached. The message contains array of context IDs.
contextSuspended
  is sent when context is suspended. The message context ID contains context state data, same state data as returned by Get State command.
contextResumed
  is sent when context is resumed. The message contains resumed context ID.
contextException
  is sent when execution exception occurs in a context. The message contains context ID and a string that describes nature of the exception.
containerSuspended
  is sent when target simultaneously suspends multiple threads in a container (process, core, etc.). The message contains context ID and context state data of a context responsible for the event. It can be container ID or any one of container children, for example, it can be thread that hit "suspend all" breakpoint. Message also contains full list of all contexts that were suspended simultaneously. No separate contextSuspened events are sent for contexts in the list. If client needs state data for those contexts, it should use Get State command.
containerResumed
  is sent when target simultaneously resumes multiple threads in a container (process, core, etc.). Message contains full list of all contexts that were resumed simultaneously. No separate contextResumed events are sent for contexts in the list.

## API

    public interface IRunControl extends IService {

        /**
         * Context property names.
         */
        static final String
            PROP_ID = "ID",
            PROP_PARENT_ID = "ParentID",
            PROP_IS_CONTAINER = "IsContainer",
            PROP_HAS_STATE = "HasState",
            PROP_CAN_RESUME = "CanResume",
            PROP_CAN_COUNT = "CanCount",
            PROP_CAN_SUSPEND = "CanSuspend",
            PROP_CAN_TERMINATE = "CanTerminate";

        /**
         * Context resume modes.
         */
        static final int
            RM_RESUME = 0,
            RM_STEP_OVER = 1,
            RM_STEP_INTO = 2,
            RM_STEP_OVER_LINE = 3,
            RM_STEP_INTO_LINE = 4,
            RM_STEP_OUT = 5;

        /**
         * State change reason of a context.
         * Reason can be any text, but if it is one of predefined strings,
         * a generic client might be able to handle it better.
         */
        static final String
            REASON_USER_REQUEST = "Suspended",
            REASON_STEP = "Step",
            REASON_BREAKPOINT = "Breakpoint",
            REASON_EXCEPTION = "Exception",
            REASON_CONTAINER = "Container",
            REASON_WATCHPOINT = "Watchpoint",
            REASON_SIGNAL = "Signal",
            REASON_SHAREDLIB = "Shared Library",
            REASON_ERROR = "Error";

        /**
         * Retrieve context info for given context ID.
         *
         * @param id – context ID.
         * @param done - callback interface called when operation is completed.
         */
        IToken getContext(String id, DoneGetContext done);

        /**
         * Client callback interface for getContext().
         */
        interface DoneGetContext {
            /**
             * Called when contexts data retrieval is done.
             * @param error – error description if operation failed, null if succeeded.
             * @param context – context data.
             */
            void doneGetContext(IToken token, Exception error, RunControlContext context);
        }

        /**
         * Retrieve children of given context.
         *
         * @param parent_context_id – parent context ID. Can be null –
         * to retrieve top level of the hierarchy, or one of context IDs retrieved
         * by previous getContext or getChildren commands.
         * @param done - callback interface called when operation is completed.
         */
        IToken getChildren(String parent_context_id, DoneGetChildren done);

        /**
         * Client callback interface for getContexts().
         */
        interface DoneGetChildren {
            /**
             * Called when contexts data retrieval is done.
             * @param error – error description if operation failed, null if succeeded.
             * @param contexts – array of available context IDs.
             */
            void doneGetChildren(IToken token, RunControlError error, Context[] contexts);
        }

        /**
         * A context corresponds to an execution thread, process, address space, etc.
         * A context can belong to a parent context. Contexts hierarchy can be simple
         * plain list or it can form a tree. It is up to target agent developers to choose
         * layout that is most descriptive for a given target. Context IDs are valid across
         * all services. In other words, all services access same hierarchy of contexts,
         * with same IDs, however, each service accesses its own subset of context's
         * attributes and functionality, which is relevant to that service.
         */
        interface RunControlContext {

            /**
             * Retrieve context ID.
             * Same as getProperties().get("ID")
             */
            String getID();

            /**
             * Retrieve parent context ID.
             * Same as getProperties().get("ParentID")
             */
            String getParentID();

            /**
             * Get context properties. See PROP_* definitions for property names.
             * Context properties are read only, clients should not try to modify them.
             * @return Map of context properties.
             */
            Map<String,Object> getProperties();

            /**
             * Utility method to read context property PROP_IS_CONTAINER.
             * Executing resume or suspend command on a container causes all its children to resume or suspend.
             * @return value of PROP_IS_CONTAINER.
             */
            boolean isContainer();

            /**
             * Utility method to read context property PROP_HAS_STATE.
             * Only context that has a state can be resumed or suspended.
             * @return value of PROP_HAS_STATE.
             */
            boolean hasState();

            /**
             * Utility method to read context property PROP_CAN_SUSPEND.
             * Value 'true' means suspend command is supported by the context,
             * however the method does not check that the command can be executed successfully in
             * the current state of the context. For example, the command still can fail if context is
             * already suspended.
             * @return value of PROP_CAN_SUSPEND.
             */
            boolean canSuspend();

            /**
             * Utility method to read a 'mode' bit in context property PROP_CAN_RESUME.
             * Value 'true' means resume command is supported by the context,
             * however the method does not check that the command can be executed successfully in
             * the current state of the context. For example, the command still can fail if context is
             * already resumed.
             * @param mode - resume mode, see RM_*.
             * @return value of requested bit of PROP_CAN_RESUME.
             */
            boolean canResume(int mode);

            /**
             * Utility method to read a 'mode' bit in context property PROP_CAN_COUNT.
             * Value 'true' means resume command with count other then 1 is supported by the context,
             * however the method does not check that the command can be executed successfully in
             * the current state of the context. For example, the command still can fail if context is
             * already resumed.
             * @param mode - resume mode, see RM_*.
             * @return value of requested bit of PROP_CAN_COUNT.
             */
            boolean canCount(int mode);

            /**
             * Utility method to read context property PROP_CAN_TERMINATE.
             * Value 'true' means terminate command is supported by the context,
             * however the method does not check that the command can be executed successfully in
             * the current state of the context. For example, the command still can fail if context is
             * already exited.
             * @return value of PROP_CAN_SUSPEND.
             */
            boolean canTerminate();

            /**
             * Send a command to retrieve current state of a context.
             * @param done - command result call back object.
             * @return pending command handle, can be used to cancel the command.
             */
            IToken getState(DoneGetState done);

            /**
             * Send a command to suspend a context.
             * Also suspends children if context is a container.
             * @param done - command result call back object.
             * @return pending command handle, can be used to cancel the command.
             */
            IToken suspend(DoneCommand done);

            /**
             * Send a command to resume a context.
             * Also resumes children if context is a container.
             * @param mode - defines how to resume the context, see RM_*.
             * @param count - if mode implies stepping, defines how many steps to perform.
             * @param done - command result call back object.
             * @return pending command handle, can be used to cancel the command.
             */
            IToken resume(int mode, int count, DoneCommand done);

            /**
             * Send a command to terminate a context.
             * @param done - command result call back object.
             * @return pending command handle, can be used to cancel the command.
             */
            IToken terminate(DoneCommand done);
        }

        class RunControlError extends Exception {
        }

        interface DoneGetState {
            void doneGetState(IToken token, Exception error, boolean suspended, String pc,
                    String reason, Map<String,Object> params);
        }

        interface DoneCommand {
            /**
             * Called when run control command execution is complete.
             * @param token - pending command handle.
             * @param error - command execution error or null.
             */
            void doneCommand(IToken token, Exception error);
        }

        /**
         * Add run control event listener.
         * @param listener - run control event listener to add.
         */
        void addListener(RunControlListener listener);

        /**
         * Remove run control event listener.
         * @param listener - run control event listener to remove.
         */
        void removeListener(RunControlListener listener);

        /**
         * Service events listener interface.
         */
        interface RunControlListener {

            /**
             * Called when a new contexts are created.
             * @param contexts - array of new context properties.
             */
            void contextAdded(RunControlContext contexts[]);

            /**
             * Called when a context properties changed.
             * @param contexts - array of new context properties.
             */
            void contextChanged(RunControlContext contexts[]);

            /**
             * Called when contexts are removed.
             * @param context_ids - aray of removed context IDs.
             */
            void contextRemoved(String context_ids[]);

            /**
             * Called when a thread is suspended.
             * @param context - ID of a context that was suspended.
             * @param pc - program counter of the context, can be null.
             * @param reason - human readable description of suspend reason.
             * @param params - additional, target specific data about suspended context.
             */
            void contextSuspended(String context, String pc,
                    String reason, Map<String,Object> params);

            /**
             * Called when a thread is resumed.
             * @param context - ID of a context that was resumed.
             */
            void contextResumed(String context);

            /**
             * Called when target simultaneously suspends multiple threads in a container
             * (process, core, etc.).
             *
             * @param context - ID of a context responsible for the event. It can be container ID or
             * any one of container children, for example, it can be thread that hit "suspend all" breakpoint.
             * Client expected to move focus (selection) to this context.
             * @param pc - program counter of the context.
             * @param reason - human readable description of suspend reason.
             * @param params - additional target specific data about suspended context.
             * @param suspended_ids - full list of all contexts that were suspended.
             */
            void containerSuspended(String context, String pc,
                    String reason, Map<String,Object> params, String[] suspended_ids);

            /**
             * Called when target simultaneously resumes multiple threads in a container (process,
             * core, etc.).
             *
             * @param context_ids - full list of all contexts that were resumed.
             */
            void containerResumed(String[] context_ids);

            /**
             * Called when an exception is detected in a target thread.
             * @param context - ID of a context that caused an exception.
             * @param msg - human readable description of the exception.
             */
            void contextException(String context, String msg);
        }
    }