title: Scriptable disassembly in gdb
body: <p>I am dumping register contents, instruction by instruction, with a <code>gdb</code> script (this is not an interactive debugging session, <code>layout asm</code> or TUI mode are out of the picture).</p>
  
  <p>I would like to add to the register values the machine code corresponding to the current instruction. I already found a trick to overcome the fact that the <code>disassemble</code> command is designed to give you a lot of context around the current instruction and that I don't know how many bytes I should disassemble to get the full instruction. Whatever the instruction size, a range of 1 takes care of this for me:</p>
  
  <pre><code>(gdb) disassemble $pc,$pc+1
  Dump of assembler code from 0x400efe to 0x400eff:
  =&gt; 0x0000000000400efe &lt;main+0&gt;: push   %r15
  End of assembler dump.
  </code></pre>
  
  <p>I have to go a step further and add a flag to display what I really want (<code>41 57</code>):</p>
  
  <pre><code>(gdb) disassemble /r $pc,$pc+1
  Dump of assembler code from 0x400efe to 0x400eff:
  =&gt; 0x0000000000400efe &lt;main+0&gt;: 41 57   push   %r15
  End of assembler dump.
  </code></pre>
  
  <p>There is another way to display this information:</p>
  
  <pre><code>(gdb) x/i $pc
  =&gt; 0x400efe &lt;main&gt;: push   %r15
  (gdb) x/x $pc
  0x400efe &lt;main&gt;:    0x56415741
  </code></pre>
  
  <p>But I couldn't find a format specifier that would let me extract specifically <code>41 57</code> (I can live with <code>5741</code>). As you can see, the instruction oriented one disassembles without displaying the machine code, while the hexdump has no idea of the instruction length.</p>
  
  <p>Finally, I need this value to end up in a <code>printf</code>, meaning that based on the current outputs I get, some parsing would still be needed. I am not sure this is doable within a pure <code>gdb</code> script. </p>
  
  <p>I'd rather avoid relying on the <code>gdb</code> <code>python</code> layer if possible.</p>
  
  <p>Do you know of any way to achieve what I'd like to do?</p>