The GDB Agent Expression Mechanism
**********************************

In some applications, it is not feasible for the debugger to interrupt the program's execution long enough for the developer to learn anything helpful about its behavior.  If the program's correctness depends on its real-time behavior, delays introduced by a debugger might cause the program to fail, even when the code itself is correct.  It is useful to be able to observe the program's behavior without interrupting it.

Using GDB's trace and collect commands, the user can specify locations in the program, and arbitrary expressions to evaluate when those locations are reached.  Later, using the tfind command, she can examine the values those expressions had when the program hit the trace points.  The expressions may also denote objects in memory --- structures or arrays, for example --- whose values GDB should record; while visiting a particular tracepoint, the user may inspect those objects as if they were in memory at that moment. However, because GDB records these values without interacting with the user, it can do so quickly and unobtrusively, hopefully not disturbing the program's behavior.

When GDB is debugging a remote target, the GDB agent code running on the target computes the values of the expressions itself.  To avoid having a full symbolic expression evaluator on the agent, GDB translates expressions in the source language into a simpler bytecode language, and then sends the bytecode to the agent; the agent then executes the bytecode, and records the values for GDB to retrieve later.

The bytecode language is simple; there are forty-odd opcodes, the bulk of which are the usual vocabulary of C operands (addition, subtraction, shifts, and so on) and various sizes of literals and memory reference operations.  The bytecode interpreter operates strictly on machine-level values --- various sizes of integers and floating point numbers --- and requires no information about types or symbols; thus, the interpreter's internal data structures are simple, and each bytecode requires only a few native machine instructions to implement it.  The interpreter is small, and strict limits on the memory and time required to evaluate an expression are easy to determine, making it suitable for use by the debugging agent in real-time applications.

General Bytecode Design
=======================

The agent represents bytecode expressions as an array of bytes.  Each instruction is one byte long (thus the term bytecode).  Some instructions are followed by operand bytes; for example, the goto instruction is followed by a destination for the jump.

The bytecode interpreter is a stack-based machine; most instructions pop their operands off the stack, perform some operation, and push the result back on the stack for the next instruction to consume.  Each element of the stack may contain either a integer or a floating point value; these values are as many bits wide as the largest integer that can be directly manipulated in the source language.  Stack elements carry no record of their type; bytecode could push a value as an integer, then pop it as a floating point value.  However, GDB will not generate code which does this.  In C, one might define the type of a stack element as follows:

     union agent_val {
       LONGEST l;
       DOUBLEST d;
     };

where LONGEST and DOUBLEST are typedef names for the largest integer and floating point types on the machine.

By the time the bytecode interpreter reaches the end of the expression, the value of the expression should be the only value left on the stack. For tracing applications, trace bytecodes in the expression will have recorded the necessary data, and the value on the stack may be discarded.  For other applications, like conditional breakpoints, the value may be useful.

Separate from the stack, the interpreter has two registers:

pc
     The address of the next bytecode to execute.

start
     The address of the start of the bytecode expression, necessary for interpreting the goto and if_goto instructions.

Neither of these registers is directly visible to the bytecode language itself, but they are useful for defining the meanings of the bytecode operations.

There are no instructions to perform side effects on the running program, or call the program's functions; we assume that these expressions are only used for unobtrusive debugging, not for patching the running code.

Most bytecode instructions do not distinguish between the various sizes of values, and operate on full-width values; the upper bits of the values are simply ignored, since they do not usually make a difference to the value computed.  The exceptions to this rule are:

memory reference instructions (refN)
     There are distinct instructions to fetch different word sizes from memory.  Once on the stack, however, the values are treated as full-size integers.  They may need to be sign-extended; the ext instruction exists for this purpose.

the sign-extension instruction (ext N)
     These clearly need to know which portion of their operand is to be extended to occupy the full length of the word.

If the interpreter is unable to evaluate an expression completely for some reason (a memory location is inaccessible, or a divisor is zero, for example), we say that interpretation ``terminates with an error''. This means that the problem is reported back to the interpreter's caller in some helpful way.  In general, code using agent expressions should assume that they may attempt to divide by zero, fetch arbitrary memory locations, and misbehave in other ways.

Even complicated C expressions compile to a few bytecode instructions; for example, the expression x + y * z would typically produce code like the following, assuming that x and y live in registers, and z is a global variable holding a 32-bit int:

     reg 1
     reg 2
     const32 address of z
     ref32
     ext 32
     mul
     add
     end

In detail, these mean:

reg 1
     Push the value of register 1 (presumably holding x) onto the stack.

reg 2
     Push the value of register 2 (holding y).

const32 address of z
     Push the address of z onto the stack.

ref32
     Fetch a 32-bit word from the address at the top of the stack; replace the address on the stack with the value.  Thus, we replace the address of z with z's value.

ext 32
     Sign-extend the value on the top of the stack from 32 bits to full length.  This is necessary because z is a signed integer.

mul
     Pop the top two numbers on the stack, multiply them, and push their product.  Now the top of the stack contains the value of the expression y * z.

add
     Pop the top two numbers, add them, and push the sum.  Now the top of the stack contains the value of x + y * z.

end
     Stop executing; the value left on the stack top is the value to be recorded.

Bytecode Descriptions
=====================

Each bytecode description has the following form:

add (0x02): A B => A+B

     Pop the top two stack items, A and B, as integers; push their sum, as an integer.

In this example, add is the name of the bytecode, and (0x02) is the one-byte value used to encode the bytecode, in hexadecimal.  The phrase ``A B => A+B'' shows the stack before and after the bytecode executes.  Beforehand, the stack must contain at least two values, A and B; since the top of the stack is to the right, B is on the top of the stack, and A is underneath it.  After execution, the bytecode will have popped A and B from the stack, and replaced them with a single value, A+B.  There may be other values on the stack below those shown, but the bytecode affects only those shown.

Here is another example:

const8 (0x22) N: => N
     Push the 8-bit integer constant N on the stack, without sign extension.

In this example, the bytecode const8 takes an operand N directly from the bytecode stream; the operand follows the const8 bytecode itself.  We write any such operands immediately after the name of the bytecode, before the colon, and describe the exact encoding of the operand in the bytecode stream in the body of the bytecode description.

For the const8 bytecode, there are no stack items given before the =>; this simply means that the bytecode consumes no values from the stack.  If a bytecode consumes no values, or produces no values, the list on either side of the => may be empty.

If a value is written as A, B, or N, then the bytecode treats it as an integer.  If a value is written is ADDR, then the bytecode treats it as an address.

We do not fully describe the floating point operations here; although this design can be extended in a clean way to handle floating point values, they are not of immediate interest to the customer, so we avoid describing them, to save time.

float (0x01): =>

     Prefix for floating-point bytecodes.  Not implemented yet.

add (0x02): A B => A+B
     Pop two integers from the stack, and push their sum, as an integer.

sub (0x03): A B => A-B
     Pop two integers from the stack, subtract the top value from the next-to-top value, and push the difference.

mul (0x04): A B => A*B
     Pop two integers from the stack, multiply them, and push the product on the stack.  Note that, when one multiplies two N-bit numbers yielding another N-bit number, it is irrelevant whether the numbers are signed or not; the results are the same.

div_signed (0x05): A B => A/B
     Pop two signed integers from the stack; divide the next-to-top value by the top value, and push the quotient.  If the divisor is zero, terminate with an error.

div_unsigned (0x06): A B => A/B
     Pop two unsigned integers from the stack; divide the next-to-top value by the top value, and push the quotient.  If the divisor is zero, terminate with an error.

rem_signed (0x07): A B => A MODULO B
     Pop two signed integers from the stack; divide the next-to-top value by the top value, and push the remainder.  If the divisor is zero, terminate with an error.

rem_unsigned (0x08): A B => A MODULO B
     Pop two unsigned integers from the stack; divide the next-to-top value by the top value, and push the remainder.  If the divisor is zero, terminate with an error.

lsh (0x09): A B => A<<B
     Pop two integers from the stack; let A be the next-to-top value, and B be the top value.  Shift A left by B bits, and push the result.

rsh_signed (0x0a): A B => (signed)A>>B
     Pop two integers from the stack; let A be the next-to-top value, and B be the top value.  Shift A right by B bits, inserting copies of the top bit at the high end, and push the result.

rsh_unsigned (0x0b): A B => A>>B
     Pop two integers from the stack; let A be the next-to-top value, and B be the top value.  Shift A right by B bits, inserting zero bits at the high end, and push the result.

log_not (0x0e): A => !A
     Pop an integer from the stack; if it is zero, push the value one; otherwise, push the value zero.

bit_and (0x0f): A B => A&B
     Pop two integers from the stack, and push their bitwise and.

bit_or (0x10): A B => A|B
     Pop two integers from the stack, and push their bitwise or.

bit_xor (0x11): A B => A^B
     Pop two integers from the stack, and push their bitwise exclusive-or.

bit_not (0x12): A => ~A
     Pop an integer from the stack, and push its bitwise complement.

equal (0x13): A B => A=B
     Pop two integers from the stack; if they are equal, push the value one; otherwise, push the value zero.

less_signed (0x14): A B => A<B
     Pop two signed integers from the stack; if the next-to-top value is less than the top value, push the value one; otherwise, push the value zero.

less_unsigned (0x15): A B => A<B
     Pop two unsigned integers from the stack; if the next-to-top value is less than the top value, push the value one; otherwise, push the value zero.

ext (0x16) N: A => A, sign-extended from N bits
     Pop an unsigned value from the stack; treating it as an N-bit twos-complement value, extend it to full length.  This means that all bits to the left of bit N-1 (where the least significant bit is bit 0) are set to the value of bit N-1.  Note that N may be larger than or equal to the width of the stack elements of the bytecode engine; in this case, the bytecode should have no effect.

     The number of source bits to preserve, N, is encoded as a single byte unsigned integer following the ext bytecode.

zero_ext (0x2a) N: A => A, zero-extended from N bits
     Pop an unsigned value from the stack; zero all but the bottom N bits.  This means that all bits to the left of bit N-1 (where the least significant bit is bit 0) are set to the value of bit N-1.

     The number of source bits to preserve, N, is encoded as a single byte unsigned integer following the zero_ext bytecode.

ref8 (0x17): ADDR => A
ref16 (0x18): ADDR => A
ref32 (0x19): ADDR => A
ref64 (0x1a): ADDR => A
     Pop an address ADDR from the stack.  For bytecode refN, fetch an N-bit value from ADDR, using the natural target endianness.  Push the fetched value as an unsigned integer.

     Note that ADDR may not be aligned in any particular way; the refN bytecodes should operate correctly for any address.

     If attempting to access memory at ADDR would cause a processor exception of some sort, terminate with an error.

ref_float (0x1b): ADDR => D
ref_double (0x1c): ADDR => D
ref_long_double (0x1d): ADDR => D
l_to_d (0x1e): A => D
d_to_l (0x1f): D => A
     Not implemented yet.

dup (0x28): A => A A
     Push another copy of the stack's top element.

swap (0x2b): A B => B A
     Exchange the top two items on the stack.

pop (0x29): A =>
     Discard the top value on the stack.

pick (0x32) N: A ... B => A ... B A
     Duplicate an item from the stack and push it on the top of the stack. N, a single byte, indicates the stack item to copy.  If N is zero, this is the same as dup; if N is one, it copies the item under the top item, etc.  If N exceeds the number of items on the stack, terminate with an error.

rot (0x33): A B C => C B A
     Rotate the top three items on the stack.

if_goto (0x20) OFFSET: A =>
     Pop an integer off the stack; if it is non-zero, branch to the given offset in the bytecode string.  Otherwise, continue to the next instruction in the bytecode stream.  In other words, if A is non-zero, set the pc register to start + OFFSET. Thus, an offset of zero denotes the beginning of the expression.

     The OFFSET is stored as a sixteen-bit unsigned value, stored immediately following the if_goto bytecode.  It is always stored most significant byte first, regardless of the target's normal endianness.  The offset is not guaranteed to fall at any particular alignment within the bytecode stream; thus, on machines where fetching a 16-bit on an unaligned address raises an exception, you should fetch the offset one byte at a time.

goto (0x21) OFFSET: =>
     Branch unconditionally to OFFSET; in other words, set the pc register to start + OFFSET.

     The offset is stored in the same way as for the if_goto bytecode.

const8 (0x22) N: => N
const16 (0x23) N: => N
const32 (0x24) N: => N
const64 (0x25) N: => N
     Push the integer constant N on the stack, without sign extension. To produce a small negative value, push a small twos-complement value, and then sign-extend it using the ext bytecode.

     The constant N is stored in the appropriate number of bytes following the constB bytecode.  The constant N is always stored most significant byte first, regardless of the target's normal endianness.  The constant is not guaranteed to fall at any particular alignment within the bytecode stream; thus, on machines where fetching a 16-bit on an unaligned address raises an exception, you should fetch N one byte at a time.

reg (0x26) N: => A
     Push the value of register number N, without sign extension.  The registers are numbered following GDB's conventions.

     The register number N is encoded as a 16-bit unsigned integer immediately following the reg bytecode.  It is always stored most significant byte first, regardless of the target's normal endianness. The register number is not guaranteed to fall at any particular alignment within the bytecode stream; thus, on machines where fetching a 16-bit on an unaligned address raises an exception, you should fetch the register number one byte at a time.

getv (0x2c) N: => V
     Push the value of trace state variable number N, without sign extension.

     The variable number N is encoded as a 16-bit unsigned integer immediately following the getv bytecode.  It is always stored most significant byte first, regardless of the target's normal endianness. The variable number is not guaranteed to fall at any particular alignment within the bytecode stream; thus, on machines where fetching a 16-bit on an unaligned address raises an exception, you should fetch the register number one byte at a time.

setv (0x2d) N: => V
     Set trace state variable number N to the value found on the top of the stack.  The stack is unchanged, so that the value is readily available if the assignment is part of a larger expression.  The handling of N is as described for getv.

trace (0x0c): ADDR SIZE =>
     Record the contents of the SIZE bytes at ADDR in a trace buffer, for later retrieval by GDB.

trace_quick (0x0d) SIZE: ADDR => ADDR
     Record the contents of the SIZE bytes at ADDR in a trace buffer, for later retrieval by GDB.  SIZE is a single byte unsigned integer following the trace opcode.

     This bytecode is equivalent to the sequence dup const8 SIZE trace, but we provide it anyway to save space in bytecode strings.

trace16 (0x30) SIZE: ADDR => ADDR
     Identical to trace_quick, except that SIZE is a 16-bit big-endian unsigned integer, not a single byte.  This should probably have been named trace_quick16, for consistency.

tracev (0x2e) N: => A
     Record the value of trace state variable number N in the trace buffer.  The handling of N is as described for getv.

end (0x27): =>
     Stop executing bytecode; the result should be the top element of the stack.  If the purpose of the expression was to compute an lvalue or a range of memory, then the next-to-top of the stack is the lvalue's address, and the top of the stack is the lvalue's size, in bytes.

Using Agent Expressions
=======================

Agent expressions can be used in several different ways by GDBN, and the debugger can generate different bytecode sequences as appropriate.

One possibility is to do expression evaluation on the target rather than the host, such as for the conditional of a conditional tracepoint.  In such a case, GDBN compiles the source expression into a bytecode sequence that simply gets values from registers or memory, does arithmetic, and returns a result.

Another way to use agent expressions is for tracepoint data collection.  GDBN generates a different bytecode sequence for collection; in addition to bytecodes that do the calculation, GDBN adds trace bytecodes to save the pieces of memory that were used.

  * The user selects trace points in the program's code at which GDB should collect data.

  * The user specifies expressions to evaluate at each trace point.  These expressions may denote objects in memory, in which case those objects' contents are recorded as the program runs, or computed values, in which case the values themselves are recorded.

  * GDB transmits the tracepoints and their associated expressions to the GDB agent, running on the debugging target.

  * The agent arranges to be notified when a trace point is hit.

  * When execution on the target reaches a trace point, the agent evaluates the expressions associated with that trace point, and records the resulting values and memory ranges.

  * Later, when the user selects a given trace event and inspects the objects and expression values recorded, GDB talks to the agent to retrieve recorded data as necessary to meet the user's requests.  If the user asks to see an object whose contents have not been recorded, GDB reports an error.

Varying Target Capabilities
===========================

Some targets don't support floating-point, and some would rather not have to deal with long long operations.  Also, different targets will have different stack sizes, and different bytecode buffer lengths.

Thus, GDB needs a way to ask the target about itself.  We haven't worked out the details yet, but in general, GDB should be able to send the target a packet asking it to describe itself.  The reply should be a packet whose length is explicit, so we can add new information to the packet in future revisions of the agent, without confusing old versions of GDB, and it should contain a version number.  It should contain at least the following information:

  * whether floating point is supported

  * whether long long is supported

  * maximum acceptable size of bytecode stack

  * maximum acceptable length of bytecode expressions

  * which registers are actually available for collection

  * whether the target supports disabled tracepoints

Rationale
=========

Some of the design decisions apparent above are arguable.

What about stack overflow/underflow?
     GDB should be able to query the target to discover its stack size. Given that information, GDB can determine at translation time whether a given expression will overflow the stack.  But this spec isn't about what kinds of error-checking GDB ought to do.

Why are you doing everything in LONGEST?

     Speed isn't important, but agent code size is; using LONGEST brings in a bunch of support code to do things like division, etc.  So this is a serious concern.

     First, note that you don't need different bytecodes for different operand sizes.  You can generate code without knowing how big the stack elements actually are on the target.  If the target only supports 32-bit ints, and you don't send any 64-bit bytecodes, everything just works.  The observation here is that the MIPS and the Alpha have only fixed-size registers, and you can still get C's semantics even though most instructions only operate on full-sized words.  You just need to make sure everything is properly sign-extended at the right times.  So there is no need for 32- and 64-bit variants of the bytecodes.  Just implement everything using the largest size you support.

     GDB should certainly check to see what sizes the target supports, so the user can get an error earlier, rather than later.  But this information is not necessary for correctness.

Why don't you have > or <= operators?
     I want to keep the interpreter small, and we don't need them.  We can combine the less_ opcodes with log_not, and swap the order of the operands, yielding all four asymmetrical comparison operators. For example, (x <= y) is ! (x > y), which is ! (y < x).

Why do you have log_not?
Why do you have ext?
Why do you have zero_ext?
     These are all easily synthesized from other instructions, but I expect them to be used frequently, and they're simple, so I include them to keep bytecode strings short.

     log_not is equivalent to const8 0 equal; it's used in half the relational operators.

     ext N is equivalent to const8 S-N lsh const8 S-N rsh_signed, where S is the size of the stack elements; it follows refM and REG bytecodes when the value should be signed.  See the next bulleted item.

     zero_ext N is equivalent to constM MASK log_and; it's used whenever we push the value of a register, because we can't assume the upper bits of the register aren't garbage.

Why not have sign-extending variants of the ref operators?
     Because that would double the number of ref operators, and we need the ext bytecode anyway for accessing bitfields.

Why not have constant-address variants of the ref operators?
     Because that would double the number of ref operators again, and const32 ADDRESS ref32 is only one byte longer.

Why do the refN operators have to support unaligned fetches?
     GDB will generate bytecode that fetches multi-byte values at unaligned addresses whenever the executable's debugging information tells it to. Furthermore, GDB does not know the value the pointer will have when GDB generates the bytecode, so it cannot determine whether a particular fetch will be aligned or not.

     In particular, structure bitfields may be several bytes long, but follow no alignment rules; members of packed structures are not necessarily aligned either.

     In general, there are many cases where unaligned references occur in correct C code, either at the programmer's explicit request, or at the compiler's discretion.  Thus, it is simpler to make the GDB agent bytecodes work correctly in all circumstances than to make GDB guess in each case whether the compiler did the usual thing.

Why are there no side-effecting operators?
     Because our current client doesn't want them?  That's a cheap answer.  I think the real answer is that I'm afraid of implementing function calls.  We should re-visit this issue after the present contract is delivered.

Why aren't the goto ops PC-relative?
     The interpreter has the base address around anyway for PC bounds checking, and it seemed simpler.

Why is there only one offset size for the goto ops?
     Offsets are currently sixteen bits.  I'm not happy with this situation either:

     Suppose we have multiple branch ops with different offset sizes.  As I generate code left-to-right, all my jumps are forward jumps (there are no loops in expressions), so I never know the target when I emit the jump opcode.  Thus, I have to either always assume the largest offset size, or do jump relaxation on the code after I generate it, which seems like a big waste of time.

     I can imagine a reasonable expression being longer than 256 bytes.  I can't imagine one being longer than 64k.  Thus, we need 16-bit offsets. This kind of reasoning is so bogus, but relaxation is pathetic.

     The other approach would be to generate code right-to-left.  Then I'd always know my offset size.  That might be fun.

Where is the function call bytecode?

     When we add side-effects, we should add this.

Why does the reg bytecode take a 16-bit register number?

     Intel's IA-64 architecture has 128 general-purpose registers, and 128 floating-point registers, and I'm sure it has some random control registers.

Why do we need trace and trace_quick?
     Because GDB needs to record all the memory contents and registers an expression touches.  If the user wants to evaluate an expression x->y->z, the agent must record the values of x and x->y as well as the value of x->y->z.

Don't the trace bytecodes make the interpreter less general?
     They do mean that the interpreter contains special-purpose code, but that doesn't mean the interpreter can only be used for that purpose.  If an expression doesn't use the trace bytecodes, they don't get in its way.

Why doesn't trace_quick consume its arguments the way everything else does?
     In general, you do want your operators to consume their arguments; it's consistent, and generally reduces the amount of stack rearrangement necessary.  However, trace_quick is a kludge to save space; it only exists so we needn't write dup const8 SIZE trace before every memory reference.  Therefore, it's okay for it not to consume its arguments; it's meant for a specific context in which we know exactly what it should do with the stack.  If we're going to have a kludge, it should be an effective kludge.

Why does trace16 exist?
     That opcode was added by the customer that contracted Cygnus for the data tracing work.  I personally think it is unnecessary; objects that large will be quite rare, so it is okay to use dup const16 SIZE trace in those cases.

     Whatever we decide to do with trace16, we should at least leave opcode 0x30 reserved, to remain compatible with the customer who added it.