feat: 备份时显示速度和已备份总量
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,804 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# (c) B.Kerler 2018-2024 under GPLv3 license
|
||||
# If you use my code, make sure you refer to my name
|
||||
#
|
||||
# !!!!! If you use this code in commercial products, your product is automatically
|
||||
# GPLv3 and has to be open sourced under GPLv3 as well. !!!!!
|
||||
import codecs
|
||||
import copy
|
||||
import datetime as dt
|
||||
import logging
|
||||
import logging.config
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from io import BytesIO
|
||||
from struct import unpack
|
||||
|
||||
import colorama
|
||||
|
||||
try:
|
||||
from capstone import *
|
||||
except ImportError:
|
||||
print("Capstone library is missing (optional).")
|
||||
try:
|
||||
from keystone import *
|
||||
except ImportError:
|
||||
print("Keystone library is missing (optional).")
|
||||
|
||||
|
||||
def is_windows():
|
||||
if sys.platform == 'win32' or sys.platform == 'win64' or sys.platform == 'winnt':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class structhelper_io:
|
||||
pos = 0
|
||||
|
||||
def __init__(self, data: BytesIO = None, direction='little'):
|
||||
self.data = data
|
||||
self.direction = direction
|
||||
|
||||
def setdata(self, data, offset=0):
|
||||
self.pos = offset
|
||||
self.data = data
|
||||
|
||||
def qword(self):
|
||||
dat = int.from_bytes(self.data.read(8), self.direction)
|
||||
return dat
|
||||
|
||||
def dword(self):
|
||||
dat = int.from_bytes(self.data.read(4), self.direction)
|
||||
return dat
|
||||
|
||||
def dwords(self, dwords=1):
|
||||
dat = [int.from_bytes(self.data.read(4), self.direction) for _ in range(dwords)]
|
||||
return dat
|
||||
|
||||
def short(self):
|
||||
dat = int.from_bytes(self.data.read(2), self.direction)
|
||||
return dat
|
||||
|
||||
def shorts(self, shorts):
|
||||
dat = [int.from_bytes(self.data.read(2), self.direction) for _ in range(shorts)]
|
||||
return dat
|
||||
|
||||
def bytes(self, rlen=1):
|
||||
dat = self.data.read(rlen)
|
||||
if dat == b'':
|
||||
return dat
|
||||
if rlen == 1:
|
||||
return dat[0]
|
||||
return dat
|
||||
|
||||
def string(self, rlen=1):
|
||||
dat = self.data.read(rlen)
|
||||
return dat
|
||||
|
||||
def getpos(self):
|
||||
return self.data.tell()
|
||||
|
||||
def seek(self, pos):
|
||||
self.data.seek(pos)
|
||||
|
||||
|
||||
def find_binary(data, strf, pos=0):
|
||||
t = strf.split(b".")
|
||||
pre = 0
|
||||
offsets = []
|
||||
while pre != -1:
|
||||
pre = data[pos:].find(t[0], pre)
|
||||
if pre == -1:
|
||||
if len(offsets) > 0:
|
||||
for offset in offsets:
|
||||
error = 0
|
||||
rt = offset + len(t[0])
|
||||
for i in range(1, len(t)):
|
||||
if t[i] == b'':
|
||||
rt += 1
|
||||
continue
|
||||
rt += 1
|
||||
prep = data[rt:].find(t[i])
|
||||
if prep != 0:
|
||||
error = 1
|
||||
break
|
||||
rt += len(t[i])
|
||||
if error == 0:
|
||||
return offset + pos
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
offsets.append(pre)
|
||||
pre += 1
|
||||
return None
|
||||
|
||||
|
||||
class progress:
|
||||
def __init__(self, pagesize):
|
||||
self.progtime = 0
|
||||
self.prog = 0
|
||||
self.progpos = 0
|
||||
self.start = time.time()
|
||||
self.pagesize = pagesize
|
||||
|
||||
def calcProcessTime(self, starttime, cur_iter, max_iter):
|
||||
telapsed = time.time() - starttime
|
||||
if telapsed > 0 and cur_iter > 0:
|
||||
testimated = (telapsed / cur_iter) * max_iter
|
||||
finishtime = starttime + testimated
|
||||
finishtime = dt.datetime.fromtimestamp(finishtime).strftime("%H:%M:%S") # in time
|
||||
lefttime = testimated - telapsed # in seconds
|
||||
return int(telapsed), int(lefttime), finishtime
|
||||
else:
|
||||
return 0, 0, ""
|
||||
|
||||
def show_progress(self, prefix, pos, total, display=True):
|
||||
if pos > total:
|
||||
pos = total
|
||||
if pos != 0:
|
||||
prog = round(float(pos) / float(total) * float(100), 1)
|
||||
else:
|
||||
prog = 0
|
||||
if prog == 0:
|
||||
self.prog = 0
|
||||
self.start = time.time()
|
||||
self.progtime = time.time()
|
||||
self.progpos = pos
|
||||
self._emit_bytes(pos, total)
|
||||
if display:
|
||||
print_progress(prog, 100, prefix='Done',
|
||||
suffix=prefix + ' (Sector 0x%X of 0x%X) %0.2f MB/s' %
|
||||
(pos // self.pagesize,
|
||||
total // self.pagesize,
|
||||
0), bar_length=10)
|
||||
|
||||
if prog > self.prog or prog == 100.0:
|
||||
t0 = time.time()
|
||||
if display:
|
||||
tdiff = t0 - self.progtime
|
||||
datasize = (pos - self.progpos) / 1024 / 1024
|
||||
if datasize != 0 and tdiff != 0:
|
||||
try:
|
||||
throughput = datasize / tdiff
|
||||
except:
|
||||
throughput = 0
|
||||
else:
|
||||
throughput = 0
|
||||
telapsed, lefttime, finishtime = self.calcProcessTime(self.start, prog, 100)
|
||||
hinfo = ""
|
||||
if lefttime > 0:
|
||||
sec = lefttime
|
||||
if sec > 60:
|
||||
min = sec // 60
|
||||
sec = sec % 60
|
||||
if min > 60:
|
||||
h = min // 24
|
||||
min = min % 24
|
||||
hinfo = "%02dh:%02dm:%02ds left" % (h, min, sec)
|
||||
else:
|
||||
hinfo = "%02dm:%02ds left" % (min, sec)
|
||||
else:
|
||||
hinfo = "%02ds left" % sec
|
||||
print_progress(prog, 100, prefix='Progress:',
|
||||
suffix=prefix + f' (Sector 0x%X of 0x%X, {hinfo}) %0.2f MB/s' %
|
||||
(pos // self.pagesize,
|
||||
total // self.pagesize,
|
||||
throughput), bar_length=10)
|
||||
self._emit_rate(prefix, pos, t0)
|
||||
self._emit_bytes(pos, total)
|
||||
self.prog = prog
|
||||
self.progpos = pos
|
||||
self.progtime = t0
|
||||
|
||||
def _emit_rate(self, prefix, pos, now):
|
||||
kind = ""
|
||||
lowered = prefix.lower()
|
||||
if lowered.startswith("write"):
|
||||
kind = "W"
|
||||
elif lowered.startswith("read"):
|
||||
kind = "R"
|
||||
if not kind or pos <= 0:
|
||||
return
|
||||
if now - getattr(self, "rate_time", 0) < 0.4:
|
||||
return
|
||||
elapsed = now - self.start
|
||||
if elapsed <= 0:
|
||||
return
|
||||
shown = int(round((pos / 1024 / 1024) / elapsed))
|
||||
if shown < 1:
|
||||
shown = 1
|
||||
self.rate_time = now
|
||||
sys.stdout.write(f"\nFLASHER\tRATE\t{kind}:{shown}mb/s\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
def _emit_bytes(self, pos, total):
|
||||
done = int(getattr(self, "byte_base", 0) + pos)
|
||||
whole = getattr(self, "byte_span", None)
|
||||
whole = int(whole if whole else total)
|
||||
now = time.time()
|
||||
if pos < total and now - getattr(self, "byte_time", 0) < 0.4:
|
||||
return
|
||||
self.byte_time = now
|
||||
sys.stdout.write(f"\nFLASHER\tBYTES\t{done}\t{whole}\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
class structhelper:
|
||||
pos = 0
|
||||
|
||||
def __init__(self, data, pos=0):
|
||||
self.pos = 0
|
||||
self.data = data
|
||||
|
||||
def qword(self, big=False):
|
||||
e = ">" if big else "<"
|
||||
dat = unpack(e + "Q", self.data[self.pos:self.pos + 8])[0]
|
||||
self.pos += 8
|
||||
return dat
|
||||
|
||||
def dword(self, big=False):
|
||||
e = ">" if big else "<"
|
||||
dat = unpack(e + "I", self.data[self.pos:self.pos + 4])[0]
|
||||
self.pos += 4
|
||||
return dat
|
||||
|
||||
def dwords(self, dwords=1, big=False):
|
||||
e = ">" if big else "<"
|
||||
dat = unpack(e + str(dwords) + "I", self.data[self.pos:self.pos + 4 * dwords])
|
||||
self.pos += 4 * dwords
|
||||
return dat
|
||||
|
||||
def qwords(self, qwords=1, big=False):
|
||||
e = ">" if big else "<"
|
||||
dat = unpack(e + str(qwords) + "Q", self.data[self.pos:self.pos + 8 * qwords])
|
||||
self.pos += 8 * qwords
|
||||
return dat
|
||||
|
||||
def short(self, big=False):
|
||||
e = ">" if big else "<"
|
||||
dat = unpack(e + "H", self.data[self.pos:self.pos + 2])[0]
|
||||
self.pos += 2
|
||||
return dat
|
||||
|
||||
def shorts(self, shorts, big=False):
|
||||
e = ">" if big else "<"
|
||||
dat = unpack(e + str(shorts) + "H", self.data[self.pos:self.pos + 2 * shorts])
|
||||
self.pos += 2 * shorts
|
||||
return dat
|
||||
|
||||
def bytes(self, rlen=1):
|
||||
dat = self.data[self.pos:self.pos + rlen]
|
||||
self.pos += rlen
|
||||
if rlen == 1: return dat[0]
|
||||
return dat
|
||||
|
||||
def string(self, rlen=1):
|
||||
dat = self.data[self.pos:self.pos + rlen]
|
||||
self.pos += rlen
|
||||
return dat
|
||||
|
||||
def getpos(self):
|
||||
return self.pos
|
||||
|
||||
def seek(self, pos):
|
||||
self.pos = pos
|
||||
|
||||
|
||||
def do_tcp_server(client, arguments, handler):
|
||||
def tcpprint(arg):
|
||||
if isinstance(arg, bytes) or isinstance(arg, bytearray):
|
||||
return connection.sendall(arg)
|
||||
else:
|
||||
return connection.sendall(bytes(str(arg), 'utf-8'))
|
||||
|
||||
client.printer = tcpprint
|
||||
import socket
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
port = int(arguments["--tcpport"])
|
||||
server_address = ('localhost', port)
|
||||
print('starting up on %s port %s' % server_address)
|
||||
sock.bind(server_address)
|
||||
sock.listen(1)
|
||||
response = None
|
||||
while True:
|
||||
print('waiting for a connection')
|
||||
connection, client_address = sock.accept()
|
||||
try:
|
||||
print('connection from', client_address)
|
||||
while True:
|
||||
data = connection.recv(4096).decode('utf-8')
|
||||
if data == '':
|
||||
break
|
||||
print('received %s' % data)
|
||||
if data:
|
||||
print('handling request')
|
||||
lines = data.split("\n")
|
||||
for line in lines:
|
||||
if ":" in line:
|
||||
cmd = line.split(":")[0]
|
||||
marguments = line.split(":")[1]
|
||||
try:
|
||||
opts = parse_args(cmd, marguments, arguments)
|
||||
except:
|
||||
response = "Wrong arguments\n<NAK>\n"
|
||||
opts = None
|
||||
if opts is not None:
|
||||
if handler(cmd, opts):
|
||||
response = "<ACK>\n"
|
||||
else:
|
||||
response = "<NAK>\n"
|
||||
connection.sendall(bytes(response, 'utf-8'))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def parse_args(cmd, args, mainargs):
|
||||
options = {}
|
||||
opts = None
|
||||
if "," in args:
|
||||
opts = args.split(",")
|
||||
else:
|
||||
opts = [args]
|
||||
for arg in mainargs:
|
||||
if "--" in arg:
|
||||
options[arg] = mainargs[arg]
|
||||
if cmd == "gpt":
|
||||
options["<directory>"] = opts[0]
|
||||
elif cmd == "r":
|
||||
options["<partitionname>"] = opts[0]
|
||||
options["<filename>"] = opts[1]
|
||||
elif cmd == "rl":
|
||||
options["<directory>"] = opts[0]
|
||||
elif cmd == "rf":
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "rs":
|
||||
options["<start_sector>"] = opts[0]
|
||||
options["<sectors>"] = opts[1]
|
||||
options["<filename>"] = opts[2]
|
||||
elif cmd == "w":
|
||||
options["<partitionname>"] = opts[0]
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "wl":
|
||||
options["<directory>"] = opts[0]
|
||||
elif cmd == "wf":
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "ws":
|
||||
options["<start_sector>"] = opts[0]
|
||||
options["<filename>"] = opts[1]
|
||||
elif cmd == "e":
|
||||
options["<partitionname>"] = opts[0]
|
||||
elif cmd == "es":
|
||||
options["<start_sector>"] = opts[0]
|
||||
options["<sectors>"] = opts[1]
|
||||
elif cmd == "footer":
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "peek":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<length>"] = opts[1]
|
||||
options["<filename>"] = opts[2]
|
||||
elif cmd == "peekhex":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<length>"] = opts[1]
|
||||
elif cmd == "peekdword":
|
||||
options["<offset>"] = opts[0]
|
||||
elif cmd == "peekqword":
|
||||
options["<offset>"] = opts[0]
|
||||
elif cmd == "memtbl":
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "poke":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<filename>"] = opts[1]
|
||||
elif cmd == "pokehex":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<data>"] = opts[1]
|
||||
elif cmd == "pokedword":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<data>"] = opts[1]
|
||||
elif cmd == "pokeqword":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<data>"] = opts[1]
|
||||
elif cmd == "memcpy":
|
||||
options["<offset>"] = opts[0]
|
||||
options["<size>"] = opts[1]
|
||||
elif cmd == "pbl":
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "qfp":
|
||||
options["<filename>"] = opts[0]
|
||||
elif cmd == "setbootablestoragedrive":
|
||||
options["<lun>"] = opts[0]
|
||||
elif cmd == "send":
|
||||
options["<command>"] = opts[0]
|
||||
elif cmd == "xml":
|
||||
options["<xmlfile>"] = opts[0]
|
||||
elif cmd == "rawxml":
|
||||
options["<xmlstring>"] = opts[0]
|
||||
return options
|
||||
|
||||
|
||||
def getint(valuestr):
|
||||
try:
|
||||
return int(valuestr)
|
||||
except:
|
||||
try:
|
||||
return int(valuestr, 16)
|
||||
except:
|
||||
return 0
|
||||
|
||||
|
||||
class ColorFormatter(logging.Formatter):
|
||||
LOG_COLORS = {
|
||||
logging.ERROR: colorama.Fore.RED,
|
||||
logging.DEBUG: colorama.Fore.LIGHTMAGENTA_EX,
|
||||
logging.WARNING: colorama.Fore.YELLOW,
|
||||
}
|
||||
|
||||
def format(self, record, *args, **kwargs):
|
||||
# if the corresponding logger has children, they may receive modified
|
||||
# record, so we want to keep it intact
|
||||
new_record = copy.copy(record)
|
||||
if new_record.levelno in self.LOG_COLORS:
|
||||
pad = ""
|
||||
if new_record.name != "root":
|
||||
print(new_record.name)
|
||||
pad = "[LIB]: "
|
||||
# we want levelname to be in different color, so let's modify it
|
||||
new_record.msg = "{pad}{color_begin}{msg}{color_end}".format(
|
||||
pad=pad,
|
||||
msg=new_record.msg,
|
||||
color_begin=self.LOG_COLORS[new_record.levelno],
|
||||
color_end=colorama.Style.RESET_ALL,
|
||||
)
|
||||
# now we can let standart formatting take care of the rest
|
||||
return super(ColorFormatter, self).format(new_record, *args, **kwargs)
|
||||
|
||||
|
||||
class LogBase(type):
|
||||
debuglevel = logging.root.level
|
||||
|
||||
def __init__(cls, *args):
|
||||
super().__init__(*args)
|
||||
logger_attribute_name = '_' + cls.__name__ + '__logger'
|
||||
logger_debuglevel_name = '_' + cls.__name__ + '__debuglevel'
|
||||
logger_name = '.'.join([c.__name__ for c in cls.mro()[-2::-1]])
|
||||
LOG_CONFIG = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"root": {
|
||||
"()": ColorFormatter,
|
||||
"format": "%(name)s - %(message)s",
|
||||
}
|
||||
},
|
||||
"handlers": {
|
||||
"root": {
|
||||
# "level": cls.__logger.level,
|
||||
"formatter": "root",
|
||||
"class": "logging.StreamHandler",
|
||||
"stream": "ext://sys.stdout",
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
"": {
|
||||
"handlers": ["root"],
|
||||
# "level": cls.debuglevel,
|
||||
"propagate": False
|
||||
}
|
||||
},
|
||||
}
|
||||
logging.config.dictConfig(LOG_CONFIG)
|
||||
logger = logging.getLogger(logger_name)
|
||||
|
||||
setattr(cls, logger_attribute_name, logger)
|
||||
setattr(cls, logger_debuglevel_name, cls.debuglevel)
|
||||
|
||||
|
||||
def del_rw(action, name, exc):
|
||||
os.chmod(name, stat.S_IWRITE)
|
||||
os.remove(name)
|
||||
|
||||
|
||||
def rmrf(path):
|
||||
if os.path.exists(path):
|
||||
if os.path.isfile(path):
|
||||
del_rw("", path, "")
|
||||
else:
|
||||
shutil.rmtree(path, onerror=del_rw)
|
||||
|
||||
|
||||
class elf:
|
||||
class memorysegment:
|
||||
phy_addr = 0
|
||||
virt_start_addr = 0
|
||||
virt_end_addr = 0
|
||||
file_start_addr = 0
|
||||
file_end_addr = 0
|
||||
|
||||
def __init__(self, indata, filename):
|
||||
self.data = indata
|
||||
self.filename = filename
|
||||
self.header, self.pentry = self.parse()
|
||||
self.memorylayout = []
|
||||
for entry in self.pentry:
|
||||
ms = self.memorysegment()
|
||||
ms.phy_addr = entry.phy_addr
|
||||
ms.virt_start_addr = entry.virt_addr
|
||||
ms.virt_end_addr = entry.virt_addr + entry.seg_mem_len
|
||||
ms.file_start_addr = entry.from_file
|
||||
ms.file_end_addr = entry.from_file + entry.seg_file_len
|
||||
self.memorylayout.append(ms)
|
||||
|
||||
def getfileoffset(self, offset):
|
||||
for memsegment in self.memorylayout:
|
||||
if memsegment.virt_end_addr >= offset >= memsegment.virt_start_addr:
|
||||
return offset - memsegment.virt_start_addr + memsegment.file_start_addr
|
||||
return None
|
||||
|
||||
def getvirtaddr(self, fileoffset):
|
||||
for memsegment in self.memorylayout:
|
||||
if memsegment.file_end_addr >= fileoffset >= memsegment.file_start_addr:
|
||||
return memsegment.virt_start_addr + fileoffset - memsegment.file_start_addr
|
||||
return None
|
||||
|
||||
def getbaseaddr(self, offset):
|
||||
for memsegment in self.memorylayout:
|
||||
if memsegment.virt_end_addr >= offset >= memsegment.virt_start_addr:
|
||||
return memsegment.virt_start_addr
|
||||
return None
|
||||
|
||||
class programentry:
|
||||
p_type = 0
|
||||
from_file = 0
|
||||
virt_addr = 0
|
||||
phy_addr = 0
|
||||
seg_file_len = 0
|
||||
seg_mem_len = 0
|
||||
p_flags = 0
|
||||
p_align = 0
|
||||
|
||||
def parse_programentry(self, dat):
|
||||
pe = self.programentry()
|
||||
if self.elfclass == 1:
|
||||
(pe.p_type, pe.from_file, pe.virt_addr, pe.phy_addr, pe.seg_file_len, pe.seg_mem_len, pe.p_flags,
|
||||
pe.p_align) = struct.unpack("<IIIIIIII", dat)
|
||||
elif self.elfclass == 2:
|
||||
(pe.p_type, pe.p_flags, pe.from_file, pe.virt_addr, pe.phy_addr, pe.seg_file_len, pe.seg_mem_len,
|
||||
pe.p_align) = struct.unpack("<IIQQQQQQ", dat)
|
||||
return pe
|
||||
|
||||
def parse(self):
|
||||
self.elfclass = self.data[4]
|
||||
if self.elfclass == 1: # 32Bit
|
||||
start = 0x28
|
||||
elif self.elfclass == 2: # 64Bit
|
||||
start = 0x34
|
||||
else:
|
||||
print("Error on parsing " + self.filename)
|
||||
return ['', '']
|
||||
elfheadersize, programheaderentrysize, programheaderentrycount = struct.unpack("<HHH",
|
||||
self.data[start:start + 3 * 2])
|
||||
programheadersize = programheaderentrysize * programheaderentrycount
|
||||
header = self.data[0:elfheadersize + programheadersize]
|
||||
pentry = []
|
||||
for i in range(0, programheaderentrycount):
|
||||
start = elfheadersize + (i * programheaderentrysize)
|
||||
end = start + programheaderentrysize
|
||||
pentry.append(self.parse_programentry(self.data[start:end]))
|
||||
|
||||
return [header, pentry]
|
||||
|
||||
|
||||
class patchtools:
|
||||
cstyle = False
|
||||
bDebug = False
|
||||
|
||||
def __init__(self, bdebug=False):
|
||||
self.bDebug = bdebug
|
||||
|
||||
def has_bad_uart_chars(self, data):
|
||||
badchars = [b'\x00', b'\n', b'\r', b'\x08', b'\x7f', b'\x20', b'\x09']
|
||||
for idx, c in enumerate(data):
|
||||
c = bytes([c])
|
||||
if c in badchars:
|
||||
return True
|
||||
return False
|
||||
|
||||
def generate_offset(self, offset):
|
||||
div = 0
|
||||
found = False
|
||||
while not found and div < 0x606:
|
||||
data = struct.pack("<I", offset + div)
|
||||
data2 = struct.pack("<H", div)
|
||||
badchars = self.has_bad_uart_chars(data)
|
||||
if not badchars:
|
||||
badchars = self.has_bad_uart_chars(data2)
|
||||
if not badchars:
|
||||
return div
|
||||
div += 4
|
||||
|
||||
# if div is not found within positive offset, try negative offset
|
||||
div = 0
|
||||
while not found and div < 0x606:
|
||||
data = struct.pack("<I", offset - div)
|
||||
data2 = struct.pack("<H", div)
|
||||
badchars = self.has_bad_uart_chars(data)
|
||||
if not badchars:
|
||||
badchars = self.has_bad_uart_chars(data2)
|
||||
if not badchars:
|
||||
return -div
|
||||
div += 4
|
||||
return 0
|
||||
|
||||
# Usage: offset, "X24"
|
||||
def generate_offset_asm(self, offset, reg):
|
||||
div = self.generate_offset(offset)
|
||||
abase = ((offset + div) & 0xFFFF0000) >> 16
|
||||
a = ((offset + div) & 0xFFFF)
|
||||
strasm = ""
|
||||
if div > 0:
|
||||
strasm += "# " + hex(offset) + "\n"
|
||||
strasm += "mov " + reg + ", #" + hex(a) + ";\n"
|
||||
strasm += "movk " + reg + ", #" + hex(abase) + ", LSL#16;\n"
|
||||
strasm += "sub " + reg + ", " + reg + ", #" + hex(div) + ";\n"
|
||||
else:
|
||||
strasm += "# " + hex(offset) + "\n"
|
||||
strasm += "mov " + reg + ", #" + hex(a) + ";\n"
|
||||
strasm += "movk " + reg + ", #" + hex(abase) + ", LSL#16;\n"
|
||||
strasm += "add " + reg + ", " + reg + ", #" + hex(-div) + ";\n"
|
||||
return strasm
|
||||
|
||||
def uart_valid_sc(self, sc):
|
||||
badchars = [b'\x00', b'\n', b'\r', b'\x08', b'\x7f', b'\x20', b'\x09']
|
||||
for idx, c in enumerate(sc):
|
||||
c = bytes([c])
|
||||
if c in badchars:
|
||||
print("bad char 0x%s in SC at offset %d, opcode # %d!\n" % (codecs.encode(c, 'hex'), idx, idx / 4))
|
||||
print(codecs.encode(sc, 'hex'))
|
||||
return False
|
||||
return True
|
||||
|
||||
def disasm(self, code, size):
|
||||
cs = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)
|
||||
instr = []
|
||||
for i in cs.disasm(code, size):
|
||||
# print("0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str))
|
||||
instr.append("%s\t%s" % (i.mnemonic, i.op_str))
|
||||
return instr
|
||||
|
||||
def assembler(self, code):
|
||||
ks = Ks(KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN)
|
||||
if self.bDebug:
|
||||
try:
|
||||
encoding, count = ks.asm(code)
|
||||
except KsError as e:
|
||||
print(e)
|
||||
print(e.stat_count)
|
||||
print(code[e.stat_count:e.stat_count + 10])
|
||||
exit(0)
|
||||
if self.bDebug:
|
||||
# walk every line to find the (first) error
|
||||
for idx, line in enumerate(code.splitlines()):
|
||||
print("%02d: %s" % (idx, line))
|
||||
if len(line) and line[0] != '.':
|
||||
try:
|
||||
encoding, count = ks.asm(line)
|
||||
except Exception as e:
|
||||
print("bummer: " + str(e))
|
||||
else:
|
||||
exit(0)
|
||||
else:
|
||||
encoding, count = ks.asm(code)
|
||||
|
||||
sc = ""
|
||||
count = 0
|
||||
out = ""
|
||||
for i in encoding:
|
||||
if self.cstyle:
|
||||
out += ("\\x%02x" % i)
|
||||
else:
|
||||
out += ("%02x" % i)
|
||||
sc += "%02x" % i
|
||||
|
||||
count += 1
|
||||
# if bDebug and count % 4 == 0:
|
||||
# out += ("\n")
|
||||
|
||||
return out
|
||||
|
||||
def find_binary(self, data, strf, pos=0):
|
||||
t = strf.split(b".")
|
||||
pre = 0
|
||||
offsets = []
|
||||
while pre != -1:
|
||||
pre = data[pos:].find(t[0], pre)
|
||||
if pre == -1:
|
||||
if len(offsets) > 0:
|
||||
for offset in offsets:
|
||||
error = 0
|
||||
rt = offset + len(t[0])
|
||||
for i in range(1, len(t)):
|
||||
if t[i] == b'':
|
||||
rt += 1
|
||||
continue
|
||||
rt += 1
|
||||
prep = data[rt:].find(t[i])
|
||||
if prep != 0:
|
||||
error = 1
|
||||
break
|
||||
rt += len(t[i])
|
||||
if error == 0:
|
||||
return offset
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
offsets.append(pre)
|
||||
pre += 1
|
||||
return None
|
||||
|
||||
|
||||
def read_object(data: object, definition: object) -> dict:
|
||||
"""
|
||||
Unpacks a structure using the given data and definition.
|
||||
"""
|
||||
obj = {}
|
||||
object_size = 0
|
||||
pos = 0
|
||||
for (name, stype) in definition:
|
||||
object_size += struct.calcsize(stype)
|
||||
obj[name] = struct.unpack(stype, data[pos:pos + struct.calcsize(stype)])[0]
|
||||
pos += struct.calcsize(stype)
|
||||
obj['object_size'] = object_size
|
||||
obj['raw_data'] = data
|
||||
return obj
|
||||
|
||||
|
||||
def write_object(definition, *args):
|
||||
"""
|
||||
Unpacks a structure using the given data and definition.
|
||||
"""
|
||||
obj = {}
|
||||
object_size = 0
|
||||
data = b""
|
||||
i = 0
|
||||
for (name, stype) in definition:
|
||||
object_size += struct.calcsize(stype)
|
||||
arg = args[i]
|
||||
try:
|
||||
data += struct.pack(stype, arg)
|
||||
except Exception as e:
|
||||
print("Error:" + str(e))
|
||||
break
|
||||
i += 1
|
||||
obj['object_size'] = len(data)
|
||||
obj['raw_data'] = data
|
||||
return obj
|
||||
|
||||
|
||||
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
|
||||
"""
|
||||
Call in a loop to create terminal progress bar
|
||||
@params:
|
||||
iteration - Required : current iteration (Int)
|
||||
total - Required : total iterations (Int)
|
||||
prefix - Optional : prefix string (Str)
|
||||
suffix - Optional : suffix string (Str)
|
||||
decimals - Optional : positive number of decimals in percent complete (Int)
|
||||
bar_length - Optional : character length of bar (Int)
|
||||
"""
|
||||
str_format = "{:>5." + str(decimals) + "f}"
|
||||
percents = str_format.format(100 * (iteration / float(total)))
|
||||
filled_length = int(round(bar_length * iteration / float(total)))
|
||||
bar = '█' * filled_length + '-' * (bar_length - filled_length)
|
||||
|
||||
progstring = '\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)
|
||||
cols, _ = shutil.get_terminal_size()
|
||||
progstring += " " * (cols - len(progstring) - 1)
|
||||
sys.stdout.write(progstring)
|
||||
|
||||
if iteration == total:
|
||||
sys.stdout.write('\n')
|
||||
sys.stdout.flush()
|
||||
@@ -0,0 +1,440 @@
|
||||
# One 9008 session: identify, back up, or flash.
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
EDL = os.path.join(HERE, "edl")
|
||||
LOADER = os.path.join(
|
||||
EDL, "Loaders", "cyanogen", "007050e100000000_4614048173062ae4_fhprg_peek.bin"
|
||||
)
|
||||
IMAGES = os.path.join(os.path.dirname(HERE), "images")
|
||||
|
||||
WRITES = [
|
||||
("gpt_primary.bin", 0),
|
||||
("gpt_backup.bin", 7471038),
|
||||
("cdt.bin", 131072),
|
||||
("sbl1.mbn", 262144),
|
||||
("rpm.mbn", 263168),
|
||||
("tz.mbn", 264192),
|
||||
("hyp.mbn", 266240),
|
||||
("aboot.mbn", 524288),
|
||||
("boot.img", 526336),
|
||||
("rootfs.img", 659456),
|
||||
]
|
||||
EFS = [
|
||||
("modemst1.bin", "modemst1", 267296),
|
||||
("modemst2.bin", "modemst2", 271392),
|
||||
("fsc.bin", "fsc", 275488),
|
||||
("fsg.bin", "fsg", 393216),
|
||||
]
|
||||
EFS_BYTES = {
|
||||
"modemst1": 2 * 1024 * 1024,
|
||||
"modemst2": 2 * 1024 * 1024,
|
||||
"fsc": 1024,
|
||||
"fsg": 2 * 1024 * 1024,
|
||||
}
|
||||
|
||||
|
||||
def emit(key, value):
|
||||
print(f"FLASHER\t{key}\t{value}", flush=True)
|
||||
|
||||
|
||||
def fail(message):
|
||||
emit("FAIL", message)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def format_size(sectors):
|
||||
size = int(sectors) * 512
|
||||
gib = 1024 ** 3
|
||||
mib = 1024 ** 2
|
||||
kib = 1024
|
||||
if size >= gib:
|
||||
return f"{size / gib:.1f} GiB"
|
||||
if size >= mib:
|
||||
return f"{size / mib:.1f} MiB"
|
||||
return f"{max(size // kib, 1)} KiB"
|
||||
|
||||
|
||||
def fill_edl_args(args):
|
||||
defaults = {
|
||||
"--gpt-num-part-entries": "0",
|
||||
"--gpt-part-entry-size": "0",
|
||||
"--gpt-part-entry-start-lba": "0",
|
||||
"--lun": None,
|
||||
"--skipresponse": False,
|
||||
"--skipwrite": False,
|
||||
"--memory": "eMMC",
|
||||
}
|
||||
for key, value in defaults.items():
|
||||
if args.get(key) is None:
|
||||
args[key] = value
|
||||
|
||||
|
||||
def open_link():
|
||||
os.chdir(EDL)
|
||||
if EDL not in sys.path:
|
||||
sys.path.insert(0, EDL)
|
||||
sys.argv = [
|
||||
"edl.py",
|
||||
"printgpt",
|
||||
"--memory=eMMC",
|
||||
"--maxpayload=16384",
|
||||
"--loader=" + LOADER,
|
||||
]
|
||||
import edl
|
||||
fill_edl_args(edl.args)
|
||||
from edlclient.Config.usb_ids import default_ids
|
||||
from edlclient.Library.Connection.usblib import usb_class
|
||||
from edlclient.Library.sahara import sahara
|
||||
|
||||
app = edl.main(edl.args, "")
|
||||
vid = int(app.args["--vid"], 16)
|
||||
pid = int(app.args["--pid"], 16)
|
||||
portconfig = [[vid, pid, -1]] if vid != -1 and pid != -1 else default_ids
|
||||
app.serial = False
|
||||
app.portname = ""
|
||||
app.serial_number = None
|
||||
app.cdc = usb_class(portconfig=portconfig, loglevel=logging.INFO, serial_number=None)
|
||||
app.sahara = sahara(app.cdc, loglevel=logging.INFO)
|
||||
app.sahara.programmer = LOADER
|
||||
app.cdc.timeout = 1500
|
||||
return app
|
||||
|
||||
|
||||
def identify_only():
|
||||
# 只做 Sahara 命令模式,不上传引导、不读容量。
|
||||
# 读完后状态机回到等待握手,重启软件还能再读序列号和芯片型号。
|
||||
app = open_link()
|
||||
try:
|
||||
conninfo = app.doconnect(0) or {}
|
||||
mode = conninfo.get("mode")
|
||||
if mode == "error":
|
||||
fail("设备已拔出")
|
||||
if mode != "sahara":
|
||||
return "", ""
|
||||
try:
|
||||
version = conninfo.get("data").version
|
||||
except Exception:
|
||||
version = 2
|
||||
if not app.sahara.cmd_info(version=version):
|
||||
fail("没有读到芯片序列号")
|
||||
serial = getattr(app.sahara, "serials", None) or ""
|
||||
chip = chip_name(app)
|
||||
return serial, chip
|
||||
finally:
|
||||
try:
|
||||
app.cdc.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def connect():
|
||||
os.chdir(EDL)
|
||||
if EDL not in sys.path:
|
||||
sys.path.insert(0, EDL)
|
||||
sys.argv = [
|
||||
"edl.py",
|
||||
"printgpt",
|
||||
"--memory=eMMC",
|
||||
"--maxpayload=16384",
|
||||
"--loader=" + LOADER,
|
||||
]
|
||||
import edl
|
||||
fill_edl_args(edl.args)
|
||||
|
||||
last = "Firehose 没有连上"
|
||||
saved = {"serial": "", "chip": ""}
|
||||
for skip in (False, True):
|
||||
edl.args["--skipstorageinit"] = skip
|
||||
app = edl.main(edl.args, "")
|
||||
try:
|
||||
app.run()
|
||||
except Exception as exc:
|
||||
last = str(exc)
|
||||
app = None
|
||||
if app is not None:
|
||||
keep_identity(app, saved)
|
||||
if app is not None and app.fh is not None and app.fh.connected:
|
||||
keep_identity(app, saved)
|
||||
return app
|
||||
if app is not None and getattr(app, "cdc", None) is not None:
|
||||
try:
|
||||
app.cdc.close()
|
||||
except Exception:
|
||||
pass
|
||||
last = "Firehose 没有连上"
|
||||
fail(last)
|
||||
|
||||
|
||||
def first_number(raw):
|
||||
if raw is None:
|
||||
return None
|
||||
digits = []
|
||||
started = False
|
||||
for ch in str(raw):
|
||||
if ch.isdigit():
|
||||
digits.append(ch)
|
||||
started = True
|
||||
elif started:
|
||||
break
|
||||
if not digits:
|
||||
return None
|
||||
value = int("".join(digits))
|
||||
if value <= 0:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def sectors_from_mapping(info):
|
||||
if not isinstance(info, dict):
|
||||
return None
|
||||
for key in ("num_partition_sectors", "total_blocks", "total_lbas"):
|
||||
value = first_number(info.get(key))
|
||||
if value:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def storage_sectors(app):
|
||||
info = None
|
||||
try:
|
||||
info = app.fh.get_storage_info()
|
||||
except Exception:
|
||||
info = None
|
||||
sectors = sectors_from_mapping(info)
|
||||
if sectors:
|
||||
return sectors
|
||||
cfg = app.fh.firehose.cfg
|
||||
sectors = first_number(getattr(cfg, "total_blocks", None))
|
||||
if sectors:
|
||||
return sectors
|
||||
xml = '<?xml version="1.0" ?><data><getstorageinfo physical_partition_number="0"/></data>'
|
||||
rsp = app.fh.firehose.xmlsend(xml)
|
||||
pieces = []
|
||||
for item in (getattr(rsp, "data", None), getattr(rsp, "log", None), rsp):
|
||||
if isinstance(item, (bytes, bytearray)):
|
||||
pieces.append(item.decode("utf-8", "replace"))
|
||||
elif isinstance(item, dict):
|
||||
sectors = sectors_from_mapping(item)
|
||||
if sectors:
|
||||
return sectors
|
||||
pieces.append(str(item))
|
||||
elif item is not None:
|
||||
pieces.append(str(item))
|
||||
text = "\n".join(pieces)
|
||||
for key in ("num_partition_sectors", "total_blocks"):
|
||||
at = text.find(key)
|
||||
if at < 0:
|
||||
continue
|
||||
value = first_number(text[at + len(key):])
|
||||
if value:
|
||||
return value
|
||||
fail("没有读到 eMMC 扇区数")
|
||||
|
||||
|
||||
def keep_identity(app, saved):
|
||||
sahara = getattr(app, "sahara", None)
|
||||
if sahara is None:
|
||||
return
|
||||
serial = getattr(sahara, "serials", None) or ""
|
||||
if serial:
|
||||
saved["serial"] = serial
|
||||
elif saved.get("serial"):
|
||||
sahara.serials = saved["serial"]
|
||||
chip = chip_name(app)
|
||||
if chip and not str(chip).startswith("0x"):
|
||||
saved["chip"] = chip
|
||||
elif chip and not saved.get("chip"):
|
||||
saved["chip"] = chip
|
||||
elif saved.get("chip"):
|
||||
sahara._flasher_chip = saved["chip"]
|
||||
|
||||
|
||||
def chip_name(app):
|
||||
sahara = getattr(app, "sahara", None)
|
||||
if sahara is None:
|
||||
return ""
|
||||
named = getattr(sahara, "_flasher_chip", None)
|
||||
if named:
|
||||
return named
|
||||
msm_id = getattr(sahara, "msm_id", None)
|
||||
if isinstance(msm_id, int):
|
||||
try:
|
||||
from edlclient.Config.qualcomm_config import msmids
|
||||
name = msmids.get(msm_id)
|
||||
if name:
|
||||
return name
|
||||
except Exception:
|
||||
pass
|
||||
return "0x{:06x}".format(msm_id)
|
||||
hwid = getattr(sahara, "hwidstr", None) or ""
|
||||
return hwid
|
||||
|
||||
|
||||
def read_part(app, name, path):
|
||||
options = {
|
||||
"<partitionname>": name,
|
||||
"<filename>": path,
|
||||
"--lun": None,
|
||||
"--memory": "eMMC",
|
||||
}
|
||||
if not app.fh.handle_firehose("r", options):
|
||||
fail(f"读取 {name} 失败")
|
||||
|
||||
|
||||
def fit_partition(path, size):
|
||||
with open(path, "rb") as handle:
|
||||
data = handle.read()
|
||||
if len(data) > size:
|
||||
fail(f"{os.path.basename(path)} 大于目标分区")
|
||||
if len(data) < size:
|
||||
with open(path, "ab") as handle:
|
||||
handle.write(b"\x00" * (size - len(data)))
|
||||
|
||||
|
||||
def write_file(app, start, path):
|
||||
options = {
|
||||
"<start_sector>": str(start),
|
||||
"<filename>": path,
|
||||
"--lun": None,
|
||||
"--memory": "eMMC",
|
||||
"--skipwrite": False,
|
||||
}
|
||||
if not app.fh.handle_firehose("ws", options):
|
||||
fail(f"写入 {os.path.basename(path)} 失败")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
fail("缺少命令")
|
||||
command = sys.argv[1]
|
||||
port = ""
|
||||
dest = ""
|
||||
full = False
|
||||
skip_efs = False
|
||||
args = sys.argv[2:]
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--port" and i + 1 < len(args):
|
||||
port = args[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
if args[i] == "--dest" and i + 1 < len(args):
|
||||
dest = args[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
if args[i] == "--full":
|
||||
full = True
|
||||
i += 1
|
||||
continue
|
||||
if args[i] == "--no-efs":
|
||||
skip_efs = True
|
||||
i += 1
|
||||
continue
|
||||
i += 1
|
||||
if port:
|
||||
os.environ["EDL_USB_PORT"] = port
|
||||
if command == "info":
|
||||
serial, chip = identify_only()
|
||||
if serial:
|
||||
emit("SERIAL", serial)
|
||||
if chip:
|
||||
emit("CHIP", chip)
|
||||
emit("DONE", "info")
|
||||
return
|
||||
app = connect()
|
||||
serial = getattr(app.sahara, "serials", None) or ""
|
||||
if serial:
|
||||
emit("SERIAL", serial)
|
||||
chip = chip_name(app)
|
||||
if chip:
|
||||
emit("CHIP", chip)
|
||||
sectors = storage_sectors(app)
|
||||
emit("DISK", format_size(sectors))
|
||||
emit("SECTORS", str(sectors))
|
||||
if command == "info":
|
||||
emit("DONE", "info")
|
||||
return
|
||||
if command == "backup":
|
||||
if not dest:
|
||||
fail("没有备份目录")
|
||||
if skip_efs and not full:
|
||||
fail("没有要备份的内容")
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
if not skip_efs:
|
||||
span = 60 if full else 80
|
||||
for index, (_file, name, _lba) in enumerate(EFS):
|
||||
emit("PROGRESS", str(int(index * span / len(EFS))))
|
||||
read_part(app, name, os.path.join(dest, name + ".bin"))
|
||||
if full:
|
||||
emit("STATUS", "正在备份整盘")
|
||||
target = os.path.join(dest, "emmc.bin")
|
||||
chunk = 32768
|
||||
sector_bytes = int(app.fh.firehose.cfg.SECTOR_SIZE_IN_BYTES)
|
||||
total_bytes = sectors * sector_bytes
|
||||
with open(target, "wb") as out:
|
||||
done = 0
|
||||
while done < sectors:
|
||||
count = min(chunk, sectors - done)
|
||||
part = os.path.join(dest, f".chunk-{done}.bin")
|
||||
if not app.fh.firehose.cmd_read(
|
||||
0, done, count, part, False,
|
||||
progress_base=done * sector_bytes,
|
||||
progress_total=total_bytes,
|
||||
):
|
||||
fail("整盘读取失败")
|
||||
with open(part, "rb") as src:
|
||||
out.write(src.read())
|
||||
os.remove(part)
|
||||
done += count
|
||||
emit("PROGRESS", str(min(99, int(done * 100 / sectors))))
|
||||
expected = sectors * 512
|
||||
if os.path.getsize(target) != expected:
|
||||
fail("整盘大小不完整")
|
||||
emit("PROGRESS", "100")
|
||||
emit("DONE", "backup")
|
||||
return
|
||||
if command == "flash":
|
||||
restore = bool(dest)
|
||||
if restore:
|
||||
for name in ("modemst1", "modemst2", "fsc", "fsg"):
|
||||
if not os.path.isfile(os.path.join(dest, name + ".bin")):
|
||||
fail(f"缺少 {name} 备份")
|
||||
total = len(WRITES) + (len(EFS) if restore else 0)
|
||||
step = 0
|
||||
for filename, start in WRITES:
|
||||
path = os.path.join(IMAGES, filename)
|
||||
if not os.path.isfile(path):
|
||||
fail(f"镜像缺少 {filename}")
|
||||
emit("STATUS", f"正在写入 {filename}")
|
||||
write_file(app, start, path)
|
||||
step += 1
|
||||
emit("PROGRESS", str(int(step * 90 / total)))
|
||||
if restore:
|
||||
for filename, name, start in EFS:
|
||||
path = os.path.join(dest, name + ".bin")
|
||||
fit_partition(path, EFS_BYTES[name])
|
||||
emit("STATUS", f"正在写回 {name}")
|
||||
write_file(app, start, path)
|
||||
step += 1
|
||||
emit("PROGRESS", str(int(step * 90 / total)))
|
||||
try:
|
||||
app.cdc.timeout = 1500
|
||||
app.fh.firehose.cmd_reset("reset")
|
||||
except Exception:
|
||||
pass
|
||||
emit("PROGRESS", "100")
|
||||
emit("DONE", "flash")
|
||||
return
|
||||
fail("未知命令")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as exc:
|
||||
fail(str(exc))
|
||||
+56
-1
@@ -49,6 +49,8 @@ struct Device {
|
||||
status: String,
|
||||
rate: String,
|
||||
progress: i32,
|
||||
bytes_done: u64,
|
||||
bytes_total: u64,
|
||||
pending: Option<JobKind>,
|
||||
queued: bool,
|
||||
present: bool,
|
||||
@@ -62,6 +64,7 @@ enum EventMsg {
|
||||
Chip(String, String),
|
||||
Disk(String, String),
|
||||
Progress(String, i32),
|
||||
Bytes(String, u64, u64),
|
||||
Status(String, String),
|
||||
Rate(String, String),
|
||||
Finished(String, &'static str),
|
||||
@@ -342,6 +345,14 @@ fn apply_line(line: &str, out: &mut WorkerOut, tx: &mpsc::Sender<EventMsg>, loca
|
||||
let _ = tx.send(EventMsg::Progress(location.to_string(), n));
|
||||
}
|
||||
}
|
||||
"BYTES" => {
|
||||
let mut nums = value.split('\t');
|
||||
if let (Some(done), Some(total)) = (nums.next(), nums.next()) {
|
||||
if let (Ok(done), Ok(total)) = (done.parse::<u64>(), total.parse::<u64>()) {
|
||||
let _ = tx.send(EventMsg::Bytes(location.to_string(), done, total));
|
||||
}
|
||||
}
|
||||
}
|
||||
"STATUS" => {
|
||||
let _ = tx.send(EventMsg::Status(location.to_string(), value));
|
||||
}
|
||||
@@ -587,7 +598,7 @@ fn main() {
|
||||
table.set_col_resize(true);
|
||||
table.set_col_resize_min(48);
|
||||
table.set_type(TableRowSelectMode::Single);
|
||||
for (index, width) in [46, 110, 110, 210, 100, 250, 70].into_iter().enumerate() {
|
||||
for (index, width) in [46, 110, 110, 190, 90, 230, 160].into_iter().enumerate() {
|
||||
table.set_col_width(index as i32, width);
|
||||
}
|
||||
table.end();
|
||||
@@ -868,6 +879,9 @@ fn enqueue(queue: &Arc<Mutex<VecDeque<Job>>>, devices: &Arc<Mutex<Vec<Device>>>,
|
||||
dev.queued = true;
|
||||
dev.pending = Some(kind);
|
||||
dev.progress = 0;
|
||||
dev.bytes_done = 0;
|
||||
dev.bytes_total = 0;
|
||||
dev.rate.clear();
|
||||
dev.status = job_status(kind).into();
|
||||
queue.lock().unwrap().push_back(Job { location: location.to_string(), kind, resume: false });
|
||||
}
|
||||
@@ -929,6 +943,8 @@ fn apply_found(found: &[(String, String, String, String)], devices: &Arc<Mutex<V
|
||||
status: "9008".into(),
|
||||
rate: String::new(),
|
||||
progress: 0,
|
||||
bytes_done: 0,
|
||||
bytes_total: 0,
|
||||
pending: None,
|
||||
queued: false,
|
||||
present: true,
|
||||
@@ -972,6 +988,9 @@ fn cell_text(devices: &Mutex<Vec<Device>>, row: i32, col: i32) -> String {
|
||||
4 => dev.disk.clone(),
|
||||
5 if dev.rate.is_empty() => dev.status.clone(),
|
||||
5 => format!("{} {}", dev.status, dev.rate),
|
||||
6 if dev.bytes_total > 0 && dev.status.contains('备') => {
|
||||
format!("{}/{}", format_amount(dev.bytes_done), format_amount(dev.bytes_total))
|
||||
}
|
||||
6 => format!("{}%", dev.progress),
|
||||
_ => String::new(),
|
||||
}
|
||||
@@ -987,6 +1006,27 @@ fn draw_mark(checked: bool, x: i32, y: i32, w: i32, h: i32) {
|
||||
}
|
||||
}
|
||||
|
||||
fn format_amount(bytes: u64) -> String {
|
||||
const KB: f64 = 1024.0;
|
||||
const MB: f64 = 1024.0 * 1024.0;
|
||||
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
|
||||
let value = bytes as f64;
|
||||
let (scaled, unit) = if value >= GB {
|
||||
(value / GB, "GB")
|
||||
} else if value >= MB {
|
||||
(value / MB, "MB")
|
||||
} else if value >= KB {
|
||||
(value / KB, "KB")
|
||||
} else {
|
||||
return format!("{bytes}B");
|
||||
};
|
||||
if scaled >= 100.0 || (scaled - scaled.round()).abs() < 0.05 {
|
||||
format!("{:.0}{unit}", scaled)
|
||||
} else {
|
||||
format!("{:.1}{unit}", scaled)
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_table(table: &mut TableRow, devices: &Arc<Mutex<Vec<Device>>>) {
|
||||
let count = devices.lock().unwrap().len() as i32;
|
||||
if table.rows() != count {
|
||||
@@ -1018,10 +1058,21 @@ fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg) {
|
||||
dev.progress = value;
|
||||
}
|
||||
}
|
||||
EventMsg::Bytes(location, done, total) => {
|
||||
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
|
||||
dev.bytes_done = done;
|
||||
dev.bytes_total = total;
|
||||
if total > 0 {
|
||||
dev.progress = ((done.saturating_mul(100)) / total).min(100) as i32;
|
||||
}
|
||||
}
|
||||
}
|
||||
EventMsg::Status(location, status) => {
|
||||
if let Some(dev) = list.iter_mut().find(|d| d.location == location) {
|
||||
dev.status = status;
|
||||
dev.rate.clear();
|
||||
dev.bytes_done = 0;
|
||||
dev.bytes_total = 0;
|
||||
}
|
||||
}
|
||||
EventMsg::Rate(location, rate) => {
|
||||
@@ -1034,6 +1085,8 @@ fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg) {
|
||||
dev.queued = false;
|
||||
dev.pending = None;
|
||||
dev.rate.clear();
|
||||
dev.bytes_done = 0;
|
||||
dev.bytes_total = 0;
|
||||
if kind == "info" {
|
||||
dev.info_done = true;
|
||||
dev.progress = 0;
|
||||
@@ -1053,6 +1106,8 @@ fn apply(devices: &Arc<Mutex<Vec<Device>>>, msg: EventMsg) {
|
||||
dev.queued = false;
|
||||
dev.pending = None;
|
||||
dev.rate.clear();
|
||||
dev.bytes_done = 0;
|
||||
dev.bytes_total = 0;
|
||||
dev.info_done = true;
|
||||
if err == "设备已拔出" {
|
||||
dev.present = false;
|
||||
|
||||
Reference in New Issue
Block a user