Exceptions in Debug Mode don't update any regs.
[riscv-isa-sim.git] / riscv / gdbserver.cc
index c254ab027c195b32485967d4985dd546fe776330..33a24e97f8c0b5f8b463c66967eb315fa3b68f55 100644 (file)
@@ -66,13 +66,13 @@ static uint32_t jal(unsigned int rd, uint32_t imm) {
     MATCH_JAL;
 }
 
-static uint32_t csrsi(unsigned int csr, uint8_t imm) {
+static uint32_t csrsi(unsigned int csr, uint16_t imm) {
   return (csr << 20) |
     (bits(imm, 4, 0) << 15) |
     MATCH_CSRRSI;
 }
 
-static uint32_t csrci(unsigned int csr, uint8_t imm) {
+static uint32_t csrci(unsigned int csr, uint16_t imm) {
   return (csr << 20) |
     (bits(imm, 4, 0) << 15) |
     MATCH_CSRRCI;
@@ -82,6 +82,33 @@ static uint32_t csrr(unsigned int rd, unsigned int csr) {
   return (csr << 20) | (rd << 7) | MATCH_CSRRS;
 }
 
+static uint32_t csrw(unsigned int source, unsigned int csr) {
+  return (csr << 20) | (source << 15) | MATCH_CSRRW;
+}
+
+static uint32_t fence_i()
+{
+  return MATCH_FENCE_I;
+}
+
+static uint32_t sb(unsigned int src, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 5) << 25) |
+    (src << 20) |
+    (base << 15) |
+    (bits(offset, 4, 0) << 7) |
+    MATCH_SB;
+}
+
+static uint32_t sh(unsigned int src, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 5) << 25) |
+    (src << 20) |
+    (base << 15) |
+    (bits(offset, 4, 0) << 7) |
+    MATCH_SH;
+}
+
 static uint32_t sw(unsigned int src, unsigned int base, uint16_t offset)
 {
   return (bits(offset, 11, 5) << 25) |
@@ -100,6 +127,38 @@ static uint32_t sd(unsigned int src, unsigned int base, uint16_t offset)
     MATCH_SD;
 }
 
+static uint32_t ld(unsigned int rd, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 0) << 20) |
+    (base << 15) |
+    (bits(rd, 4, 0) << 7) |
+    MATCH_LD;
+}
+
+static uint32_t lw(unsigned int rd, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 0) << 20) |
+    (base << 15) |
+    (bits(rd, 4, 0) << 7) |
+    MATCH_LW;
+}
+
+static uint32_t lh(unsigned int rd, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 0) << 20) |
+    (base << 15) |
+    (bits(rd, 4, 0) << 7) |
+    MATCH_LH;
+}
+
+static uint32_t lb(unsigned int rd, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 0) << 20) |
+    (base << 15) |
+    (bits(rd, 4, 0) << 7) |
+    MATCH_LB;
+}
+
 static uint32_t fsd(unsigned int src, unsigned int base, uint16_t offset)
 {
   return (bits(offset, 11, 5) << 25) |
@@ -109,6 +168,15 @@ static uint32_t fsd(unsigned int src, unsigned int base, uint16_t offset)
     MATCH_FSD;
 }
 
+static uint32_t fld(unsigned int src, unsigned int base, uint16_t offset)
+{
+  return (bits(offset, 11, 5) << 25) |
+    (bits(src, 4, 0) << 20) |
+    (base << 15) |
+    (bits(offset, 4, 0) << 7) |
+    MATCH_FLD;
+}
+
 static uint32_t addi(unsigned int dest, unsigned int src, uint16_t imm)
 {
   return (bits(imm, 11, 0) << 20) |
@@ -117,6 +185,14 @@ static uint32_t addi(unsigned int dest, unsigned int src, uint16_t imm)
     MATCH_ADDI;
 }
 
+static uint32_t ori(unsigned int dest, unsigned int src, uint16_t imm)
+{
+  return (bits(imm, 11, 0) << 20) |
+    (src << 15) |
+    (dest << 7) |
+    MATCH_ORI;
+}
+
 static uint32_t nop()
 {
   return addi(0, 0, 0);
@@ -193,25 +269,124 @@ void circular_buffer_t<T>::append(const T *src, unsigned int count)
 class halt_op_t : public operation_t
 {
   public:
-    halt_op_t(gdbserver_t& gdbserver) : operation_t(gdbserver) {};
-
-    bool start()
-    {
-      // TODO: For now we just assume the target is 64-bit.
-      gs.write_debug_ram(0, csrsi(DCSR_ADDRESS, DCSR_HALT_MASK));
-      gs.write_debug_ram(1, csrr(S0, DPC_ADDRESS));
-      gs.write_debug_ram(2, sd(S0, 0, (uint16_t) DEBUG_RAM_START));
-      gs.write_debug_ram(3, csrr(S0, DCSR_ADDRESS));
-      gs.write_debug_ram(4, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 8));
-      gs.write_debug_ram(5, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*5))));
-      gs.set_interrupt(0);
+    halt_op_t(gdbserver_t& gdbserver, bool send_status=false) :
+      operation_t(gdbserver), send_status(send_status) {};
+
+    bool perform_step(unsigned int step) {
+      switch (step) {
+        case 0:
+          // TODO: For now we just assume the target is 64-bit.
+          gs.write_debug_ram(0, csrsi(CSR_DCSR, DCSR_HALT));
+          gs.write_debug_ram(1, csrr(S0, CSR_DPC));
+          gs.write_debug_ram(2, sd(S0, 0, (uint16_t) DEBUG_RAM_START));
+          gs.write_debug_ram(3, csrr(S0, CSR_MSTATUS));
+          gs.write_debug_ram(4, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 8));
+          gs.write_debug_ram(5, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*5))));
+          gs.set_interrupt(0);
+          // We could read more registers here, but only on 64-bit targets. I'm
+          // trying to keep The patterns here usable for 32-bit ISAs as well.
+          return false;
+
+        case 1:
+          gs.dpc = ((uint64_t) gs.read_debug_ram(1) << 32) | gs.read_debug_ram(0);
+          gs.mstatus = ((uint64_t) gs.read_debug_ram(3) << 32) | gs.read_debug_ram(2);
+          gs.write_debug_ram(0, csrr(S0, CSR_DCSR));
+          gs.write_debug_ram(1, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+          gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*6))));
+          gs.set_interrupt(0);
+          return false;
+
+        case 2:
+          gs.dcsr = ((uint64_t) gs.read_debug_ram(5) << 32) | gs.read_debug_ram(4);
+
+          gs.sptbr_valid = false;
+          gs.pte_cache.clear();
+
+          if (send_status) {
+            switch (get_field(gs.dcsr, DCSR_CAUSE)) {
+              case DCSR_CAUSE_NONE:
+                fprintf(stderr, "Internal error. Processor halted without reason.\n");
+                abort();
+
+              case DCSR_CAUSE_DEBUGINT:
+                gs.send_packet("S02");   // Pretend program received SIGINT.
+                break;
+
+              case DCSR_CAUSE_HWBP:
+              case DCSR_CAUSE_STEP:
+              case DCSR_CAUSE_HALT:
+                // There's no gdb code for this.
+                gs.send_packet("T05");
+                break;
+              case DCSR_CAUSE_SWBP:
+                gs.send_packet("T05swbreak:;");
+                break;
+            }
+          }
+
+          return true;
+      }
       return false;
     }
 
-    bool step()
-    {
-      return true;
+  private:
+    bool send_status;
+};
+
+class continue_op_t : public operation_t
+{
+  public:
+    continue_op_t(gdbserver_t& gdbserver, bool single_step) :
+      operation_t(gdbserver), single_step(single_step) {};
+
+    bool perform_step(unsigned int step) {
+      switch (step) {
+        case 0:
+          gs.write_debug_ram(0, ld(S0, 0, (uint16_t) DEBUG_RAM_START+16));
+          gs.write_debug_ram(1, csrw(S0, CSR_DPC));
+          if (gs.fence_i_required) {
+            gs.write_debug_ram(2, fence_i());
+            gs.write_debug_ram(3, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*3))));
+            gs.fence_i_required = false;
+          } else {
+            gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+          }
+          gs.write_debug_ram(4, gs.dpc);
+          gs.write_debug_ram(5, gs.dpc >> 32);
+          gs.set_interrupt(0);
+          return false;
+
+        case 1:
+          gs.write_debug_ram(0, ld(S0, 0, (uint16_t) DEBUG_RAM_START+16));
+          gs.write_debug_ram(1, csrw(S0, CSR_MSTATUS));
+          gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+          gs.write_debug_ram(4, gs.mstatus);
+          gs.write_debug_ram(5, gs.mstatus >> 32);
+          gs.set_interrupt(0);
+          return false;
+
+        case 2:
+          gs.write_debug_ram(0, lw(S0, 0, (uint16_t) DEBUG_RAM_START+16));
+          gs.write_debug_ram(1, csrw(S0, CSR_DCSR));
+          gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+
+          reg_t dcsr = set_field(gs.dcsr, DCSR_HALT, 0);
+          dcsr = set_field(dcsr, DCSR_STEP, single_step);
+          // Software breakpoints should go here.
+          dcsr = set_field(dcsr, DCSR_EBREAKM, 1);
+          dcsr = set_field(dcsr, DCSR_EBREAKH, 1);
+          dcsr = set_field(dcsr, DCSR_EBREAKS, 1);
+          dcsr = set_field(dcsr, DCSR_EBREAKU, 1);
+          gs.write_debug_ram(4, dcsr);
+
+          gs.set_interrupt(0);
+          return true;
+      }
+      return false;
     }
+
+  private:
+    bool single_step;
 };
 
 class general_registers_read_op_t : public operation_t
@@ -230,46 +405,46 @@ class general_registers_read_op_t : public operation_t
 
   public:
     general_registers_read_op_t(gdbserver_t& gdbserver) :
-      operation_t(gdbserver), current_reg(0) {};
+      operation_t(gdbserver) {};
 
-    bool start()
+    bool perform_step(unsigned int step)
     {
-      gs.start_packet();
+      if (step == 0) {
+        gs.start_packet();
 
-      // x0 is always zero.
-      gs.send((reg_t) 0);
+        // x0 is always zero.
+        gs.send((reg_t) 0);
 
-      gs.write_debug_ram(0, sd(1, 0, (uint16_t) DEBUG_RAM_START + 16));
-      gs.write_debug_ram(1, sd(2, 0, (uint16_t) DEBUG_RAM_START + 0));
-      gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
-      gs.set_interrupt(0);
-      current_reg = 1;
-      return false;
-    }
+        gs.write_debug_ram(0, sd(1, 0, (uint16_t) DEBUG_RAM_START + 16));
+        gs.write_debug_ram(1, sd(2, 0, (uint16_t) DEBUG_RAM_START + 0));
+        gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+        gs.set_interrupt(0);
+        return false;
+      }
 
-    bool step()
-    {
-      fprintf(stderr, "step %d\n", current_reg);
       gs.send(((uint64_t) gs.read_debug_ram(5) << 32) | gs.read_debug_ram(4));
-      if (current_reg >= 31) {
+      if (step >= 16) {
         gs.end_packet();
         return true;
       }
 
       gs.send(((uint64_t) gs.read_debug_ram(1) << 32) | gs.read_debug_ram(0));
 
-      current_reg += 2;
-      // TODO properly read s0 and s1
-      gs.write_debug_ram(0, sd(current_reg, 0, (uint16_t) DEBUG_RAM_START + 16));
-      gs.write_debug_ram(1, sd(current_reg+1, 0, (uint16_t) DEBUG_RAM_START + 0));
-      gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+      unsigned int current_reg = 2 * step + 1;
+      unsigned int i = 0;
+      if (current_reg == S1) {
+        gs.write_debug_ram(i++, ld(S1, 0, (uint16_t) DEBUG_RAM_END - 8));
+      }
+      gs.write_debug_ram(i++, sd(current_reg, 0, (uint16_t) DEBUG_RAM_START + 16));
+      if (current_reg + 1 == S0) {
+        gs.write_debug_ram(i++, csrr(S0, CSR_DSCRATCH));
+      }
+      gs.write_debug_ram(i++, sd(current_reg+1, 0, (uint16_t) DEBUG_RAM_START + 0));
+      gs.write_debug_ram(i, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*i))));
       gs.set_interrupt(0);
 
       return false;
     }
-
-  private:
-    unsigned int current_reg;
 };
 
 class register_read_op_t : public operation_t
@@ -278,43 +453,420 @@ class register_read_op_t : public operation_t
     register_read_op_t(gdbserver_t& gdbserver, unsigned int reg) :
       operation_t(gdbserver), reg(reg) {};
 
-    bool start()
+    bool perform_step(unsigned int step)
     {
-      if (reg >= REG_XPR0 && reg <= REG_XPR31) {
-        die("handle_register_read");
-        // send(p->state.XPR[reg - REG_XPR0]);
-      } else if (reg == REG_PC) {
-        gs.write_debug_ram(0, csrr(S0, DPC_ADDRESS));
-        gs.write_debug_ram(1, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+      switch (step) {
+        case 0:
+          if (reg >= REG_XPR0 && reg <= REG_XPR31) {
+            die("handle_register_read");
+            // send(p->state.XPR[reg - REG_XPR0]);
+          } else if (reg == REG_PC) {
+            gs.start_packet();
+            gs.send(gs.dpc);
+            gs.end_packet();
+            return true;
+          } else if (reg >= REG_FPR0 && reg <= REG_FPR31) {
+            // send(p->state.FPR[reg - REG_FPR0]);
+            gs.write_debug_ram(0, fsd(reg - REG_FPR0, 0, (uint16_t) DEBUG_RAM_START + 16));
+            gs.write_debug_ram(1, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*1))));
+          } else if (reg >= REG_CSR0 && reg <= REG_CSR4095) {
+            gs.write_debug_ram(0, csrr(S0, reg - REG_CSR0));
+            gs.write_debug_ram(1, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+            gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+            // If we hit an exception reading the CSR, we'll end up returning ~0 as
+            // the register's value, which is what we want. (Right?)
+            gs.write_debug_ram(4, 0xffffffff);
+            gs.write_debug_ram(5, 0xffffffff);
+          } else {
+            gs.send_packet("E02");
+            return true;
+          }
+          gs.set_interrupt(0);
+          return false;
+
+        case 1:
+          gs.start_packet();
+          gs.send(((uint64_t) gs.read_debug_ram(5) << 32) | gs.read_debug_ram(4));
+          gs.end_packet();
+          return true;
+      }
+      return false;
+    }
+
+  private:
+    unsigned int reg;
+};
+
+class register_write_op_t : public operation_t
+{
+  public:
+    register_write_op_t(gdbserver_t& gdbserver, unsigned int reg, reg_t value) :
+      operation_t(gdbserver), reg(reg), value(value) {};
+
+    bool perform_step(unsigned int step)
+    {
+      gs.write_debug_ram(0, ld(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+      gs.write_debug_ram(4, value);
+      gs.write_debug_ram(5, value >> 32);
+      if (reg == S0) {
+        gs.write_debug_ram(1, csrw(S0, CSR_DSCRATCH));
         gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+      } else if (reg == S1) {
+        gs.write_debug_ram(1, sd(S0, 0, (uint16_t) DEBUG_RAM_END - 8));
+        gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+      } else if (reg >= REG_XPR0 && reg <= REG_XPR31) {
+        gs.write_debug_ram(1, addi(reg, S0, 0));
+        gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+      } else if (reg == REG_PC) {
+        gs.dpc = value;
+        return true;
       } else if (reg >= REG_FPR0 && reg <= REG_FPR31) {
         // send(p->state.FPR[reg - REG_FPR0]);
-        gs.write_debug_ram(0, fsd(reg - REG_FPR0, 0, (uint16_t) DEBUG_RAM_START + 16));
+        gs.write_debug_ram(0, fld(reg - REG_FPR0, 0, (uint16_t) DEBUG_RAM_START + 16));
         gs.write_debug_ram(1, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*1))));
       } else if (reg >= REG_CSR0 && reg <= REG_CSR4095) {
-        gs.write_debug_ram(0, csrr(S0, reg - REG_CSR0));
-        gs.write_debug_ram(1, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+        gs.write_debug_ram(1, csrw(S0, reg - REG_CSR0));
         gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+        if (reg == REG_CSR0 + CSR_SPTBR) {
+          gs.sptbr = value;
+          gs.sptbr_valid = true;
+        }
       } else {
         gs.send_packet("E02");
         return true;
       }
-
       gs.set_interrupt(0);
+      gs.send_packet("OK");
+      return true;
+    }
 
-      return false;
+  private:
+    unsigned int reg;
+    reg_t value;
+};
+
+class memory_read_op_t : public operation_t
+{
+  public:
+    // Read length bytes from vaddr, storing the result into data.
+    // If data is NULL, send the result straight to gdb.
+    memory_read_op_t(gdbserver_t& gdbserver, reg_t vaddr, unsigned int length,
+        unsigned char *data=NULL) :
+      operation_t(gdbserver), vaddr(vaddr), length(length), data(data) {};
+
+    bool perform_step(unsigned int step)
+    {
+      if (step == 0) {
+        // address goes in S0
+        paddr = gs.translate(vaddr);
+        access_size = (paddr % length);
+        if (access_size == 0)
+          access_size = length;
+        if (access_size > 8)
+          access_size = 8;
+
+        gs.write_debug_ram(0, ld(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+        switch (access_size) {
+          case 1:
+            gs.write_debug_ram(1, lb(S1, S0, 0));
+            break;
+          case 2:
+            gs.write_debug_ram(1, lh(S1, S0, 0));
+            break;
+          case 4:
+            gs.write_debug_ram(1, lw(S1, S0, 0));
+            break;
+          case 8:
+            gs.write_debug_ram(1, ld(S1, S0, 0));
+            break;
+        }
+        gs.write_debug_ram(2, sd(S1, 0, (uint16_t) DEBUG_RAM_START + 24));
+        gs.write_debug_ram(3, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*3))));
+        gs.write_debug_ram(4, paddr);
+        gs.write_debug_ram(5, paddr >> 32);
+        gs.set_interrupt(0);
+
+        if (!data) {
+          gs.start_packet();
+        }
+        return false;
+      }
+
+      char buffer[3];
+      reg_t value = ((uint64_t) gs.read_debug_ram(7) << 32) | gs.read_debug_ram(6);
+      for (unsigned int i = 0; i < access_size; i++) {
+        if (data) {
+          *(data++) = value & 0xff;
+          fprintf(stderr, "%02x", (unsigned int) (value & 0xff));
+        } else {
+          sprintf(buffer, "%02x", (unsigned int) (value & 0xff));
+          gs.send(buffer);
+        }
+        value >>= 8;
+      }
+      if (data)
+        fprintf(stderr, "\n");
+      length -= access_size;
+      paddr += access_size;
+
+      if (length == 0) {
+        if (!data) {
+          gs.end_packet();
+        }
+        return true;
+      } else {
+        gs.write_debug_ram(4, paddr);
+        gs.write_debug_ram(5, paddr >> 32);
+        gs.set_interrupt(0);
+        return false;
+      }
     }
 
-    bool step()
+  private:
+    reg_t vaddr;
+    unsigned int length;
+    unsigned char* data;
+    reg_t paddr;
+    unsigned int access_size;
+};
+
+class memory_write_op_t : public operation_t
+{
+  public:
+    memory_write_op_t(gdbserver_t& gdbserver, reg_t vaddr, unsigned int length,
+        const unsigned char *data) :
+      operation_t(gdbserver), vaddr(vaddr), offset(0), length(length), data(data) {};
+
+    ~memory_write_op_t() {
+      delete[] data;
+    }
+
+    bool perform_step(unsigned int step)
     {
-      gs.start_packet();
-      gs.send(((uint64_t) gs.read_debug_ram(5) << 32) | gs.read_debug_ram(4));
-      gs.end_packet();
+      reg_t paddr = gs.translate(vaddr);
+      if (step == 0) {
+        // address goes in S0
+        access_size = (paddr % length);
+        if (access_size == 0)
+          access_size = length;
+        if (access_size > 8)
+          access_size = 8;
+
+        fprintf(stderr, "write to 0x%lx -> 0x%lx: ", vaddr, paddr);
+        for (unsigned int i = 0; i < length; i++)
+          fprintf(stderr, "%02x", data[i]);
+        fprintf(stderr, "\n");
+
+        gs.write_debug_ram(0, ld(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+        switch (access_size) {
+          case 1:
+            gs.write_debug_ram(1, lb(S1, 0, (uint16_t) DEBUG_RAM_START + 24));
+            gs.write_debug_ram(2, sb(S1, S0, 0));
+            gs.write_debug_ram(6, data[0]);
+            break;
+          case 2:
+            gs.write_debug_ram(1, lh(S1, 0, (uint16_t) DEBUG_RAM_START + 24));
+            gs.write_debug_ram(2, sh(S1, S0, 0));
+            gs.write_debug_ram(6, data[0] | (data[1] << 8));
+            break;
+          case 4:
+            gs.write_debug_ram(1, lw(S1, 0, (uint16_t) DEBUG_RAM_START + 24));
+            gs.write_debug_ram(2, sw(S1, S0, 0));
+            gs.write_debug_ram(6, data[0] | (data[1] << 8) |
+                (data[2] << 16) | (data[3] << 24));
+            break;
+          case 8:
+            gs.write_debug_ram(1, ld(S1, 0, (uint16_t) DEBUG_RAM_START + 24));
+            gs.write_debug_ram(2, sd(S1, S0, 0));
+            gs.write_debug_ram(6, data[0] | (data[1] << 8) |
+                (data[2] << 16) | (data[3] << 24));
+            gs.write_debug_ram(7, data[4] | (data[5] << 8) |
+                (data[6] << 16) | (data[7] << 24));
+            break;
+          default:
+            gs.send_packet("E12");
+            return true;
+        }
+        gs.write_debug_ram(3, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*3))));
+        gs.write_debug_ram(4, paddr);
+        gs.write_debug_ram(5, paddr >> 32);
+        gs.set_interrupt(0);
+
+        return false;
+      }
+
+      if (gs.read_debug_ram(DEBUG_RAM_SIZE / 4 - 1)) {
+        fprintf(stderr, "Exception happened while writing to 0x%lx -> 0x%lx\n",
+            vaddr, paddr);
+      }
+
+      offset += access_size;
+      if (offset >= length) {
+        gs.send_packet("OK");
+        return true;
+      } else {
+        const unsigned char *d = data + offset;
+        switch (access_size) {
+          case 1:
+            gs.write_debug_ram(6, d[0]);
+            break;
+          case 2:
+            gs.write_debug_ram(6, d[0] | (d[1] << 8));
+            break;
+          case 4:
+            gs.write_debug_ram(6, d[0] | (d[1] << 8) |
+                (d[2] << 16) | (d[3] << 24));
+            break;
+          case 8:
+            gs.write_debug_ram(6, d[0] | (d[1] << 8) |
+                (d[2] << 16) | (d[3] << 24));
+            gs.write_debug_ram(7, d[4] | (d[5] << 8) |
+                (d[6] << 16) | (d[7] << 24));
+            break;
+          default:
+            gs.send_packet("E12");
+            return true;
+        }
+        gs.write_debug_ram(4, paddr + offset);
+        gs.write_debug_ram(5, (paddr + offset) >> 32);
+        gs.set_interrupt(0);
+        return false;
+      }
+    }
+
+  private:
+    reg_t vaddr;
+    unsigned int offset;
+    unsigned int length;
+    unsigned int access_size;
+    const unsigned char *data;
+};
+
+class collect_translation_info_op_t : public operation_t
+{
+  public:
+    // Read sufficient information from the target into gdbserver structures so
+    // that it's possible to translate vaddr, vaddr+length, and all addresses
+    // in between to physical addresses.
+    collect_translation_info_op_t(gdbserver_t& gdbserver, reg_t vaddr, size_t length) :
+      operation_t(gdbserver), state(STATE_START), vaddr(vaddr), length(length) {};
+
+    bool perform_step(unsigned int step)
+    {
+      unsigned int vm = gs.virtual_memory();
+
+      if (step == 0) {
+        switch (vm) {
+          case VM_MBARE:
+            // Nothing to be done.
+            return true;
+
+          case VM_SV32:
+            levels = 2;
+            ptidxbits = 10;
+            ptesize = 4;
+            break;
+          case VM_SV39:
+            levels = 3;
+            ptidxbits = 9;
+            ptesize = 8;
+            break;
+          case VM_SV48:
+            levels = 4;
+            ptidxbits = 9;
+            ptesize = 8;
+            break;
+
+          default:
+            {
+              char buf[100];
+              sprintf(buf, "VM mode %d is not supported by gdbserver.cc.", vm);
+              die(buf);
+              return true;        // die doesn't return, but gcc doesn't know that.
+            }
+        }
+      }
+
+      // Perform any reads from the just-completed action.
+      switch (state) {
+        case STATE_START:
+          break;
+        case STATE_READ_SPTBR:
+          gs.sptbr = ((uint64_t) gs.read_debug_ram(5) << 32) | gs.read_debug_ram(4);
+          gs.sptbr_valid = true;
+          break;
+        case STATE_READ_PTE:
+          gs.pte_cache[pte_addr] = ((uint64_t) gs.read_debug_ram(5) << 32) |
+            gs.read_debug_ram(4);
+          fprintf(stderr, "pte_cache[0x%lx] = 0x%lx\n", pte_addr, gs.pte_cache[pte_addr]);
+          break;
+      }
+
+      // Set up the next action.
+      // We only get here for VM_SV32/39/38.
+
+      if (!gs.sptbr_valid) {
+        state = STATE_READ_SPTBR;
+        gs.write_debug_ram(0, csrr(S0, CSR_SPTBR));
+        gs.write_debug_ram(1, sd(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+        gs.write_debug_ram(2, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*2))));
+        gs.set_interrupt(0);
+        return false;
+      }
+
+      reg_t base = gs.sptbr << PGSHIFT;
+      int ptshift = (levels - 1) * ptidxbits;
+      for (unsigned int i = 0; i < levels; i++, ptshift -= ptidxbits) {
+        reg_t idx = (vaddr >> (PGSHIFT + ptshift)) & ((1 << ptidxbits) - 1);
+
+        pte_addr = base + idx * ptesize;
+        auto it = gs.pte_cache.find(pte_addr);
+        if (it == gs.pte_cache.end()) {
+          state = STATE_READ_PTE;
+          if (ptesize == 4) {
+            gs.write_debug_ram(0, lw(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+            gs.write_debug_ram(1, lw(S1, S0, 0));
+            gs.write_debug_ram(2, sd(S1, 0, (uint16_t) DEBUG_RAM_START + 16));
+          } else {
+            gs.write_debug_ram(0, ld(S0, 0, (uint16_t) DEBUG_RAM_START + 16));
+            gs.write_debug_ram(1, ld(S1, S0, 0));
+            gs.write_debug_ram(2, sd(S1, 0, (uint16_t) DEBUG_RAM_START + 16));
+          }
+          gs.write_debug_ram(3, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 4*3))));
+          gs.write_debug_ram(4, pte_addr);
+          gs.write_debug_ram(5, pte_addr >> 32);
+          gs.set_interrupt(0);
+          return false;
+        }
+
+        reg_t pte = gs.pte_cache[pte_addr];
+        reg_t ppn = pte >> PTE_PPN_SHIFT;
+
+        if (PTE_TABLE(pte)) { // next level of page table
+          base = ppn << PGSHIFT;
+        } else {
+          // We've collected all the data required for the translation.
+          return true;
+        }
+      }
+      fprintf(stderr,
+          "ERROR: gdbserver couldn't find appropriate PTEs to translate 0x%lx\n",
+          vaddr);
       return true;
     }
 
   private:
-    unsigned int reg;
+    enum {
+      STATE_START,
+      STATE_READ_SPTBR,
+      STATE_READ_PTE
+    } state;
+    reg_t vaddr;
+    size_t length;
+    unsigned int levels;
+    unsigned int ptidxbits;
+    unsigned int ptesize;
+    reg_t pte_addr;
 };
 
 ////////////////////////////// gdbserver itself
@@ -322,8 +874,7 @@ class register_read_op_t : public operation_t
 gdbserver_t::gdbserver_t(uint16_t port, sim_t *sim) :
   sim(sim),
   client_fd(0),
-  recv_buf(64 * 1024), send_buf(64 * 1024),
-  operation(NULL)
+  recv_buf(64 * 1024), send_buf(64 * 1024)
 {
   socket_fd = socket(AF_INET, SOCK_STREAM, 0);
   if (socket_fd == -1) {
@@ -356,6 +907,92 @@ gdbserver_t::gdbserver_t(uint16_t port, sim_t *sim) :
   }
 }
 
+reg_t gdbserver_t::translate(reg_t vaddr)
+{
+  unsigned int vm = virtual_memory();
+  unsigned int levels, ptidxbits, ptesize;
+
+  switch (vm) {
+    case VM_MBARE:
+      return vaddr;
+
+    case VM_SV32:
+      levels = 2;
+      ptidxbits = 10;
+      ptesize = 4;
+      break;
+    case VM_SV39:
+      levels = 3;
+      ptidxbits = 9;
+      ptesize = 8;
+      break;
+    case VM_SV48:
+      levels = 4;
+      ptidxbits = 9;
+      ptesize = 8;
+      break;
+
+    default:
+      {
+        char buf[100];
+        sprintf(buf, "VM mode %d is not supported by gdbserver.cc.", vm);
+        die(buf);
+        return true;        // die doesn't return, but gcc doesn't know that.
+      }
+  }
+
+  // Handle page tables here. There's a bunch of duplicated code with
+  // collect_translation_info_op_t. :-(
+  reg_t base = sptbr << PGSHIFT;
+  int ptshift = (levels - 1) * ptidxbits;
+  for (unsigned int i = 0; i < levels; i++, ptshift -= ptidxbits) {
+    reg_t idx = (vaddr >> (PGSHIFT + ptshift)) & ((1 << ptidxbits) - 1);
+
+    reg_t pte_addr = base + idx * ptesize;
+    auto it = pte_cache.find(pte_addr);
+    if (it == pte_cache.end()) {
+      fprintf(stderr, "ERROR: gdbserver tried to translate 0x%lx without first "
+          "collecting the relevant PTEs.\n", vaddr);
+      die("gdbserver_t::translate()");
+    }
+
+    reg_t pte = pte_cache[pte_addr];
+    reg_t ppn = pte >> PTE_PPN_SHIFT;
+
+    if (PTE_TABLE(pte)) { // next level of page table
+      base = ppn << PGSHIFT;
+    } else {
+      // We've collected all the data required for the translation.
+      reg_t vpn = vaddr >> PGSHIFT;
+      reg_t paddr = (ppn | (vpn & ((reg_t(1) << ptshift) - 1))) << PGSHIFT;
+      paddr += vaddr & (PGSIZE-1);
+      fprintf(stderr, "gdbserver translate 0x%lx -> 0x%lx\n", vaddr, paddr);
+      return paddr;
+    }
+  }
+
+  fprintf(stderr, "ERROR: gdbserver tried to translate 0x%lx but the relevant "
+      "PTEs are invalid.\n", vaddr);
+  // TODO: Is it better to throw an exception here?
+  return -1;
+}
+
+unsigned int gdbserver_t::privilege_mode()
+{
+  unsigned int mode = get_field(dcsr, DCSR_PRV);
+  if (get_field(mstatus, MSTATUS_MPRV))
+    mode = get_field(mstatus, MSTATUS_MPP);
+  return mode;
+}
+
+unsigned int gdbserver_t::virtual_memory()
+{
+  unsigned int mode = privilege_mode();
+  if (mode == PRV_M)
+    return VM_MBARE;
+  return get_field(mstatus, MSTATUS_VM);
+}
+
 void gdbserver_t::write_debug_ram(unsigned int index, uint32_t value)
 {
   sim->debug_module.ram_write32(index, value);
@@ -366,14 +1003,9 @@ uint32_t gdbserver_t::read_debug_ram(unsigned int index)
   return sim->debug_module.ram_read32(index);
 }
 
-void gdbserver_t::set_operation(operation_t* operation)
+void gdbserver_t::add_operation(operation_t* operation)
 {
-  assert(this->operation == NULL || operation == NULL);
-  if (operation && operation->start()) {
-    delete operation;
-  } else {
-    this->operation = operation;
-  }
+  operation_queue.push(operation);
 }
 
 void gdbserver_t::accept()
@@ -394,7 +1026,7 @@ void gdbserver_t::accept()
     extended_mode = false;
 
     // gdb wants the core to be halted when it attaches.
-    set_operation(new halt_op_t(*this));
+    add_operation(new halt_op_t(*this));
   }
 }
 
@@ -457,7 +1089,7 @@ void print_packet(const std::vector<uint8_t> &packet)
     if (c >= ' ' and c <= '~')
       fprintf(stderr, "%c", c);
     else
-      fprintf(stderr, "\\x%x", c);
+      fprintf(stderr, "\\x%02x", c);
   }
   fprintf(stderr, "\n");
 }
@@ -546,7 +1178,7 @@ void gdbserver_t::handle_halt_reason(const std::vector<uint8_t> &packet)
 
 void gdbserver_t::handle_general_registers_read(const std::vector<uint8_t> &packet)
 {
-  set_operation(new general_registers_read_op_t(*this));
+  add_operation(new general_registers_read_op_t(*this));
 }
 
 void gdbserver_t::set_interrupt(uint32_t hartid) {
@@ -613,7 +1245,7 @@ void gdbserver_t::handle_register_read(const std::vector<uint8_t> &packet)
   if (*iter != '#')
     return send_packet("E01");
 
-  set_operation(new register_read_op_t(*this, n));
+  add_operation(new register_read_op_t(*this, n));
 }
 
 void gdbserver_t::handle_register_write(const std::vector<uint8_t> &packet)
@@ -632,24 +1264,7 @@ void gdbserver_t::handle_register_write(const std::vector<uint8_t> &packet)
 
   processor_t *p = sim->get_core(0);
 
-  die("handle_register_write");
-  /*
-  if (n >= REG_XPR0 && n <= REG_XPR31) {
-    p->state.XPR.write(n - REG_XPR0, value);
-  } else if (n == REG_PC) {
-    p->state.pc = value;
-  } else if (n >= REG_FPR0 && n <= REG_FPR31) {
-    p->state.FPR.write(n - REG_FPR0, value);
-  } else if (n >= REG_CSR0 && n <= REG_CSR4095) {
-    try {
-      p->set_csr(n - REG_CSR0, value);
-    } catch(trap_t& t) {
-      return send_packet("EFF");
-    }
-  } else {
-    return send_packet("E07");
-  }
-  */
+  add_operation(new register_write_op_t(*this, n, value));
 
   return send_packet("OK");
 }
@@ -666,16 +1281,8 @@ void gdbserver_t::handle_memory_read(const std::vector<uint8_t> &packet)
   if (*iter != '#')
     return send_packet("E11");
 
-  start_packet();
-  char buffer[3];
-  processor_t *p = sim->get_core(0);
-  mmu_t* mmu = sim->debug_mmu;
-
-  for (reg_t i = 0; i < length; i++) {
-    sprintf(buffer, "%02x", mmu->load_uint8(address + i));
-    send(buffer);
-  }
-  end_packet();
+  add_operation(new collect_translation_info_op_t(*this, address, length));
+  add_operation(new memory_read_op_t(*this, address, length));
 }
 
 void gdbserver_t::handle_memory_binary_write(const std::vector<uint8_t> &packet)
@@ -691,19 +1298,37 @@ void gdbserver_t::handle_memory_binary_write(const std::vector<uint8_t> &packet)
     return send_packet("E21");
   iter++;
 
-  processor_t *p = sim->get_core(0);
-  mmu_t* mmu = sim->debug_mmu;
+  if (length == 0) {
+    return send_packet("OK");
+  }
+
+  unsigned char *data = new unsigned char[length];
   for (unsigned int i = 0; i < length; i++) {
     if (iter == packet.end()) {
       return send_packet("E22");
     }
-    mmu->store_uint8(address + i, *iter);
+    uint8_t c = *iter;
     iter++;
+    if (c == '}') {
+      // The binary data representation uses 7d (ascii ‘}’) as an escape
+      // character. Any escaped byte is transmitted as the escape character
+      // followed by the original character XORed with 0x20. For example, the
+      // byte 0x7d would be transmitted as the two bytes 0x7d 0x5d. The bytes
+      // 0x23 (ascii ‘#’), 0x24 (ascii ‘$’), and 0x7d (ascii ‘}’) must always
+      // be escaped.
+      if (iter == packet.end()) {
+        return send_packet("E23");
+      }
+      c = (*iter) ^ 0x20;
+      iter++;
+    }
+    data[i] = c;
   }
   if (*iter != '#')
     return send_packet("E4b"); // EOVERFLOW
 
-  send_packet("OK");
+  add_operation(new collect_translation_info_op_t(*this, address, length));
+  add_operation(new memory_write_op_t(*this, address, length, data));
 }
 
 void gdbserver_t::handle_continue(const std::vector<uint8_t> &packet)
@@ -712,24 +1337,17 @@ void gdbserver_t::handle_continue(const std::vector<uint8_t> &packet)
   processor_t *p = sim->get_core(0);
   if (packet[2] != '#') {
     std::vector<uint8_t>::const_iterator iter = packet.begin() + 2;
-    die("handle_continue");
-    // p->state.pc = consume_hex_number(iter, packet.end());
+    dpc = consume_hex_number(iter, packet.end());
     if (*iter != '#')
       return send_packet("E30");
   }
 
-  write_debug_ram(0, csrci(DCSR_ADDRESS, DCSR_HALT_MASK));
-  write_debug_ram(1, jal(0, (uint32_t) (DEBUG_ROM_RESUME - (DEBUG_RAM_START + 1*5))));
-  set_interrupt(0);
-
-  // TODO p->set_halted(false, HR_NONE);
-  // TODO running = true;
+  add_operation(new continue_op_t(*this, false));
 }
 
 void gdbserver_t::handle_step(const std::vector<uint8_t> &packet)
 {
   // s [addr]
-  processor_t *p = sim->get_core(0);
   if (packet[2] != '#') {
     std::vector<uint8_t>::const_iterator iter = packet.begin() + 2;
     die("handle_step");
@@ -738,8 +1356,7 @@ void gdbserver_t::handle_step(const std::vector<uint8_t> &packet)
       return send_packet("E40");
   }
 
-  // TODO: p->set_single_step(true);
-  // TODO running = true;
+  add_operation(new continue_op_t(*this, true));
 }
 
 void gdbserver_t::handle_kill(const std::vector<uint8_t> &packet)
@@ -758,28 +1375,6 @@ void gdbserver_t::handle_extended(const std::vector<uint8_t> &packet)
   extended_mode = true;
 }
 
-void software_breakpoint_t::insert(mmu_t* mmu)
-{
-  if (size == 2) {
-    instruction = mmu->load_uint16(address);
-    mmu->store_uint16(address, C_EBREAK);
-  } else {
-    instruction = mmu->load_uint32(address);
-    mmu->store_uint32(address, EBREAK);
-  }
-  fprintf(stderr, ">>> Read %x from %lx\n", instruction, address);
-}
-
-void software_breakpoint_t::remove(mmu_t* mmu)
-{
-  fprintf(stderr, ">>> write %x to %lx\n", instruction, address);
-  if (size == 2) {
-    mmu->store_uint16(address, instruction);
-  } else {
-    mmu->store_uint32(address, instruction);
-  }
-}
-
 void gdbserver_t::handle_breakpoint(const std::vector<uint8_t> &packet)
 {
   // insert: Z type,addr,kind
@@ -805,22 +1400,36 @@ void gdbserver_t::handle_breakpoint(const std::vector<uint8_t> &packet)
     return send_packet("E53");
   }
 
-  processor_t *p = sim->get_core(0);
-  die("handle_breakpoint");
-  /*
-  mmu_t* mmu = p->mmu;
+  fence_i_required = true;
+  add_operation(new collect_translation_info_op_t(*this, bp.address, bp.size));
   if (insert) {
-    bp.insert(mmu);
-    breakpoints[bp.address] = bp;
+    unsigned char* swbp = new unsigned char[4];
+    if (bp.size == 2) {
+      swbp[0] = C_EBREAK & 0xff;
+      swbp[1] = (C_EBREAK >> 8) & 0xff;
+    } else {
+      swbp[0] = EBREAK & 0xff;
+      swbp[1] = (EBREAK >> 8) & 0xff;
+      swbp[2] = (EBREAK >> 16) & 0xff;
+      swbp[3] = (EBREAK >> 24) & 0xff;
+    }
+
+    breakpoints[bp.address] = new software_breakpoint_t(bp);
+    add_operation(new memory_read_op_t(*this, bp.address, bp.size,
+          breakpoints[bp.address]->instruction));
+    add_operation(new memory_write_op_t(*this, bp.address, bp.size, swbp));
 
   } else {
-    bp = breakpoints[bp.address];
-    bp.remove(mmu);
+    software_breakpoint_t *found_bp;
+    found_bp = breakpoints[bp.address];
+    unsigned char* instruction = new unsigned char[4];
+    memcpy(instruction, found_bp->instruction, 4);
+    add_operation(new memory_write_op_t(*this, found_bp->address,
+          found_bp->size, instruction));
     breakpoints.erase(bp.address);
+    delete found_bp;
   }
-  mmu->flush_icache();
-  sim->debug_mmu->flush_icache();
-  */
+
   return send_packet("OK");
 }
 
@@ -871,8 +1480,8 @@ void gdbserver_t::handle_packet(const std::vector<uint8_t> &packet)
       return handle_halt_reason(packet);
     case 'g':
       return handle_general_registers_read(packet);
-    case 'k':
-      return handle_kill(packet);
+//    case 'k':
+//      return handle_kill(packet);
     case 'm':
       return handle_memory_read(packet);
 //    case 'M':
@@ -904,9 +1513,7 @@ void gdbserver_t::handle_packet(const std::vector<uint8_t> &packet)
 void gdbserver_t::handle_interrupt()
 {
   processor_t *p = sim->get_core(0);
-  // TODO p->set_halted(true, HR_INTERRUPT);
-  send_packet("S02");   // Pretend program received SIGINT.
-  // TODO running = false;
+  add_operation(new halt_op_t(*this, true));
 }
 
 void gdbserver_t::handle()
@@ -916,48 +1523,19 @@ void gdbserver_t::handle()
 
     bool interrupt = sim->debug_module.get_interrupt(0);
 
-    if (!interrupt) {
-      if (operation && operation->step()) {
+    if (!interrupt && !operation_queue.empty()) {
+      operation_t *operation = operation_queue.front();
+      if (operation->step()) {
+        operation_queue.pop();
         delete operation;
-        set_operation(NULL);
       }
-
-      /*
-      switch (state) {
-        case STATE_HALTING:
-          // gdb requested a halt and now it's done.
-          send_packet("T05");
-          fprintf(stderr, "DPC: 0x%x\n", read_debug_ram(0));
-          fprintf(stderr, "DCSR: 0x%x\n", read_debug_ram(2));
-          state = STATE_HALTED;
-          break;
-      }
-      */
     }
 
-    /* TODO
-    if (running && p->halted) {
-      // The core was running, but now it's halted. Better tell gdb.
-      switch (p->halt_reason) {
-        case HR_NONE:
-          fprintf(stderr, "Internal error. Processor halted without reason.\n");
-          abort();
-        case HR_STEPPED:
-        case HR_INTERRUPT:
-        case HR_CMDLINE:
-        case HR_ATTACHED:
-          // There's no gdb code for this.
-          send_packet("T05");
-          break;
-        case HR_SWBP:
-          send_packet("T05swbreak:;");
-          break;
-      }
-      send_packet("T00");
-      // TODO: Actually include register values here
-      running = false;
+    bool halt_notification = sim->debug_module.get_halt_notification(0);
+    if (halt_notification) {
+      sim->debug_module.clear_halt_notification(0);
+      add_operation(new halt_op_t(*this, true));
     }
-      */
 
     this->read();
     this->write();
@@ -966,7 +1544,7 @@ void gdbserver_t::handle()
     this->accept();
   }
 
-  if (!operation) {
+  if (operation_queue.empty()) {
     this->process_requests();
   }
 }