# Target Communication Framework Services - Memory

- Commands
  - Get Context
  - Get Children
  - Set Memory
  - Get Memory
  - Fill Memory
- Events
- API

# Memory Service

The service provides basic operations to read/write memory 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.

A single memory access can succeed for some addresses and fail for others. In such situation result message can contain partially valid data. Array of error addresses, in addition to error report, describes data validity on per byte basis:

    <array of error addresses>
        Ψ null
        Ψ [ <error address list> ]

    <error address list>
        Ψ <error address>
        Ψ <error address list> , <error address>

    <error address>
        Ψ { "addr" : <int: range starting address> , "size" : <int: range length in bytes> , "stat" : <int: status code> , "msg" : <error description> }

If there is no entry in error addresses array for a data byte, then status of such byte is defined by main error report.

Status code is bitwise or of status flags:

`BYTE_VALID = 0x00`
  no error for this byte
`BYTE_UNKNOWN = 0x01`
  status is unknown
`BYTE_INVALID = 0x02`
  byte value in invalid, error message describes the problem
`BYTE_CANNOT_READ = 0x04`
  cannot read the byte
`BYTE_CANNOT_WRITE = 0x08`
  cannot write the byte

## Commands

### Get Context

    C  <token>  Memory  getContext  <string: context ID>

The command retrieves context info for given context ID. A context corresponds to an execution thread, process, address space, etc. Exact meaning of a context depends on the target. Target agent should define contexts hierarchy that is:

- Sufficient to resolve possible ambiguity of a memory address;
- Adequately reflects target memory management strategy;
- Intuitive to a user.

For traditional OS, like UNIX, memory access context can be one of:

- Kernel address space;
- A process.

Reply:

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

    <context data>
        Ψ null
        Ψ <object>

Context data object should, at least, contain member "ID" : <string>. Context data is expected to be cached by clients. Service sends contextChanged event to notify changes in context data.

Predefined memory context properties are:

- `"ID" : <string>` - ID of the context, same as getContext command argument.
- `"ParentID" : <string>` - ID of a parent context.
- `"BigEndian" : <boolean>` - true if memory is big-endian.
- `"AddressSize" : <int>` - size of memory address in bytes.

### Get Children

    C  <token>  Memory  getChildren  <string: parent context ID>

The command requests a list of contexts available for memory access 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>

### Set Memory

    C  <token>  Memory  set
        <string: context ID>  <int: address>  <int: word size>
        <int: byte count>  <int: mode>  <string: BASE64 encoded byte array>

Writes data bytes at given address in memory, "word size" bytes at a time. Address should be aligned by "word size". Context ID must be one returned by getContexts. Mode is logical OR of any combination of:

- 0x1 continue on error (like bus error or page fault)
- 0x2 verify data after writing by reading back and compare

Result message:

    R  <token>  <error report>  <array of error addresses>

Error report provides integer error code and a short, human readable explanation of error. Error addresses, when present, let client know which bytes of data failed to be written into memory.

### Get Memory

    C  <token>  Memory  get
        <string: context ID>  <int: address>  <int: word size>
        <int: byte count>  <int: mode>

Reads data bytes at given address in memory, "word size" bytes at a time. Address should be aligned by "word size". Context ID must be one returned by getContexts. Mode is logical OR of any combination of:

- 0x1 continue on error (like bus error or page fault)
- 0x2 verify data after reading by re-reading and compare

Result message:

    R  <token>  <string: BASE64 encoded byte array>  <error report>  <array of error addresses>

Error report provides integer error code and a short, human readable explanation of error. Error addresses, when present, let client know which bytes of data failed to be retrieved from memory.

### Fill Memory

    C  <token>  Memory  fill
        <string: context ID>  <int: address>  <int: word size>
        <int: byte count>  <int: mode>  <array: array of pattern bytes>

Writes pattern bytes at given address in memory, "word size" bytes at a time. Address should be aligned by "word size". If "byte count" is bigger then pattern size, then pattern is repeated necessary number of times. Context ID must be one returned by getContexts. Mode is logical OR of any combination of:

- 0x1 continue on error (like bus error or page fault)
- 0x2 verify data after writing by reading back and compare

Result message:

    R  <token>  <error report>  <array of error addresses>

Error report provides integer error code and a short, human readable explanation of error. Error addresses, when present, let client know which bytes of data failed to be written into memory.

## Events

Memory service broadcasts notification events when memory contexts are added, removed or changed, and when memory content is altered by "set" or "fill" commands.

    E  Memory  contextAdded  <array of context data>
    E  Memory  contextChanged  <array of context data>
    E  Memory  contextRemoved  <array of context IDs>
    E  Memory  memoryChanged  <string: context ID>  <array of address ranges>

    <array of context data> - see Get Contexts command.

    <array of context IDs>
        Ψ [ <context ID list> ]

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

    <array of address ranges>
        Ψ null
        Ψ [ <address ranges list> ]

    <address ranges list>
        Ψ <address range>
        Ψ <address ranges list> , <address range>

    <address range>
        Ψ { "addr" : <int: range starting address> , "size" : <int: range length in bytes> }

## API

    /**
     * IMemory service provides basic operations to read/write memory on a target.
     */
    public interface Memory extends Service {

        static final String NAME = "Memory";

        /**
         * 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, MemoryContext context);
        }

        /**
         * Retrieve contexts available for memory commands.
         * 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.
         *
         * @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 getContexts commands.
         * @param done - callback interface called when operation is completed.
         */
        IToken getChildren(String parent_context_id, DoneGetChildren done);

        /**
         * Client callback interface for getChildren().
         */
        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, Exception error, String[] context_ids);
        }

        /**
         * Memory access mode:
         * Carry on when some of the memory cannot be accessed and
         * return MemoryError at the end if any of the bytes
         * were not processed correctly.
         */
        final static int MODE_CONTINUEONERROR = 0x1;

        /**
         * Memory access mode:
         * Verify result of memory operations (by reading and comparing).
         */
        final static int MODE_VERIFY = 0x2;

        interface MemoryContext {

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

            /**
             * Return true if the context has children.
             * Same as getProperties().get("has_children")
             * Children can be retrieved by getContexts call.
             */
            boolean hasChildren();

            /**
             * Retrieve context properties.
             */
            Map<String,Object> getProperties();

            /**
             * Set target memory.
             * If 'word_size' is 0 it means client does not care about word size.
             */
            void set(long addr, int word_size, byte[] buf,
                             int offs, int size, int mode, DoneMemory done);

            /**
             * Read target memory.
             */
            void get(long addr, int word_size, byte[] buf,
                             int offs, int size, int mode, DoneMemory done);

            /**
             * Fill target memory with given pattern.
             * 'size' is number of bytes to fill.
             */
            void fill(long addr, int word_size, byte[] value,
                              int size, int mode, DoneMemory done);

            /**
             * Client callback interface for set(), get() and fill().
             */
            interface DoneMemory {
                void doneMemory(MemoryError error);
            }
        }

        class MemoryError extends Exception {
        }

        /**
         * ErrorOffset interface can be implemented by MemoryError object,
         * which is returned by get, set and fill commands.
         *
         * get/set/fill () returns this exception when reading failed
         * for some but not all bytes, and MODE_CONTINUEONERROR
         * has been set in mode. (For example, when only part of the request
         * translates to valid memory addresses.)
         * Exception.getMessage can be used for generalized message of the
         * possible reasons of partial memory operation.
         */
        interface ErrorOffset {

            // Error may have per byte information
            final static int
                BYTE_VALID        = 0x00,
                BYTE_UNKNOWN      = 0x01, // e.g. out of range
                BYTE_INVALID      = 0x02,
                BYTE_CANNOT_READ  = 0x04,
                BYTE_CANNOT_WRITE = 0x08;

            int getStatus(int offset);

            /**
             * Returns the detail message string about the
             * byte associated with specified location.
             * @return  the detail error message string.
             */
            String getMessage(int offset);

        }

        void addListener(MemoryListener listener);

        interface MemoryListener {

            /**
             * Called when a new memory access context(s) is created.
             */
            void contextAdded(Context[] contexts);

            /**
             * Called when a new memory access context(s) properties changed.
             */
            void contextChanged(Context[] contexts);

            /**
             * Called when memory access context(s) is removed.
             */
            void contextRemoved(String[] context_ids);

            /**
             * Called when target memory content was changed and clients
             * need to update themselves. Clients, at least, should invalidate
             * corresponding cached memory data.
             * Not every change is notified - it is not possible,
             * only those, which are not caused by normal execution of the debuggee.
             * addr and size can be null if unknown.
             */
            void memoryChanged(String context_id,
                   long[] addr, long[] size);
        }
    }