]> sigrok.org Git - libsigrokdecode.git/blobdiff - decoders/usb_packet/pd.py
usb_packet: Handle invalid packets more gracefully.
[libsigrokdecode.git] / decoders / usb_packet / pd.py
index be5429780872e96377da7e903da10c279b105d6d..54c530359f6bb8bf07ce49a4c61871ff78a25fb6 100644 (file)
@@ -143,7 +143,7 @@ def bitstr_to_num(bitstr):
     return int(''.join(l), 2)
 
 class Decoder(srd.Decoder):
-    api_version = 1
+    api_version = 2
     id = 'usb_packet'
     name = 'USB packet'
     longname = 'Universal Serial Bus (LS/FS) packet'
@@ -192,7 +192,6 @@ class Decoder(srd.Decoder):
     )
 
     def __init__(self):
-        self.samplenum = 0
         self.bits = []
         self.packet = []
         self.packet_summary = ''
@@ -221,6 +220,10 @@ class Decoder(srd.Decoder):
         for (bit, ss, es) in self.bits:
             packet += bit
 
+        if len(packet) < 8:
+            self.putp([28, ['Invalid packet (shorter than 8 bits)']])
+            return
+
         # Bits[0:7]: SYNC
         sync = packet[:7 + 1]
         self.ss, self.es = self.bits[0][1], self.bits[7][2]
@@ -234,9 +237,13 @@ class Decoder(srd.Decoder):
             self.putb([0, ['SYNC: %s' % sync, 'SYNC', 'S']])
         self.packet.append(sync)
 
+        if len(packet) < 16:
+            self.putp([28, ['Invalid packet (shorter than 16 bits)']])
+            return
+
         # Bits[8:15]: PID
         pid = packet[8:15 + 1]
-        pidname = pids.get(pid, (pid, ''))[0]
+        pidname = pids.get(pid, ('UNKNOWN', 'Unknown PID'))[0]
         self.ss, self.es = self.bits[8][1], self.bits[15][2]
         self.putpb(['PID', pidname])
         self.putb([2, ['PID: %s' % pidname, pidname, pidname[0]]])
@@ -244,6 +251,10 @@ class Decoder(srd.Decoder):
         self.packet_summary += pidname
 
         if pidname in ('OUT', 'IN', 'SOF', 'SETUP', 'PRE', 'PING'):
+            if len(packet) < 32:
+                self.putp([28, ['Invalid packet (shorter than 32 bits)']])
+                return
+
             if pidname == 'SOF':
                 # Bits[16:26]: Framenum
                 framenum = bitstr_to_num(packet[16:26 + 1])
@@ -290,7 +301,6 @@ class Decoder(srd.Decoder):
                                'DB: %02X' % db, '%02X' % db]])
                 databytes.append(db)
                 self.packet_summary += ' %02X' % db
-                data = data[8:]
             self.packet_summary += ' ]'
 
             # Convenience Python output (no annotation) for all bytes together.
@@ -335,9 +345,7 @@ class Decoder(srd.Decoder):
             elif ptype == 'EOP':
                 self.es_packet = es
                 self.handle_packet()
+                self.packet, self.packet_summary = [], ''
                 self.bits, self.state = [], 'WAIT FOR SOP'
             else:
                 pass # TODO: Error
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-