devmem2.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/python3
  2. # simply a python3 version of the 'devmem2' program written by Jan-Derk Bakker (2010)
  3. # this one is written by Pat Beirne <patb@pbeirne.com>
  4. from mmap import mmap
  5. import os, sys, time, struct
  6. if __name__ == "__main__":
  7. if len(sys.argv) == 1:
  8. print("devmem2: read/write memory location, version 1.0")
  9. print(" python3 version; only operates on 32 bit words (w)")
  10. print(" syntax: devmem2 address [ type [ write-data ]]")
  11. sys.exit(1)
  12. write_mode = False
  13. if len(sys.argv) == 4:
  14. if sys.argv[2] != 'w':
  15. print("error: only w is permitted in the 2nd parameter....32bit word")
  16. sys.exit(1)
  17. try:
  18. write_data = int(sys.argv[3],0)
  19. except:
  20. print("error: the 3rd parameter must be a number, not {}".format(sys.argv[3]))
  21. sys.exit(1)
  22. write_mode = True
  23. try:
  24. address = int(sys.argv[1],0)
  25. except:
  26. print("error: the 1st parameter must be a number, not {}".format(sys.argv[1]))
  27. sys.exit(1)
  28. # print("got past parameter check")
  29. with open("/dev/mem","r+b") as m:
  30. address_page = address & ~0xFFF
  31. address_offset = address & 0xFFF
  32. mem = mmap(m.fileno(), 32, offset = address_page)
  33. # read 4-byte word....often a requirement on ARM devices
  34. read_data = struct.unpack("<L", mem[address_offset: address_offset+4])[0]
  35. print("Value at address {}: {}".format(hex(address),hex(read_data)))
  36. if write_mode == False:
  37. sys.exit(0)
  38. mem[address_offset:address_offset+4] = struct.pack("<L",write_data)
  39. read_data = struct.unpack("<L", mem[address_offset: address_offset+4])[0]
  40. print("Written {}; readback {}".format(hex(write_data),hex(read_data)))
  41. sys.exit(0)