Skip to content

Instantly share code, notes, and snippets.

@aikoncwd
Created January 10, 2018 09:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aikoncwd/4e6596fdc244b1cdbfd19e3f4558ee68 to your computer and use it in GitHub Desktop.
Save aikoncwd/4e6596fdc244b1cdbfd19e3f4558ee68 to your computer and use it in GitHub Desktop.
Python 3.x - bin2dat.py: Convert Intel CPU microcode binary format to text format.
#!/usr/bin/env python
# coding=utf-8
"""bin2dat.py: Convert Intel CPU microcode binary format to text format."""
__author__ = "H. Fischer"
__copyright__ = "Copyright 2017, HF"
__license__ = "GPL"
__version__ = "3"
import sys
import base64
import re
from tkinter import *
import tkinter.messagebox as mbox
from tkinter.filedialog import askopenfilename
# Microcode file
global filepath_in
filepath_in = "d:\microcode_0xA6.bin"
# CPU ID
global cpuid
cpuid = "m36506e3" # i7-6700K (see http://www.cpu-world.com/cgi-bin/CPUID.pl)
# Microcode version
global version
version = "A6"
global root
root = Tk()
global v
v = StringVar()
def center(win):
win.update_idletasks()
w = win.winfo_screenwidth()
h = win.winfo_screenheight()
size = tuple(int(_) for _ in win.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
win.geometry("%dx%d+%d+%d" % (size + (x, y)))
def getFileName():
v.set(askopenfilename().replace("/", chr(92)))
def act():
root.quit()
def validateInput(input, datatype, pattern):
if not re.search(pattern, input):
win = Tk()
win.wm_withdraw()
mbox.showerror("BIN2DAT - " + datatype, "Invalid " + datatype + ": " + input + " - skipped!")
win.destroy()
return False
else:
return True
def getInput(title, prompt, btnAction, variable):
btnAction = btnAction.lower()
if not (btnAction == "askfn" or btnAction == "submit"):
root.wm_withdraw()
mbox.showerror(title, "Unknown button action: " + btnAction + " - aborted!")
root.quit()
root.destroy()
return("")
root.title(title)
root["padx"] = 20
root["pady"] = 15
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
# Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = prompt
entryLabel.pack(side=LEFT)
v.set(variable)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame, textvariable=v)
entryWidget["width"] = 40
entryWidget.pack(side=LEFT)
textFrame.pack()
# Create Frame to hold the Button(s)
buttonFrame = Frame(root, height="20")
buttonFrame.pack()
# Create action Button(s)
if btnAction == "askfn":
afnButton = Button(buttonFrame, text="Select file", command=getFileName)
afnButton.pack(side=LEFT, padx="8", pady="6")
button = Button(buttonFrame, text="Submit", command=act)
if btnAction == "submit":
button.pack(pady="6")
else:
button.pack(side=LEFT, padx="8", pady="6")
center(root)
root.mainloop()
root.destroy()
return v.get()
if __name__ == "__main__":
# Get and validate user input (microcode filepath, CPU ID, microcode version)
fpa = getInput("BIN2DAT - Microcode file", "Please select the microcode file to convert:", "askfn", filepath_in)
if fpa == "" or not validateInput(fpa, "Microcode file", "^[a-zA-Z]:/*"):
sys.exit(1)
else:
filepath_in = fpa
filepath_in = filepath_in.replace(chr(92), "/")
if filepath_in.find(".") > 0:
filepath_out = filepath_in[0:filepath_in.find(".")]
else:
filepath_out = filepath_in
filepath_out = filepath_out + ".dat"
root = Tk()
v = StringVar()
cid = getInput("BIN2DAT - CPU ID", "Please enter the CPU ID:", "submit", cpuid)
if not validateInput(cid, "CPU ID", "^m[a-fA-F0-9]{7}$|^$"):
sys.exit(1)
else:
cpuid = cid.lower()
if not cpuid == "":
root = Tk()
v = StringVar()
mcv = getInput("BIN2DAT - Microcode version", "Please enter the microcode version:", "submit", version)
if mcv == "" or not validateInput(mcv, "Microcode version", "^[a-fA-F0-9]{2}$"):
sys.exit(1)
else:
version = mcv.lower()
# Perform the conversion
try:
with open(filepath_in, 'rb') as fp, open(filepath_out, 'w') as out:
if not cpuid == "":
out.write("/* " + cpuid + "_000000" + version + ".inc */\n")
while True:
r = []
STOP = False
for i in range(4):
block = fp.read(4)
if not block:
block = b"\0\0\0\0"
STOP = True
if not i:
break
r.append("0x" + base64.b16encode(block[::-1]).decode())
if STOP:
break
out.write(", ".join(r) + ',\n')
except IOError:
win = Tk()
win.wm_withdraw()
mbox.showerror("BIN2DAT", "Unable to process file(s): " + filepath_in + ", " + filepath_out + " - aborted!")
win.destroy()
else:
print("BIN2DAT: Microcode has been successfully converted.")
finally:
try:
out.close()
fp.close()
except Exception:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment