Пример #1
0
 def setup(self):
   """
             input            output
   Program ---------> pyGDB -----------> SEGGER GDB -------> Device
   """
   
   # get segger gdb
   self._segger = GdbServer('/opt/SEGGER/JLink_Linux_V443c') #, printter=self.print_segger)
   #sleep(3)
   
   # get our gdb server
   self._output = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   self._output.connect(self._segger.get_gdb_host())
   self._input = self.request
   
   # SWO?
   if self._enable_swo:
     # send the magic
     self._output.setblocking(1)
     self._input.setblocking(1)
     self._output.sendall(
         bytes(
             self._segger.swoStart(GdbServer.TRANSPORT_SWD, SWO_PROTO, SWO_SPEED), 'ASCII'
           )
       )
     self._output.recv(len(self._segger.SWO_REPLY))
     self.print_gdb('Sent maigc and burnt reply')
     # start SWO reciver
     self._swo = SwoServer(self._segger.get_swv_host(), printter=self.print_swo)
   
   # clean up the sockets
   self._input.setblocking(0)
   self._output.setblocking(0)
Пример #2
0
    def setup(self):
        """
              input            output
    Program ---------> pyGDB -----------> SEGGER GDB -------> Device
    """

        # get segger gdb
        self._segger = GdbServer("/opt/SEGGER/JLink_Linux_V443c")  # , printter=self.print_segger)
        # sleep(3)

        # get our gdb server
        self._output = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._output.connect(self._segger.get_gdb_host())
        self._input = self.request

        # SWO?
        if self._enable_swo:
            # send the magic
            self._output.setblocking(1)
            self._input.setblocking(1)
            self._output.sendall(bytes(self._segger.swoStart(GdbServer.TRANSPORT_SWD, SWO_PROTO, SWO_SPEED), "ASCII"))
            self._output.recv(len(self._segger.SWO_REPLY))
            self.print_gdb("Sent maigc and burnt reply")
            # start SWO reciver
            self._swo = SwoServer(self._segger.get_swv_host(), printter=self.print_swo)

        # clean up the sockets
        self._input.setblocking(0)
        self._output.setblocking(0)
Пример #3
0
class GdbProxyHandler(socketserver.BaseRequestHandler):
  """
  The RequestHandler class for our server.

  It is instantiated once per connection to the server, and must
  override the handle() method to implement communication to the
  client.
  """
  
  currentHandle = None
  
  def __init__(self, request, client_address, server, enable_swo=False):
    self._input = None
    self._output = None
    self._run = True
    self._segger = None
    self._enable_swo = enable_swo
    self._finished = False
    self._plock = threading.Lock()
    
    # make sure there is only one connection
    if GdbProxyHandler.currentHandle != None:
      self.print_gdb('New connection killing old connection ...')
      GdbProxyHandler.currentHandle.close(wait=True)
      self.print_gdb(' OK\n')
    GdbProxyHandler.currentHandle = self
    
    self.print_gdb('New connection')
    
    socketserver.BaseRequestHandler.__init__(self, request, client_address, server)
  
  def print_gdb(self, to_print):
    self._print_all(to_print, 0)
  
  def print_segger(self, to_print):
    self._print_all(to_print, 40)
  
  def print_swo(self, to_print):
    self._print_all(to_print, 80)
  
  def _print_all(self, to_print, padding):
    self._plock.acquire()
    for line in to_print.split('\n'):
      print( (' '*padding) + line )
    self._plock.release()
  
  def setup(self):
    """
              input            output
    Program ---------> pyGDB -----------> SEGGER GDB -------> Device
    """
    
    # get segger gdb
    self._segger = GdbServer('/opt/SEGGER/JLink_Linux_V443c') #, printter=self.print_segger)
    #sleep(3)
    
    # get our gdb server
    self._output = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self._output.connect(self._segger.get_gdb_host())
    self._input = self.request
    
    # SWO?
    if self._enable_swo:
      # send the magic
      self._output.setblocking(1)
      self._input.setblocking(1)
      self._output.sendall(
          bytes(
              self._segger.swoStart(GdbServer.TRANSPORT_SWD, SWO_PROTO, SWO_SPEED), 'ASCII'
            )
        )
      self._output.recv(len(self._segger.SWO_REPLY))
      self.print_gdb('Sent maigc and burnt reply')
      # start SWO reciver
      self._swo = SwoServer(self._segger.get_swv_host(), printter=self.print_swo)
    
    # clean up the sockets
    self._input.setblocking(0)
    self._output.setblocking(0)
  
  def _read_input(self, size=4096):
    try:
      return self._input.recv(size)
    except Exception as e:
      if e.args[0] != 11:
        raise e
      else:
        return bytes()
  
  def _read_output(self, size=4096):
    try:
      return self._output.recv(size)
    except Exception as e:
      if e.args[0] != 11:
        raise e
      else:
        return bytes()
  
  def handle(self):
    last5inbuf = bytes()
    inbuf      = bytes()
    outbuf     = bytes()
    
    while self._run: # and self._segger.is_alive():
      
      # read the input
      buf = self._read_input()
      inbuf += buf
      last5inbuf += buf
      last5inbuf = last5inbuf[-5:]
      sbuf = str(buf, 'ASCII', 'replace')
      while len(sbuf) > 0:
        if len(sbuf) > 40:
          self.print_gdb('>: ' + sbuf[:36] + ' ...')
          sbuf = sbuf[36:]
        else:
          self.print_gdb('>: ' + sbuf)
          sbuf = ''
      
      # read the output
      outbuf += self._read_output()
      sbuf = str(buf, 'ASCII', 'replace')
      while len(sbuf) > 0:
        if len(sbuf) > 40:
          self.print_gdb('>: ' + sbuf[:36] + ' ...')
          sbuf = sbuf[36:]
        else:
          self.print_gdb('>: ' + sbuf)
          sbuf = ''
      
      # send the input
      sent = self._input.send(outbuf)
      outbuf = outbuf[sent:]
      
      # send the output
      sent = self._output.send(inbuf)
      inbuf = inbuf[sent:]
      
      # find out if the session has ended
      if last5inbuf == bytes('$k#6b', 'ASCII'):
        self.print_gdb('found kill request')
        sleep(1)
        try:
          outbuf += self._output.recv(4096)
        except Exception as e:
          pass
        try:
          sent = self._input.send(outbuf)
        except Exception as e:
          pass
        self._run = False
    
    if self._output != None and last5inbuf != bytes('$k#6b', 'ASCII'):
      self.print_gdb('Trying to safely close by detaching ...')
      self._output.send(bytes(self._formGdbMsg('D'), 'ASCII'))
  
  # TODO
  @staticmethod
  def _formGdbMsg(msg):
    msg = functools.reduce(lambda x, y: x+y, map(lambda x: x in '#$}' and '}'+chr(ord(x)^0x20) or x, msg))
    chksum =sum(map(ord, msg))%256
    return '${msg}#{chksum:02X}'.format(msg=msg, chksum=chksum)
  
  def close(self, wait=False):
    self._run = False
    if not wait:
      return
    while not self._finished:
      pass
  
  def finish(self):
    if self._input != None:
      self._input.close()
      self._input = None
    if self._output != None:
      self._output.close()
      self._output = None
    if self._swo != None:
      self._swo.stop()
      self._swo = None
    if self.currentHandle != None:
      self.currentHandle = None
    if self._segger != None:
      self._segger.stop()
      self._segger = None
    print('Connection closed')
    gc.collect() # help the gc
    print('Waiting for other end ...')
    sleep(1)
    print('.. OK')
    self._finished = True
  
  def __del__(self):
    if GdbProxyHandler.currentHandle == self:
      GdbProxyHandler.currentHandle = None
Пример #4
0
class GdbProxyHandler(socketserver.BaseRequestHandler):
    """
  The RequestHandler class for our server.

  It is instantiated once per connection to the server, and must
  override the handle() method to implement communication to the
  client.
  """

    currentHandle = None

    def __init__(self, request, client_address, server, enable_swo=False):
        self._input = None
        self._output = None
        self._run = True
        self._segger = None
        self._enable_swo = enable_swo
        self._finished = False
        self._plock = threading.Lock()

        # make sure there is only one connection
        if GdbProxyHandler.currentHandle != None:
            self.print_gdb("New connection killing old connection ...")
            GdbProxyHandler.currentHandle.close(wait=True)
            self.print_gdb(" OK\n")
        GdbProxyHandler.currentHandle = self

        self.print_gdb("New connection")

        socketserver.BaseRequestHandler.__init__(self, request, client_address, server)

    def print_gdb(self, to_print):
        self._print_all(to_print, 0)

    def print_segger(self, to_print):
        self._print_all(to_print, 40)

    def print_swo(self, to_print):
        self._print_all(to_print, 80)

    def _print_all(self, to_print, padding):
        self._plock.acquire()
        for line in to_print.split("\n"):
            print((" " * padding) + line)
        self._plock.release()

    def setup(self):
        """
              input            output
    Program ---------> pyGDB -----------> SEGGER GDB -------> Device
    """

        # get segger gdb
        self._segger = GdbServer("/opt/SEGGER/JLink_Linux_V443c")  # , printter=self.print_segger)
        # sleep(3)

        # get our gdb server
        self._output = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._output.connect(self._segger.get_gdb_host())
        self._input = self.request

        # SWO?
        if self._enable_swo:
            # send the magic
            self._output.setblocking(1)
            self._input.setblocking(1)
            self._output.sendall(bytes(self._segger.swoStart(GdbServer.TRANSPORT_SWD, SWO_PROTO, SWO_SPEED), "ASCII"))
            self._output.recv(len(self._segger.SWO_REPLY))
            self.print_gdb("Sent maigc and burnt reply")
            # start SWO reciver
            self._swo = SwoServer(self._segger.get_swv_host(), printter=self.print_swo)

        # clean up the sockets
        self._input.setblocking(0)
        self._output.setblocking(0)

    def _read_input(self, size=4096):
        try:
            return self._input.recv(size)
        except Exception as e:
            if e.args[0] != 11:
                raise e
            else:
                return bytes()

    def _read_output(self, size=4096):
        try:
            return self._output.recv(size)
        except Exception as e:
            if e.args[0] != 11:
                raise e
            else:
                return bytes()

    def handle(self):
        last5inbuf = bytes()
        inbuf = bytes()
        outbuf = bytes()

        while self._run:  # and self._segger.is_alive():

            # read the input
            buf = self._read_input()
            inbuf += buf
            last5inbuf += buf
            last5inbuf = last5inbuf[-5:]
            sbuf = str(buf, "ASCII", "replace")
            while len(sbuf) > 0:
                if len(sbuf) > 40:
                    self.print_gdb(">: " + sbuf[:36] + " ...")
                    sbuf = sbuf[36:]
                else:
                    self.print_gdb(">: " + sbuf)
                    sbuf = ""

            # read the output
            outbuf += self._read_output()
            sbuf = str(buf, "ASCII", "replace")
            while len(sbuf) > 0:
                if len(sbuf) > 40:
                    self.print_gdb(">: " + sbuf[:36] + " ...")
                    sbuf = sbuf[36:]
                else:
                    self.print_gdb(">: " + sbuf)
                    sbuf = ""

            # send the input
            sent = self._input.send(outbuf)
            outbuf = outbuf[sent:]

            # send the output
            sent = self._output.send(inbuf)
            inbuf = inbuf[sent:]

            # find out if the session has ended
            if last5inbuf == bytes("$k#6b", "ASCII"):
                self.print_gdb("found kill request")
                sleep(1)
                try:
                    outbuf += self._output.recv(4096)
                except Exception as e:
                    pass
                try:
                    sent = self._input.send(outbuf)
                except Exception as e:
                    pass
                self._run = False

        if self._output != None and last5inbuf != bytes("$k#6b", "ASCII"):
            self.print_gdb("Trying to safely close by detaching ...")
            self._output.send(bytes(self._formGdbMsg("D"), "ASCII"))

    # TODO
    @staticmethod
    def _formGdbMsg(msg):
        msg = functools.reduce(lambda x, y: x + y, map(lambda x: x in "#$}" and "}" + chr(ord(x) ^ 0x20) or x, msg))
        chksum = sum(map(ord, msg)) % 256
        return "${msg}#{chksum:02X}".format(msg=msg, chksum=chksum)

    def close(self, wait=False):
        self._run = False
        if not wait:
            return
        while not self._finished:
            pass

    def finish(self):
        if self._input != None:
            self._input.close()
            self._input = None
        if self._output != None:
            self._output.close()
            self._output = None
        if self._swo != None:
            self._swo.stop()
            self._swo = None
        if self.currentHandle != None:
            self.currentHandle = None
        if self._segger != None:
            self._segger.stop()
            self._segger = None
        print("Connection closed")
        gc.collect()  # help the gc
        print("Waiting for other end ...")
        sleep(1)
        print(".. OK")
        self._finished = True

    def __del__(self):
        if GdbProxyHandler.currentHandle == self:
            GdbProxyHandler.currentHandle = None