Skip to content

Commit

Permalink
Merge pull request #993 from ColdWindScholar/main
Browse files Browse the repository at this point in the history
Fix "OSError: Unable to find libfuse" on Windows and Optimized the code and fixed other bugs
  • Loading branch information
bkerler authored May 12, 2024
2 parents df9e179 + 9fd9a5b commit 491f930
Show file tree
Hide file tree
Showing 46 changed files with 582 additions and 687 deletions.
18 changes: 4 additions & 14 deletions mtk
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,6 @@ cmds = {
"script": "Run multiple commands using text script"
}


def showcommands():
print(info)
print("-----------------------------------\n")
print("Available commands are:\n")
for cmd in cmds:
print("%20s" % (cmd) + ":\t" + cmds[cmd])
print()


if __name__ == '__main__':
print(info)
print("")
Expand Down Expand Up @@ -620,12 +610,12 @@ if __name__ == '__main__':
parser_ess.add_argument('--da_addr', help='Set a specific da payload addr')
parser_ess.add_argument('--brom_addr', help='Set a specific brom payload addr')
parser_ess.add_argument('--ptype',
help='Set the payload type ( "amonet","kamakiri","kamakiri2","carbonara" kamakiri2/da used by default)')
help='Set the payload type ( "amonet","kamakiri","kamakiri2","carbonara" kamakiri2/da used by default)')
parser_ess.add_argument('--preloader', help='Set the preloader filename for dram config')
parser_ess.add_argument('--verifystage2', help='Verify if stage2 data has been written correctly')
parser_ess.add_argument('--parttype', help='Partition type\n' +
'\t\tEMMC: [user, boot1, boot2, gp1, gp2, gp3, gp4, rpmb]' +
'\t\tUFS: [lu0, lu1, lu2, lu0_lu1]')
'\t\tEMMC: [user, boot1, boot2, gp1, gp2, gp3, gp4, rpmb]' +
'\t\tUFS: [lu0, lu1, lu2, lu0_lu1]')
parser_ess.add_argument('--filename', help='Optional filename')
parser_ess.add_argument('--crash', help='Enforce crash if device is in pl mode to enter brom mode')
parser_ess.add_argument('--socid', help='Read Soc ID')
Expand Down Expand Up @@ -947,7 +937,7 @@ if __name__ == '__main__':
args = parser.parse_args()
cmd = args.cmd
if cmd not in cmds:
showcommands()
parser.print_help()
exit(0)

mtk = Main(args).run(parser)
2 changes: 1 addition & 1 deletion mtk_console.spec
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ block_cipher = None
a = Analysis(['mtk'],
pathex=[],
binaries=[],
datas=[('mtkclient/Windows/*', '.'), ('mtkclient/payloads', 'mtkclient/payloads'), ('mtkclient/Loader', 'mtkclient/Loader')],
datas=[('mtkclient/Windows/*', '.'), ('mtkclient/payloads', 'mtkclient/payloads'), ('mtkclient/Loader', 'mtkclient/Loader'), ('mtkclient/Library/Filesystem/bin', 'mtkclient/Library/Filesystem/bin')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
Expand Down
111 changes: 21 additions & 90 deletions mtk_gui
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def load_translations(application):
locale = QLocale.system()
translator = QTranslator(application)
directory = os.path.dirname(__file__)
lang = 'mtkclient/gui/i18n/' + locale.name()
lang = f'mtkclient/gui/i18n/{locale.name()}'
if locale.name() == "en_NL":
lang = lang.replace("en_NL", "nl_NL")
# lang = 'mtkclient/gui/i18n/fr_FR'
Expand Down Expand Up @@ -154,10 +154,7 @@ class MainWindow(QMainWindow):
global lock
lock.acquire()
doneBytes = 0
if "currentPartitionSizeDone" in self.Status:
curpartBytes = self.Status["currentPartitionSizeDone"]
else:
curpartBytes = self.Status["currentPartitionSize"]
curpartBytes = self.Status[f"currentPartitionSize{'Done' if 'currentPartitionSizeDone' in self.Status else ''}"]

if "allPartitions" in self.Status:
for partition in self.Status["allPartitions"]:
Expand All @@ -168,11 +165,7 @@ class MainWindow(QMainWindow):
fullPercentageDone = int((doneBytes / totalBytes) * 100)
self.ui.fullProgress.setValue(fullPercentageDone)
timeinfototal = self.timeEstTotal.update(fullPercentageDone, 100)
self.ui.fullProgressText.setText("<table width='100%'><tr><td><b>Total:</b> " +
convert_size(doneBytes) + " / " + convert_size(totalBytes) +
"</td><td align='right'>" + timeinfototal +
QCoreApplication.translate("main", " left") +
"</td></tr></table>")
self.ui.fullProgressText.setText(f"<table width='100%'><tr><td><b>Total:</b> {convert_size(doneBytes)} / {convert_size(totalBytes)}</td><td align='right'>{timeinfototal}{QCoreApplication.translate('main', ' left')}</td></tr></table>")
else:
partBytes = self.Status["currentPartitionSize"]
doneBytes = self.Status["currentPartitionSizeDone"]
Expand Down Expand Up @@ -244,21 +237,21 @@ class MainWindow(QMainWindow):
self.readflash.disableButtonsSignal.connect(self.disablebuttons)
self.ui.readpartitionsbtn.clicked.connect(self.readflash.dumpPartition)
self.ui.readselectallcheckbox.clicked.connect(self.readflash.selectAll)
self.ui.readpreloaderbtn.clicked.connect(self.on_readpreloader)
self.ui.readflashbtn.clicked.connect(self.on_readfullflash)
self.ui.readrpmbbtn.clicked.connect(self.on_readrpmb)
self.ui.readboot2btn.clicked.connect(self.on_readboot2)
self.ui.readpreloaderbtn.clicked.connect(lambda: self.readflash.dumpFlash("boot1"))
self.ui.readflashbtn.clicked.connect(lambda: self.readflash.dumpFlash("user"))
self.ui.readrpmbbtn.clicked.connect(lambda: self.readflash.dumpFlash("rpmb"))
self.ui.readboot2btn.clicked.connect(lambda: self.readflash.dumpFlash("boot2"))

def initkeys(self):
self.genkeys = generateKeysMenu(self.ui, self, self.devhandler.da_handler, self.sendToLog)
self.ui.generatekeybtn.clicked.connect(self.on_generatekeys)
self.ui.generatekeybtn.clicked.connect(self.genkeys.generateKeys)
self.genkeys.enableButtonsSignal.connect(self.enablebuttons)
self.genkeys.disableButtonsSignal.connect(self.disablebuttons)

def initunlock(self):
self.unlock = UnlockMenu(self.ui, self, self.devhandler.da_handler, self.sendToLog)
self.ui.unlockbutton.clicked.connect(self.on_unlock)
self.ui.lockbutton.clicked.connect(self.on_lock)
self.ui.unlockbutton.clicked.connect(lambda: self.unlock.unlock("unlock"))
self.ui.lockbutton.clicked.connect(lambda: self.unlock.unlock("lock"))
self.unlock.enableButtonsSignal.connect(self.enablebuttons)
self.unlock.disableButtonsSignal.connect(self.disablebuttons)

Expand All @@ -267,21 +260,21 @@ class MainWindow(QMainWindow):
self.eraseflash.enableButtonsSignal.connect(self.enablebuttons)
self.eraseflash.disableButtonsSignal.connect(self.disablebuttons)
self.ui.eraseselectallpartitionscheckbox.clicked.connect(self.eraseflash.selectAll)
self.ui.erasepartitionsbtn.clicked.connect(self.on_erasepartflash)
self.ui.eraserpmbbtn.clicked.connect(self.on_eraserpmb)
self.ui.erasepreloaderbtn.clicked.connect(self.on_erasepreloader)
self.ui.eraseboot2btn.clicked.connect(self.on_eraseboot2)
self.ui.erasepartitionsbtn.clicked.connect(self.eraseflash.erasePartition)
self.ui.eraserpmbbtn.clicked.connect(lambda: self.eraseflash.eraseFlash("rpmb"))
self.ui.erasepreloaderbtn.clicked.connect(lambda: self.eraseflash.eraseFlash("boot1"))
self.ui.eraseboot2btn.clicked.connect(lambda: self.eraseflash.eraseFlash("boot2"))

def initwrite(self):
self.writeflash = WriteFlashWindow(self.ui, self, self.devhandler.da_handler, self.sendToLog)
self.writeflash.enableButtonsSignal.connect(self.enablebuttons)
self.writeflash.disableButtonsSignal.connect(self.disablebuttons)
self.ui.writeselectfromdir.clicked.connect(self.writeflash.selectFiles)
self.ui.writeflashbtn.clicked.connect(self.on_writefullflash)
self.ui.writepartbtn.clicked.connect(self.on_writepartflash)
self.ui.writeboot2btn.clicked.connect(self.on_writeboot2)
self.ui.writepreloaderbtn.clicked.connect(self.on_writepreloader)
self.ui.writerpmbbtn.clicked.connect(self.on_writerpmb)
self.ui.writeflashbtn.clicked.connect(lambda: self.writeflash.writeFlash("user"))
self.ui.writepartbtn.clicked.connect(self.writeflash.writePartition)
self.ui.writeboot2btn.clicked.connect(lambda: self.writeflash.writeFlash("boot2"))
self.ui.writepreloaderbtn.clicked.connect(lambda: self.writeflash.writeFlash("boot1"))
self.ui.writerpmbbtn.clicked.connect(lambda: self.writeflash.writeFlash("rpmb"))

@Slot(str)
def update_status_text(self, text):
Expand Down Expand Up @@ -338,12 +331,7 @@ class MainWindow(QMainWindow):

def getpartitions(self):
data, guid_gpt = self.devhandler.da_handler.mtk.daloader.get_gpt()
if guid_gpt is None:
print("Error reading gpt")
self.ui.readtitle.setText(QCoreApplication.translate("main", "Error reading gpt"))
else:
self.ui.readtitle.setText(QCoreApplication.translate("main", "Select partitions to dump"))

self.ui.readtitle.setText(QCoreApplication.translate("main", "Error reading gpt" if guid_gpt is None else "Select partitions to dump"))
readpartitionListWidgetVBox = QVBoxLayout()
readpartitionListWidget = QWidget(self)
readpartitionListWidget.setLayout(readpartitionListWidgetVBox)
Expand Down Expand Up @@ -421,65 +409,8 @@ class MainWindow(QMainWindow):
lineedit.setDisabled(False)
return fname

def on_writefullflash(self):
self.writeflash.writeFlash("user")
return

def on_writepreloader(self):
self.writeflash.writeFlash("boot1")
return

def on_writeboot2(self):
self.writeflash.writeFlash("boot2")
return

def on_writerpmb(self):
self.writeflash.writeFlash("rpmb")
return

def on_writepartflash(self):
self.writeflash.writePartition()
return

def on_erasepartflash(self):
self.eraseflash.erasePartition()
return

def on_eraseboot2(self):
self.eraseflash.eraseBoot2()

def on_erasepreloader(self):
self.eraseflash.erasePreloader()

def on_eraserpmb(self):
self.eraseflash.eraseRpmb()

def on_generatekeys(self):
self.genkeys.generateKeys()

def on_unlock(self):
self.unlock.unlock("unlock")

def on_lock(self):
self.unlock.unlock("lock")

def on_readpreloader(self):
self.readflash.dumpFlash("boot1")

def on_readboot2(self):
self.readflash.dumpFlash("boot2")
return

def on_readfullflash(self):
self.readflash.dumpFlash("user")

def on_readrpmb(self):
self.readflash.dumpFlash("rpmb")
return

def sendToLog(self, info):
t = time.localtime()
self.ui.logBox.appendPlainText(time.strftime("[%H:%M:%S", t) + "]: " + info)
self.ui.logBox.appendPlainText(time.strftime("[%H:%M:%S", time.localtime()) + "]: " + info)
self.ui.logBox.verticalScrollBar().setValue(self.ui.logBox.verticalScrollBar().maximum())

def sendToProgress(self, progress):
Expand Down
2 changes: 1 addition & 1 deletion mtk_standalone.spec
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ block_cipher = None
a = Analysis(['mtk_gui'],
pathex=[],
binaries=[],
datas=[('mtkclient/gui/images', 'mtkclient/gui/images'), ('mtkclient/Windows/*', '.'), ('mtkclient/payloads', 'mtkclient/payloads'), ('mtkclient/Loader', 'mtkclient/Loader')],
datas=[('mtkclient/gui/images', 'mtkclient/gui/images'), ('mtkclient/Windows/*', '.'), ('mtkclient/payloads', 'mtkclient/payloads'), ('mtkclient/Loader', 'mtkclient/Loader'), ('mtkclient/Library/Filesystem/bin', 'mtkclient/Library/Filesystem/bin')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
Expand Down
2 changes: 1 addition & 1 deletion mtkclient/Library/Connection/seriallib.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def detectdevices(self):
for usbid in self.portconfig:
if port.pid == usbid[1] and port.vid == usbid[0]:
# portid = port.location[-1:]
print(f"Detected {hex(port.vid)}:{hex(port.pid)} device at: " + port.device)
print(f"Detected {hex(port.vid)}:{hex(port.pid)} device at: {port.device}")
ids.append(port.device)
return sorted(ids)

Expand Down
36 changes: 17 additions & 19 deletions mtkclient/Library/Connection/usblib.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ class CDC_CMDS:

class usb_class(DeviceClass):

def load_windows_dll(self):
@staticmethod
def load_windows_dll():
if os.name == 'nt':
windows_dir = None
try:
Expand Down Expand Up @@ -142,10 +143,7 @@ def __init__(self, loglevel=logging.INFO, portconfig=None, devclass=-1):
self.backend = None

def set_fast_mode(self, enabled):
if enabled:
self.fast = True
else:
self.fast = False
self.fast = bool(enabled)

def verify_data(self, data, pre="RX:"):
if self.__logger.level == logging.DEBUG:
Expand Down Expand Up @@ -207,23 +205,23 @@ def setLineCoding(self, baudrate=None, parity=0, databits=8, stopbits=1):
if stopbits is not None:
if stopbits not in sbits.keys():
valid = ", ".join(str(k) for k in sorted(sbits.keys()))
raise ValueError("Valid stopbits are " + valid)
raise ValueError(f"Valid stopbits are {valid}")
self.stopbits = stopbits
else:
self.stopbits = 0

if databits is not None:
if databits not in dbits:
valid = ", ".join(str(d) for d in sorted(dbits))
raise ValueError("Valid databits are " + valid)
raise ValueError(f"Valid databits are {valid}")
self.databits = databits
else:
self.databits = 0

if parity is not None:
if parity not in pmodes:
valid = ", ".join(str(pm) for pm in sorted(pmodes))
raise ValueError("Valid parity modes are " + valid)
raise ValueError(f"Valid parity modes are {valid}")
self.parity = parity
else:
self.parity = 0
Expand All @@ -234,7 +232,7 @@ def setLineCoding(self, baudrate=None, parity=0, databits=8, stopbits=1):
dif = [abs(br - baudrate) for br in brs]
best = brs[dif.index(min(dif))]
raise ValueError(
"Invalid baudrates, nearest valid is {}".format(best))
f"Invalid baudrates, nearest valid is {best}")
self.baudrate = baudrate

linecode = [
Expand All @@ -254,7 +252,7 @@ def setLineCoding(self, baudrate=None, parity=0, databits=8, stopbits=1):
wlen = self.device.ctrl_transfer(
req_type, CDC_CMDS.SET_LINE_CODING,
data_or_wLength=data, wIndex=1)
self.debug("Linecoding set, {}b sent".format(wlen))
self.debug(f"Linecoding set, {wlen}b sent")

def setbreak(self):
txdir = 0 # 0:OUT, 1:IN
Expand All @@ -264,7 +262,7 @@ def setbreak(self):
wlen = self.device.ctrl_transfer(
bmRequestType=req_type, bRequest=CDC_CMDS.SEND_BREAK,
wValue=0, data_or_wLength=0, wIndex=1)
self.debug("Break set, {}b sent".format(wlen))
self.debug(f"Break set, {wlen}b sent")

def setcontrollinestate(self, RTS=None, DTR=None, isFTDI=False):
cmds = CDC_CMDS()
Expand All @@ -284,7 +282,7 @@ def setcontrollinestate(self, RTS=None, DTR=None, isFTDI=False):
wValue=ctrlstate,
wIndex=1,
data_or_wLength=0)
self.debug("Linecoding set, {}b sent".format(wlen))
self.debug(f"Linecoding set, {wlen}b sent")

def flush(self):
return
Expand Down Expand Up @@ -348,7 +346,7 @@ def connect(self, EP_IN=-1, EP_OUT=-1):
self.debug("Detaching kernel driver")
self.device.detach_kernel_driver(0)
except Exception as err:
self.debug("No kernel driver supported: " + str(err))
self.debug(f"No kernel driver supported: {str(err)}")
try:
usb.util.claim_interface(self.device, 0)
except Exception:
Expand All @@ -360,7 +358,7 @@ def connect(self, EP_IN=-1, EP_OUT=-1):
self.debug("Detaching kernel driver")
self.device.detach_kernel_driver(self.interface)
except Exception as err:
self.debug("No kernel driver supported: " + str(err))
self.debug(f"No kernel driver supported: {str(err)}")
try:
if self.interface != 0:
usb.util.claim_interface(self.device, self.interface)
Expand Down Expand Up @@ -720,7 +718,7 @@ def send_htc_adbenable(self):
ret_tag += self.send_mass_storage_command(lun, common_cmnd, USB_DIR_IN, datasize)
if datasize > 0:
data = self.usb.read(datasize, timeout)
print("DATA: " + hexlify(data).decode('utf-8'))
print(f"DATA: {hexlify(data).decode('utf-8')}")
print("Sent HTC adb enable command")

def send_htc_ums_adbenable(self): # HTC10
Expand Down Expand Up @@ -758,7 +756,7 @@ def send_zte_adbenable(self): # zte blade
ret_tag += self.send_mass_storage_command(lun, common_cmnd2, USB_DIR_IN, datasize)
if datasize > 0:
data = self.usb.read(datasize, timeout)
print("DATA: " + hexlify(data).decode('utf-8'))
print(f"DATA: {hexlify(data).decode('utf-8')}")
print("Send HTC adb enable command")

def send_fih_adbenable(self): # motorola xt560, nokia 3.1, #f_mass_storage.c
Expand All @@ -780,7 +778,7 @@ def send_fih_adbenable(self): # motorola xt560, nokia 3.1, #f_mass_storage.c
# ret_tag+=self.send_mass_storage_command(lun, common_cmnd, USB_DIR_IN, 0x600)
if datasize > 0:
data = self.usb.read(datasize, timeout)
print("DATA: " + hexlify(data).decode('utf-8'))
print(f"DATA: {hexlify(data).decode('utf-8')}")
print("Sent FIH adb enable command")
self.usb.close()

Expand All @@ -795,7 +793,7 @@ def send_alcatel_adbenable(self): # Alcatel MW41
self.send_mass_storage_command(lun, common_cmnd, USB_DIR_IN, 0x600)
if datasize > 0:
data = self.usb.read(datasize, timeout)
print("DATA: " + hexlify(data).decode('utf-8'))
print(f"DATA: {hexlify(data).decode('utf-8')}")
print("Sent alcatel adb enable command")
self.usb.close()

Expand All @@ -814,7 +812,7 @@ def send_fih_root(self):
ret_tag += self.send_mass_storage_command(lun, common_cmnd, USB_DIR_IN, 0x600)
if datasize > 0:
data = self.usb.read(datasize, timeout)
print("DATA: " + hexlify(data).decode('utf-8'))
print(f"DATA: {hexlify(data).decode('utf-8')}")
print("Sent FIH root command")
self.usb.close()

Expand Down
Loading

0 comments on commit 491f930

Please sign in to comment.