Advertisement
Guest User

Android logcat binary reader example

a guest
Nov 19th, 2010
424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # Quick example of a binary logcat reader which fails when it encounters one of
  3. # the unexpected extra bytes occouring in some logcat entries.
  4. #
  5. # Run as:
  6. # $ adb logcat -d -B | ./readlog.py -
  7. #
  8. # - Hal
  9.  
  10. from struct import unpack
  11. from collections import namedtuple
  12. from sys import argv, stdin, stderr, stdout
  13. import re
  14.  
  15. # Define a log entry
  16. LogEntry = namedtuple("LogEntry", "payloadlen pid tid time nanotime priority \
  17. tag message")
  18. # hackish soloution to finding the two null terminated strings in our payload
  19. payloadpattern = re.compile("^(.*)\x00(.*)\x00$")
  20.  
  21. def readEntry(logstream):
  22.     rawheader = logstream.read(20)
  23.     if len(rawheader) < 20: # check for EOF
  24.         return None
  25.    
  26.     # Unpack the header into a 2 byte length and 4 4 byte ints (unsigned)
  27.     header = unpack("HxxIIII", rawheader)
  28.     payload = logstream.read(header[0]) # first element of header is msg len
  29.     if len(payload) < header[0]:
  30.         raise Exception("Insufficient bytes read for payload. Expected: "\
  31.                 + "{0}, got: {1}".format(1, 2))
  32.     priority, = unpack("B", payload[0])
  33.    
  34.     # Find the two null terminated strings with our regex
  35.     match = payloadpattern.match(payload[1:])
  36.     if not match:
  37.         raise Exception("Invalid payload")
  38.     tag, message = match.groups()
  39.    
  40.     return LogEntry(header[0], header[1], header[2], header[3], header[4], \
  41.         priority, tag, message)
  42.  
  43. if __name__ == "__main__":
  44.     if len(argv) != 2:
  45.         print >> stderr, "Usage: {0} binarylogfile\n(or '-' to read stdin)"\
  46.             .format(argv[0])
  47.         exit(1)
  48.     if argv[1] == "-":
  49.         file = stdin
  50.     else:
  51.         file = open(argv[1])
  52.    
  53.     # Read all the entries
  54.     while True:
  55.         entry = readEntry(file)
  56.         if entry:
  57.             print entry
  58.         else:
  59.             break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement