From 82975262fc3ec28c68ef54b56d0d88b5bd6d3747 Mon Sep 17 00:00:00 2001
From: first_user <adityapatil24680@gmail.com>
Date: Sun, 10 Sep 2023 11:07:52 +0530
Subject: [PATCH] optimization with efficient reading and writing of files with
 some minor code refactoring

---
 scripts/buildrom.py     | 11 ++++------
 scripts/buildversion.py |  7 +++----
 scripts/checkrom.py     | 40 +++++++++++++++++++----------------
 scripts/encodeint.py    |  5 ++---
 scripts/layoutrom.py    | 46 ++++++++++++++++++++---------------------
 scripts/ldnoexec.py     | 10 ++++-----
 scripts/readserial.py   | 28 ++++++++++++-------------
 scripts/transdump.py    |  2 --
 scripts/vgafixup.py     | 37 ++++++++++++++++-----------------
 9 files changed, 90 insertions(+), 96 deletions(-)

diff --git a/scripts/buildrom.py b/scripts/buildrom.py
index 48bfc17..e22515b 100755
--- a/scripts/buildrom.py
+++ b/scripts/buildrom.py
@@ -23,10 +23,8 @@ def main():
     outname = sys.argv[2]
 
     # Read data in
-    f = open(inname, 'rb')
-    data = f.read()
-    f.close()
-    count = len(data)
+    with open(inname, 'rb') as file:
+        data = file.read()
 
     # Pad to a 512 byte boundary
     data += b"\0" * (alignpos(count, 512) - count)
@@ -46,9 +44,8 @@ def main():
     data = data[:6] + checksum(data) + data[7:]
 
     # Write new rom
-    f = open(outname, 'wb')
-    f.write(data)
-    f.close()
+    with open(outname, 'wb') as file:
+        file.write(data)
 
 if __name__ == '__main__':
     main()
diff --git a/scripts/buildversion.py b/scripts/buildversion.py
index 8875497..0ff1a54 100755
--- a/scripts/buildversion.py
+++ b/scripts/buildversion.py
@@ -60,10 +60,9 @@ def file_version():
 def write_version(outfile, version, toolstr):
     logging.debug("Write file %s and %s" % (repr(version), repr(toolstr)))
     sys.stdout.write("Version: %s\n" % (version,))
-    f = open(outfile, 'w')
-    f.write(VERSION_FORMAT % (version, toolstr))
-    f.close()
-
+    with open(outfile, 'w') as file:
+        file.write(VERSION_FORMAT % (version, toolstr))
+        
 # Run "tool --version" for each specified tool and extract versions
 def tool_versions(tools):
     tools = [t.strip() for t in tools.split(';')]
diff --git a/scripts/checkrom.py b/scripts/checkrom.py
index a5b15a4..e880b48 100755
--- a/scripts/checkrom.py
+++ b/scripts/checkrom.py
@@ -24,18 +24,19 @@ def main():
     symbols = layoutrom.parseObjDump(objinfofile, 'in')[1]
 
     # Read in raw file
-    f = open(rawfile, 'rb')
-    rawdata = f.read()
-    f.close()
+    with open(rawfile, 'rb') as file:
+        rawdata = file.read()
+
     datasize = len(rawdata)
     finalsize = int(finalsize) * 1024
     if finalsize == 0:
-        finalsize = 64*1024
-        if datasize > 64*1024:
-            finalsize = 128*1024
-            if datasize > 128*1024:
-                finalsize = 256*1024
-    if datasize > finalsize:
+        finalsize = 64 * 1024
+        if datasize > 64 * 1024:
+            finalsize = 128 * 1024
+            if datasize > 128 * 1024:
+                finalsize = 256 * 1024
+
+    if (datasize > finalsize):
         print("Error!  ROM doesn't fit (%d > %d)" % (datasize, finalsize))
         print("   You have to either increase the size (CONFIG_ROM_SIZE)")
         print("   or turn off some features (such as hardware support not")
@@ -47,16 +48,20 @@ def main():
     start = symbols['code32flat_start'].offset
     end = symbols['code32flat_end'].offset
     expend = layoutrom.BUILD_BIOS_ADDR + layoutrom.BUILD_BIOS_SIZE
-    if end != expend:
+
+    if (end != expend):
         print("Error!  Code does not end at 0x%x (got 0x%x)" % (
             expend, end))
         sys.exit(1)
-    if datasize > finalsize:
+
+    if (datasize > finalsize):
         print("Error!  Code is too big (0x%x vs 0x%x)" % (
             datasize, finalsize))
         sys.exit(1)
+
     expdatasize = end - start
-    if datasize != expdatasize:
+
+    if (datasize != expdatasize):
         print("Error!  Unknown extra data (0x%x vs 0x%x)" % (
             datasize, expdatasize))
         sys.exit(1)
@@ -80,14 +85,13 @@ def main():
     # Print statistics
     runtimesize = end - symbols['code32init_end'].offset
     print("Total size: %d  Fixed: %d  Free: %d (used %.1f%% of %dKiB rom)" % (
-        datasize, runtimesize, finalsize - datasize
-        , (datasize / float(finalsize)) * 100.0
-        , int(finalsize / 1024)))
+        datasize, runtimesize, finalsize - datasize,
+        (datasize / float(finalsize)) * 100.0,
+        int(finalsize / 1024)))
 
     # Write final file
-    f = open(outfile, 'wb')
-    f.write((b"\0" * (finalsize - datasize)) + rawdata)
-    f.close()
+    with open(outfile, 'wb') as file:
+        file.write((b"\0" * (finalsize - datasize)) + rawdata)
 
 if __name__ == '__main__':
     main()
diff --git a/scripts/encodeint.py b/scripts/encodeint.py
index 0d34aee..d999c96 100755
--- a/scripts/encodeint.py
+++ b/scripts/encodeint.py
@@ -13,9 +13,8 @@ def main():
     value = int(sys.argv[2], 0)
 
     outval = struct.pack('<Q', value)
-    f = open(filename, 'wb')
-    f.write(outval)
-    f.close()
+    with open(filename, 'wb') as file:
+        file.write(outval)
 
 if __name__ == '__main__':
     main()
diff --git a/scripts/layoutrom.py b/scripts/layoutrom.py
index abebf02..cb6fc84 100755
--- a/scripts/layoutrom.py
+++ b/scripts/layoutrom.py
@@ -113,7 +113,7 @@ def fitSections(sections, fillsections):
         nextfixedaddr = addpos + freespace
 #        print("Filling section %x uses %d, next=%x, available=%d" % (
 #            fixedsection.finalloc, fixedsection.size, nextfixedaddr, freespace))
-        while 1:
+        while True:
             canfit = None
             for fitsection in canrelocate:
                 if addpos + fitsection.size > nextfixedaddr:
@@ -373,17 +373,17 @@ def writeLinkerScripts(li, out16, out32seg, out32flat):
 """ % (li.zonelow_base,
        int(li.zonelow_base / 16),
        outSections(filesections16, useseg=1))
-    outfile = open(out16, 'w')
-    outfile.write(COMMONHEADER + out + COMMONTRAILER)
-    outfile.close()
+    
+    with open(out16, 'w') as file:
+        file.write(COMMONHEADER + out + COMMONTRAILER)
 
     # Write 32seg linker script
     filesections32seg = getSectionsFileid(li.sections, '32seg')
     out = (outXRefs(filesections32seg, useseg=1)
            + outSections(filesections32seg, useseg=1))
-    outfile = open(out32seg, 'w')
-    outfile.write(COMMONHEADER + out + COMMONTRAILER)
-    outfile.close()
+    
+    with open(out32seg, 'w') as file:
+        file.write(COMMONHEADER + out + COMMONTRAILER)
 
     # Write 32flat linker script
     sec32all_start = li.sec32low_start
@@ -451,9 +451,9 @@ PHDRS
         text PT_LOAD AT ( code32flat_start ) ;
 }
 """ % (li.entrysym.name,)
-    outfile = open(out32flat, 'w')
-    outfile.write(out)
-    outfile.close()
+    
+    with open(out32flat, 'w') as file:
+        file.write(out)
 
 
 ######################################################################
@@ -620,19 +620,19 @@ def parseObjDump(file, fileid):
 
 # Parser for constants in simple C header files.
 def scanconfig(file):
-    f = open(file, 'r')
-    opts = {}
-    for l in f.readlines():
-        parts = l.split()
-        if len(parts) != 3:
-            continue
-        if parts[0] != '#define':
-            continue
-        value = parts[2]
-        if value.isdigit() or (value.startswith('0x') and value[2:].isdigit()):
-            value = int(value, 0)
-        opts[parts[1]] = value
-    return opts
+    with open(file, 'r') as file:
+        opts = {}
+        for l in file.readlines():
+            parts = l.split()
+            if len(parts) != 3:
+                continue
+            if parts[0] != '#define':
+                continue
+            value = parts[2]
+            if value.isdigit() or (value.startswith('0x') and value[2:].isdigit()):
+                value = int(value, 0)
+            opts[parts[1]] = value
+        return opts
 
 def main():
     # Get output name
diff --git a/scripts/ldnoexec.py b/scripts/ldnoexec.py
index 60bed07..8f40dcd 100755
--- a/scripts/ldnoexec.py
+++ b/scripts/ldnoexec.py
@@ -17,16 +17,14 @@ def main():
         opts.error("Incorrect number of arguments")
     infilename, outfilename = args
     # Read input
-    f = open(infilename, "rb")
-    srcdata = f.read()
-    f.close()
+    with open(infilename, "rb") as file:
+        srcdata = file.read()
     # Update
     outdata = bytearray(srcdata)
     outdata[FLAG_OFFSET] = 0x01 # change ET_EXEC to ET_REL
     # Write output
-    f = open(outfilename, "wb")
-    f.write(outdata)
-    f.close()
+    with open(outfilename, "wb") as file:
+        file.write(outdata)
 
 if __name__ == '__main__':
     main()
diff --git a/scripts/readserial.py b/scripts/readserial.py
index e3f56e5..f8bbc29 100755
--- a/scripts/readserial.py
+++ b/scripts/readserial.py
@@ -20,7 +20,7 @@ def calibrateserialwrite(outfile, byteadjust):
     # Build 4000 bytes of dummy data.
     data = b"0123456789" * 4 + b"012345678" + b"\n"
     data = data * 80
-    while 1:
+    while True:
         st = time.time()
         outfile.write(data)
         outfile.flush()
@@ -34,7 +34,7 @@ def calibrateserialwrite(outfile, byteadjust):
 def calibrateserialread(infile, byteadjust):
     starttime = lasttime = 0
     totalchars = 0
-    while 1:
+    while True:
         select.select([infile], [], [])
         d = infile.read(4096)
         curtime = time.time()
@@ -54,7 +54,7 @@ def calibrateserialread(infile, byteadjust):
 
 def readserial(infile, logfile, byteadjust):
     lasttime = 0
-    while 1:
+    while True:
         # Read data
         try:
             res = select.select([infile, sys.stdin], [], [])
@@ -168,17 +168,17 @@ Or: apt-get install python-serial
         return
 
     logname = time.strftime("seriallog-%Y%m%d_%H%M%S.log")
-    f = open(logname, 'wb')
-    if options.serial:
-        readserial(ser, f, byteadjust)
-    else:
-        # Read from a pipe
-        while 1:
-            ser = os.fdopen(os.open(serialport, os.O_RDONLY|os.O_NONBLOCK), 'rb')
-            res = readserial(ser, f, byteadjust)
-            ser.close()
-            if res < 0:
-                break
+    with open(logname, 'wb') as file:
+        if options.serial:
+            readserial(ser, file, byteadjust)
+        else:
+            # Read from a pipe
+            while True:
+                ser = os.fdopen(os.open(serialport, os.O_RDONLY|os.O_NONBLOCK), 'rb')
+                res = readserial(ser, file, byteadjust)
+                ser.close()
+                if res < 0:
+                    break
 
 if __name__ == '__main__':
     main()
diff --git a/scripts/transdump.py b/scripts/transdump.py
index 665f04a..1ffd566 100755
--- a/scripts/transdump.py
+++ b/scripts/transdump.py
@@ -46,8 +46,6 @@ def main():
     for i in mem:
         if (sys.version_info > (3, 0)):
             sys.stdout.buffer.write(struct.pack("<I", i))
-        else:
-            sys.stdout.write(struct.pack("<I", i))
 
 if __name__ == '__main__':
     main()
diff --git a/scripts/vgafixup.py b/scripts/vgafixup.py
index 2053cd5..3d71489 100644
--- a/scripts/vgafixup.py
+++ b/scripts/vgafixup.py
@@ -72,25 +72,24 @@ def handle_leal(sline):
 
 def main():
     infilename, outfilename = sys.argv[1:]
-    infile = open(infilename, 'r')
-    out = []
-    for line in infile:
-        sline = line.strip()
-        if sline == 'ret':
-            out.append('retw $2\n')
-        elif sline == 'leave':
-            out.append('movl %ebp, %esp ; popl %ebp\n')
-        elif sline.startswith('call'):
-            out.append('pushw %ax ; callw' + sline[4:] + '\n')
-        elif sline.startswith('leal'):
-            out.append(handle_leal(sline))
-            #print("-> %s\n   %s" % (sline, out[-1].strip()))
-        else:
-            out.append(line)
-    infile.close()
-    outfile = open(outfilename, 'w')
-    outfile.write(''.join(out))
-    outfile.close()
+    with open(infilename, 'r') as infile:
+        out = []
+        for line in infile:
+            sline = line.strip()
+            if sline == 'ret':
+                out.append('retw $2\n')
+            elif sline == 'leave':
+                out.append('movl %ebp, %esp ; popl %ebp\n')
+            elif sline.startswith('call'):
+                out.append('pushw %ax ; callw' + sline[4:] + '\n')
+            elif sline.startswith('leal'):
+                out.append(handle_leal(sline))
+                #print("-> %s\n   %s" % (sline, out[-1].strip()))
+            else:
+                out.append(line)
+
+    with open(outfilename, 'w') as outfile:
+        outfile.write(''.join(out))
 
 if __name__ == '__main__':
     main()
-- 
2.40.0

