From: Feng, Bob C Date: Wed, 23 Jan 2019 02:16:00 +0000 (+0800) Subject: BaseTools: Handle the bytes and str difference X-Git-Tag: edk2-stable201903~206 X-Git-Url: https://git.proxmox.com/?p=mirror_edk2.git;a=commitdiff_plain;h=d943b0c339fe3d35ffdf9f580ccb7a55915c6854 BaseTools: Handle the bytes and str difference Deal with bytes and str is different, remove the unicode(), correct open file parameter. Using utcfromtimestamp instead of fromtimestamp. Cc: Bob Feng Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Zhiju.Fan Tested-by: Laszlo Ersek Tested-by: Ard Biesheuvel Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- diff --git a/BaseTools/Source/Python/AutoGen/AutoGen.py b/BaseTools/Source/Python/AutoGen/AutoGen.py index baa1842667..a95d2c710e 100644 --- a/BaseTools/Source/Python/AutoGen/AutoGen.py +++ b/BaseTools/Source/Python/AutoGen/AutoGen.py @@ -726,11 +726,11 @@ class WorkspaceAutoGen(AutoGen): for files in AllWorkSpaceMetaFiles: if files.endswith('.dec'): continue - f = open(files, 'r') + f = open(files, 'rb') Content = f.read() f.close() m.update(Content) - SaveFileOnChange(os.path.join(self.BuildDir, 'AutoGen.hash'), m.hexdigest(), True) + SaveFileOnChange(os.path.join(self.BuildDir, 'AutoGen.hash'), m.hexdigest(), False) GlobalData.gPlatformHash = m.hexdigest() # @@ -755,7 +755,7 @@ class WorkspaceAutoGen(AutoGen): HashFile = os.path.join(PkgDir, Pkg.PackageName + '.hash') m = hashlib.md5() # Get .dec file's hash value - f = open(Pkg.MetaFile.Path, 'r') + f = open(Pkg.MetaFile.Path, 'rb') Content = f.read() f.close() m.update(Content) @@ -765,11 +765,11 @@ class WorkspaceAutoGen(AutoGen): for Root, Dirs, Files in os.walk(str(inc)): for File in sorted(Files): File_Path = os.path.join(Root, File) - f = open(File_Path, 'r') + f = open(File_Path, 'rb') Content = f.read() f.close() m.update(Content) - SaveFileOnChange(HashFile, m.hexdigest(), True) + SaveFileOnChange(HashFile, m.hexdigest(), False) GlobalData.gPackageHash[Pkg.Arch][Pkg.PackageName] = m.hexdigest() def _GetMetaFiles(self, Target, Toolchain, Arch): @@ -1736,7 +1736,7 @@ class PlatformAutoGen(AutoGen): for pcd in self._DynamicPcdList: if len(pcd.SkuInfoList) == 1: for (SkuName, SkuId) in allskuset: - if type(SkuId) in (str, unicode) and eval(SkuId) == 0 or SkuId == 0: + if isinstance(SkuId, str) and eval(SkuId) == 0 or SkuId == 0: continue pcd.SkuInfoList[SkuName] = copy.deepcopy(pcd.SkuInfoList[TAB_DEFAULT]) pcd.SkuInfoList[SkuName].SkuId = SkuId @@ -1906,7 +1906,7 @@ class PlatformAutoGen(AutoGen): ToolsDef += "%s_%s = %s\n" % (Tool, Attr, Value) ToolsDef += "\n" - SaveFileOnChange(self.ToolDefinitionFile, ToolsDef) + SaveFileOnChange(self.ToolDefinitionFile, ToolsDef, False) for DllPath in DllPathList: os.environ["PATH"] = DllPath + os.pathsep + os.environ["PATH"] os.environ["MAKE_FLAGS"] = MakeFlags @@ -3303,7 +3303,7 @@ class ModuleAutoGen(AutoGen): AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir) RetVal[AutoFile] = str(StringH) self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE) - if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != "": + if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != b"": AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir) RetVal[AutoFile] = UniStringBinBuffer.getvalue() AutoFile.IsBinary = True @@ -3314,7 +3314,7 @@ class ModuleAutoGen(AutoGen): AutoFile = PathClass(gAutoGenImageDefFileName % {"module_name":self.Name}, self.DebugDir) RetVal[AutoFile] = str(StringIdf) self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE) - if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != "": + if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != b"": AutoFile = PathClass(gAutoGenIdfFileName % {"module_name":self.Name}, self.OutputDir) RetVal[AutoFile] = IdfGenBinBuffer.getvalue() AutoFile.IsBinary = True @@ -3532,7 +3532,7 @@ class ModuleAutoGen(AutoGen): EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName, None) # Use a instance of BytesIO to cache data - fStringIO = BytesIO('') + fStringIO = BytesIO() for Item in VfrUniOffsetList: if (Item[0].find("Strings") != -1): @@ -3541,9 +3541,8 @@ class ModuleAutoGen(AutoGen): # GUID + Offset # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } } # - UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66] - UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid] - fStringIO.write(''.join(UniGuid)) + UniGuid = b'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f' + fStringIO.write(UniGuid) UniValue = pack ('Q', int (Item[1], 16)) fStringIO.write (UniValue) else: @@ -3552,9 +3551,8 @@ class ModuleAutoGen(AutoGen): # GUID + Offset # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } }; # - VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2] - VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid] - fStringIO.write(''.join(VfrGuid)) + VfrGuid = b'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2' + fStringIO.write(VfrGuid) VfrValue = pack ('Q', int (Item[1], 16)) fStringIO.write (VfrValue) # @@ -4095,29 +4093,29 @@ class ModuleAutoGen(AutoGen): GlobalData.gModuleHash[self.Arch] = {} m = hashlib.md5() # Add Platform level hash - m.update(GlobalData.gPlatformHash) + m.update(GlobalData.gPlatformHash.encode('utf-8')) # Add Package level hash if self.DependentPackageList: for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName): if Pkg.PackageName in GlobalData.gPackageHash[self.Arch]: - m.update(GlobalData.gPackageHash[self.Arch][Pkg.PackageName]) + m.update(GlobalData.gPackageHash[self.Arch][Pkg.PackageName].encode('utf-8')) # Add Library hash if self.LibraryAutoGenList: for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name): if Lib.Name not in GlobalData.gModuleHash[self.Arch]: Lib.GenModuleHash() - m.update(GlobalData.gModuleHash[self.Arch][Lib.Name]) + m.update(GlobalData.gModuleHash[self.Arch][Lib.Name].encode('utf-8')) # Add Module self - f = open(str(self.MetaFile), 'r') + f = open(str(self.MetaFile), 'rb') Content = f.read() f.close() m.update(Content) # Add Module's source files if self.SourceFileList: for File in sorted(self.SourceFileList, key=lambda x: str(x)): - f = open(str(File), 'r') + f = open(str(File), 'rb') Content = f.read() f.close() m.update(Content) @@ -4128,7 +4126,7 @@ class ModuleAutoGen(AutoGen): if GlobalData.gBinCacheSource: if self.AttemptModuleCacheCopy(): return False - return SaveFileOnChange(ModuleHashFile, m.hexdigest(), True) + return SaveFileOnChange(ModuleHashFile, m.hexdigest(), False) ## Decide whether we can skip the ModuleAutoGen process def CanSkipbyHash(self): diff --git a/BaseTools/Source/Python/AutoGen/GenC.py b/BaseTools/Source/Python/AutoGen/GenC.py index 700c94b3a7..9700bf8527 100644 --- a/BaseTools/Source/Python/AutoGen/GenC.py +++ b/BaseTools/Source/Python/AutoGen/GenC.py @@ -1782,7 +1782,7 @@ def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGenCFlag, IdfGenBinBuffer): TempBuffer += Buffer elif File.Ext.upper() == '.JPG': ImageType, = struct.unpack('4s', Buffer[6:10]) - if ImageType != 'JFIF': + if ImageType != b'JFIF': EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard JPG file." % File.Path) TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_JPEG) TempBuffer += pack('I', len(Buffer)) @@ -1882,7 +1882,7 @@ def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGenCFlag, IdfGenBinBuffer): def BmpImageDecoder(File, Buffer, PaletteIndex, TransParent): ImageType, = struct.unpack('2s', Buffer[0:2]) - if ImageType!= 'BM': # BMP file type is 'BM' + if ImageType!= b'BM': # BMP file type is 'BM' EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard BMP file." % File.Path) BMP_IMAGE_HEADER = collections.namedtuple('BMP_IMAGE_HEADER', ['bfSize', 'bfReserved1', 'bfReserved2', 'bfOffBits', 'biSize', 'biWidth', 'biHeight', 'biPlanes', 'biBitCount', 'biCompression', 'biSizeImage', 'biXPelsPerMeter', 'biYPelsPerMeter', 'biClrUsed', 'biClrImportant']) BMP_IMAGE_HEADER_STRUCT = struct.Struct('IHHIIIIHHIIIIII') @@ -1954,7 +1954,7 @@ def BmpImageDecoder(File, Buffer, PaletteIndex, TransParent): for Index in range(0, len(PaletteBuffer)): if Index % 4 == 3: continue - PaletteTemp += PaletteBuffer[Index] + PaletteTemp += PaletteBuffer[Index:Index+1] PaletteBuffer = PaletteTemp[1:] return ImageBuffer, PaletteBuffer diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/Python/AutoGen/GenMake.py index c42053eb4c..dc4cd688f4 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -1038,17 +1038,21 @@ cleanlib: CurrentFileDependencyList = DepDb[F] else: try: - Fd = open(F.Path, 'r') + Fd = open(F.Path, 'rb') + FileContent = Fd.read() + Fd.close() except BaseException as X: EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=F.Path + "\n\t" + str(X)) - - FileContent = Fd.read() - Fd.close() if len(FileContent) == 0: continue if FileContent[0] == 0xff or FileContent[0] == 0xfe: - FileContent = unicode(FileContent, "utf-16") + FileContent = FileContent.decode('utf-16') + else: + try: + FileContent = str(FileContent) + except: + pass IncludedFileList = gIncludePattern.findall(FileContent) for Inc in IncludedFileList: diff --git a/BaseTools/Source/Python/AutoGen/GenPcdDb.py b/BaseTools/Source/Python/AutoGen/GenPcdDb.py index 2cb1745823..cbf7a39dd5 100644 --- a/BaseTools/Source/Python/AutoGen/GenPcdDb.py +++ b/BaseTools/Source/Python/AutoGen/GenPcdDb.py @@ -295,7 +295,7 @@ class DbItemList: PackStr = PACK_CODE_BY_SIZE[self.ItemSize] - Buffer = '' + Buffer = bytearray() for Datas in self.RawDataList: if type(Datas) in (list, tuple): for Data in Datas: @@ -320,7 +320,7 @@ class DbExMapTblItemList (DbItemList): DbItemList.__init__(self, ItemSize, DataList, RawDataList) def PackData(self): - Buffer = '' + Buffer = bytearray() PackStr = "=LHH" for Datas in self.RawDataList: Buffer += pack(PackStr, @@ -369,7 +369,7 @@ class DbComItemList (DbItemList): def PackData(self): PackStr = PACK_CODE_BY_SIZE[self.ItemSize] - Buffer = '' + Buffer = bytearray() for DataList in self.RawDataList: for Data in DataList: if type(Data) in (list, tuple): @@ -390,7 +390,7 @@ class DbVariableTableItemList (DbComItemList): def PackData(self): PackStr = "=LLHHLHH" - Buffer = '' + Buffer = bytearray() for DataList in self.RawDataList: for Data in DataList: Buffer += pack(PackStr, @@ -451,7 +451,7 @@ class DbSkuHeadTableItemList (DbItemList): def PackData(self): PackStr = "=LL" - Buffer = '' + Buffer = bytearray() for Data in self.RawDataList: Buffer += pack(PackStr, GetIntegerValue(Data[0]), @@ -473,7 +473,7 @@ class DbSizeTableItemList (DbItemList): return length * self.ItemSize def PackData(self): PackStr = "=H" - Buffer = '' + Buffer = bytearray() for Data in self.RawDataList: Buffer += pack(PackStr, GetIntegerValue(Data[0])) @@ -853,8 +853,9 @@ def BuildExDataBase(Dict): Index = 0 for Item in DbItemTotal: Index +=1 - b = Item.PackData() - Buffer += b + packdata = Item.PackData() + for i in range(len(packdata)): + Buffer += packdata[i:i + 1] if Index == InitTableNum: if len(Buffer) % 8: for num in range(8 - len(Buffer) % 8): @@ -921,9 +922,9 @@ def CreatePcdDataBase(PcdDBData): totallenbuff = pack("=L", totallen) newbuffer = databasebuff[:32] for i in range(4): - newbuffer += totallenbuff[i] + newbuffer += totallenbuff[i:i+1] for i in range(36, totallen): - newbuffer += databasebuff[i] + newbuffer += databasebuff[i:i+1] return newbuffer @@ -965,8 +966,8 @@ def NewCreatePcdDatabasePhaseSpecificAutoGen(Platform, Phase): for skuname, skuid in DynamicPcdSet_Sku: AdditionalAutoGenH, AdditionalAutoGenC, PcdDbBuffer, VarCheckTab = CreatePcdDatabasePhaseSpecificAutoGen (Platform, DynamicPcdSet_Sku[(skuname, skuid)], Phase) final_data = () - for item in PcdDbBuffer: - final_data += unpack("B", item) + for item in range(len(PcdDbBuffer)): + final_data += unpack("B", PcdDbBuffer[item:item+1]) PcdDBData[(skuname, skuid)] = (PcdDbBuffer, final_data) PcdDriverAutoGenData[(skuname, skuid)] = (AdditionalAutoGenH, AdditionalAutoGenC) VarCheckTableData[(skuname, skuid)] = VarCheckTab @@ -978,8 +979,8 @@ def NewCreatePcdDatabasePhaseSpecificAutoGen(Platform, Phase): else: AdditionalAutoGenH, AdditionalAutoGenC, PcdDbBuffer, VarCheckTab = CreatePcdDatabasePhaseSpecificAutoGen (Platform, {}, Phase) final_data = () - for item in PcdDbBuffer: - final_data += unpack("B", item) + for item in range(len(PcdDbBuffer)): + final_data += unpack("B", PcdDbBuffer[item:item + 1]) PcdDBData[(TAB_DEFAULT, "0")] = (PcdDbBuffer, final_data) return AdditionalAutoGenH, AdditionalAutoGenC, CreatePcdDataBase(PcdDBData) diff --git a/BaseTools/Source/Python/AutoGen/GenVar.py b/BaseTools/Source/Python/AutoGen/GenVar.py index 98f88e2497..453af66022 100644 --- a/BaseTools/Source/Python/AutoGen/GenVar.py +++ b/BaseTools/Source/Python/AutoGen/GenVar.py @@ -73,8 +73,9 @@ class VariableMgr(object): fisrtdata_flag = DataType.PACK_CODE_BY_SIZE[MAX_SIZE_TYPE[firstdata_type]] fisrtdata = fisrtvalue_list[0] fisrtvalue_list = [] - for data_byte in pack(fisrtdata_flag, int(fisrtdata, 16) if fisrtdata.upper().startswith('0X') else int(fisrtdata)): - fisrtvalue_list.append(hex(unpack("B", data_byte)[0])) + pack_data = pack(fisrtdata_flag, int(fisrtdata, 0)) + for data_byte in range(len(pack_data)): + fisrtvalue_list.append(hex(unpack("B", pack_data[data_byte:data_byte + 1])[0])) newvalue_list = ["0x00"] * FirstOffset + fisrtvalue_list for var_item in sku_var_info_offset_list[1:]: @@ -85,8 +86,9 @@ class VariableMgr(object): data_flag = DataType.PACK_CODE_BY_SIZE[MAX_SIZE_TYPE[Curdata_type]] data = CurvalueList[0] CurvalueList = [] - for data_byte in pack(data_flag, int(data, 16) if data.upper().startswith('0X') else int(data)): - CurvalueList.append(hex(unpack("B", data_byte)[0])) + pack_data = pack(data_flag, int(data, 0)) + for data_byte in range(len(pack_data)): + CurvalueList.append(hex(unpack("B", pack_data[data_byte:data_byte + 1])[0])) if CurOffset > len(newvalue_list): newvalue_list = newvalue_list + ["0x00"] * (CurOffset - len(newvalue_list)) + CurvalueList else: @@ -123,8 +125,8 @@ class VariableMgr(object): default_data_buffer = VariableMgr.PACK_VARIABLES_DATA(default_sku_default.default_value, default_sku_default.data_type, tail) default_data_array = () - for item in default_data_buffer: - default_data_array += unpack("B", item) + for item in range(len(default_data_buffer)): + default_data_array += unpack("B", default_data_buffer[item:item + 1]) var_data[(DataType.TAB_DEFAULT, DataType.TAB_DEFAULT_STORES_DEFAULT)][index] = (default_data_buffer, sku_var_info[(DataType.TAB_DEFAULT, DataType.TAB_DEFAULT_STORES_DEFAULT)]) @@ -141,8 +143,8 @@ class VariableMgr(object): others_data_buffer = VariableMgr.PACK_VARIABLES_DATA(other_sku_other.default_value, other_sku_other.data_type, tail) others_data_array = () - for item in others_data_buffer: - others_data_array += unpack("B", item) + for item in range(len(others_data_buffer)): + others_data_array += unpack("B", others_data_buffer[item:item + 1]) data_delta = VariableMgr.calculate_delta(default_data_array, others_data_array) @@ -158,7 +160,7 @@ class VariableMgr(object): return [] pcds_default_data = var_data.get((DataType.TAB_DEFAULT, DataType.TAB_DEFAULT_STORES_DEFAULT), {}) - NvStoreDataBuffer = "" + NvStoreDataBuffer = bytearray() var_data_offset = collections.OrderedDict() offset = NvStorageHeaderSize for default_data, default_info in pcds_default_data.values(): @@ -185,7 +187,7 @@ class VariableMgr(object): nv_default_part = VariableMgr.AlignData(VariableMgr.PACK_DEFAULT_DATA(0, 0, VariableMgr.unpack_data(variable_storage_header_buffer+NvStoreDataBuffer)), 8) - data_delta_structure_buffer = "" + data_delta_structure_buffer = bytearray() for skuname, defaultstore in var_data: if (skuname, defaultstore) == (DataType.TAB_DEFAULT, DataType.TAB_DEFAULT_STORES_DEFAULT): continue @@ -216,8 +218,8 @@ class VariableMgr(object): @staticmethod def unpack_data(data): final_data = () - for item in data: - final_data += unpack("B", item) + for item in range(len(data)): + final_data += unpack("B", data[item:item + 1]) return final_data @staticmethod @@ -285,7 +287,7 @@ class VariableMgr(object): @staticmethod def PACK_VARIABLES_DATA(var_value,data_type, tail = None): - Buffer = "" + Buffer = bytearray() data_len = 0 if data_type == DataType.TAB_VOID: for value_char in var_value.strip("{").strip("}").split(","): @@ -315,7 +317,7 @@ class VariableMgr(object): @staticmethod def PACK_DEFAULT_DATA(defaultstoragename, skuid, var_value): - Buffer = "" + Buffer = bytearray() Buffer += pack("=L", 4+8+8) Buffer += pack("=Q", int(skuid)) Buffer += pack("=Q", int(defaultstoragename)) @@ -340,7 +342,7 @@ class VariableMgr(object): def PACK_DELTA_DATA(self, skuname, defaultstoragename, delta_list): skuid = self.GetSkuId(skuname) defaultstorageid = self.GetDefaultStoreId(defaultstoragename) - Buffer = "" + Buffer = bytearray() Buffer += pack("=L", 4+8+8) Buffer += pack("=Q", int(skuid)) Buffer += pack("=Q", int(defaultstorageid)) @@ -363,7 +365,7 @@ class VariableMgr(object): @staticmethod def PACK_VARIABLE_NAME(var_name): - Buffer = "" + Buffer = bytearray() for name_char in var_name.strip("{").strip("}").split(","): Buffer += pack("=B", int(name_char, 16)) diff --git a/BaseTools/Source/Python/AutoGen/InfSectionParser.py b/BaseTools/Source/Python/AutoGen/InfSectionParser.py index d985089738..09e9af3fb4 100644 --- a/BaseTools/Source/Python/AutoGen/InfSectionParser.py +++ b/BaseTools/Source/Python/AutoGen/InfSectionParser.py @@ -34,7 +34,7 @@ class InfSectionParser(): SectionData = [] try: - FileLinesList = open(self._FilePath, "r", 0).readlines() + FileLinesList = open(self._FilePath, "r").readlines() except BaseException: EdkLogger.error("build", AUTOGEN_ERROR, 'File %s is opened failed.' % self._FilePath) diff --git a/BaseTools/Source/Python/AutoGen/StrGather.py b/BaseTools/Source/Python/AutoGen/StrGather.py index d87680b2e7..680ec16bd4 100644 --- a/BaseTools/Source/Python/AutoGen/StrGather.py +++ b/BaseTools/Source/Python/AutoGen/StrGather.py @@ -123,7 +123,10 @@ def DecToHexList(Dec, Digit = 8): # @retval: A list for formatted hex string # def AscToHexList(Ascii): - return ['0x{0:02X}'.format(ord(Item)) for Item in Ascii] + try: + return ['0x{0:02X}'.format(Item) for Item in Ascii] + except: + return ['0x{0:02X}'.format(ord(Item)) for Item in Ascii] ## Create content of .h file # diff --git a/BaseTools/Source/Python/AutoGen/UniClassObject.py b/BaseTools/Source/Python/AutoGen/UniClassObject.py index 764d95ec66..d162387cc5 100644 --- a/BaseTools/Source/Python/AutoGen/UniClassObject.py +++ b/BaseTools/Source/Python/AutoGen/UniClassObject.py @@ -24,7 +24,7 @@ from io import BytesIO from Common.BuildToolError import * from Common.StringUtils import GetLineNo from Common.Misc import PathClass -from Common.LongFilePathSupport import LongFilePath, UniToStr +from Common.LongFilePathSupport import LongFilePath from Common.GlobalData import * ## # Static definitions @@ -427,7 +427,7 @@ class UniFileClassObject(object): if EndPos != -1 and EndPos - StartPos == 6 : if g4HexChar.match(Line[StartPos + 2 : EndPos], re.UNICODE): EndStr = Line[EndPos: ] - UniStr = ('\u' + (Line[StartPos + 2 : EndPos])).decode('unicode_escape') + UniStr = Line[StartPos + 2: EndPos] if EndStr.startswith(u'\\x') and len(EndStr) >= 7: if EndStr[6] == u'\\' and g4HexChar.match(EndStr[2 : 6], re.UNICODE): Line = Line[0 : StartPos] + UniStr + EndStr diff --git a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py index 6ddf38fd0d..91c2de621f 100644 --- a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py +++ b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py @@ -41,7 +41,7 @@ class VAR_CHECK_PCD_VARIABLE_TAB_CONTAINER(object): os.mkdir(dest) BinFileName = "PcdVarCheck.bin" BinFilePath = os.path.join(dest, BinFileName) - Buffer = '' + Buffer = bytearray() index = 0 for var_check_tab in self.var_check_info: index += 1 diff --git a/BaseTools/Source/Python/BPDG/GenVpd.py b/BaseTools/Source/Python/BPDG/GenVpd.py index b4a2dd25a2..09712be386 100644 --- a/BaseTools/Source/Python/BPDG/GenVpd.py +++ b/BaseTools/Source/Python/BPDG/GenVpd.py @@ -186,7 +186,7 @@ class PcdEntry: EdkLogger.error("BPDG", BuildToolError.RESOURCE_OVERFLOW, "PCD value string %s is exceed to size %d(File: %s Line: %s)" % (ValueString, Size, self.FileName, self.Lineno)) try: - self.PcdValue = pack('%ds' % Size, ValueString) + self.PcdValue = pack('%ds' % Size, ValueString.encode('utf-8')) except: EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "Invalid size or value for PCD %s to pack(File: %s Line: %s)." % (self.PcdCName, self.FileName, self.Lineno)) @@ -306,7 +306,7 @@ class GenVPD : self.PcdFixedOffsetSizeList = [] self.PcdUnknownOffsetList = [] try: - fInputfile = open(InputFileName, "r", 0) + fInputfile = open(InputFileName, "r") try: self.FileLinesList = fInputfile.readlines() except: @@ -645,7 +645,7 @@ class GenVPD : #Open an VPD file to process try: - fVpdFile = open(BinFileName, "wb", 0) + fVpdFile = open(BinFileName, "wb") except: # Open failed EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "File open failed for %s" % self.VpdFileName, None) @@ -657,7 +657,7 @@ class GenVPD : EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "File open failed for %s" % self.MapFileName, None) # Use a instance of BytesIO to cache data - fStringIO = BytesIO('') + fStringIO = BytesIO() # Write the header of map file. try : diff --git a/BaseTools/Source/Python/Common/LongFilePathOs.py b/BaseTools/Source/Python/Common/LongFilePathOs.py index 53528546b7..3d6fe9b01c 100644 --- a/BaseTools/Source/Python/Common/LongFilePathOs.py +++ b/BaseTools/Source/Python/Common/LongFilePathOs.py @@ -15,7 +15,6 @@ from __future__ import absolute_import import os from . import LongFilePathOsPath from Common.LongFilePathSupport import LongFilePath -from Common.LongFilePathSupport import UniToStr import time path = LongFilePathOsPath @@ -64,7 +63,7 @@ def listdir(path): List = [] uList = os.listdir(u"%s" % LongFilePath(path)) for Item in uList: - List.append(UniToStr(Item)) + List.append(Item) return List environ = os.environ diff --git a/BaseTools/Source/Python/Common/LongFilePathSupport.py b/BaseTools/Source/Python/Common/LongFilePathSupport.py index b3e3c8ea64..ed29d37d38 100644 --- a/BaseTools/Source/Python/Common/LongFilePathSupport.py +++ b/BaseTools/Source/Python/Common/LongFilePathSupport.py @@ -49,15 +49,3 @@ def CopyLongFilePath(src, dst): with open(LongFilePath(src), 'rb') as fsrc: with open(LongFilePath(dst), 'wb') as fdst: shutil.copyfileobj(fsrc, fdst) - -## Convert a python unicode string to a normal string -# -# Convert a python unicode string to a normal string -# UniToStr(u'I am a string') is 'I am a string' -# -# @param Uni: The python unicode string -# -# @retval: The formatted normal string -# -def UniToStr(Uni): - return repr(Uni)[2:-1] diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Python/Common/Misc.py index d3b71fc4a2..6b3c4f7937 100644 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -456,15 +456,22 @@ def RemoveDirectory(Directory, Recursively=False): # @retval False If the file content is the same # def SaveFileOnChange(File, Content, IsBinaryFile=True): - if not IsBinaryFile: - Content = Content.replace("\n", os.linesep) if os.path.exists(File): - try: - if Content == open(File, "rb").read(): - return False - except: - EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File) + if IsBinaryFile: + try: + with open(File, "rb") as f: + if Content == f.read(): + return False + except: + EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File) + else: + try: + with open(File, "r") as f: + if Content == f.read(): + return False + except: + EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File) DirName = os.path.dirname(File) if not CreateDirectory(DirName): @@ -475,12 +482,18 @@ def SaveFileOnChange(File, Content, IsBinaryFile=True): if not os.access(DirName, os.W_OK): EdkLogger.error(None, PERMISSION_FAILURE, "Do not have write permission on directory %s" % DirName) - try: - Fd = open(File, "wb") - Fd.write(Content) - Fd.close() - except IOError as X: - EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X) + if IsBinaryFile: + try: + with open(File, "wb") as Fd: + Fd.write(Content) + except IOError as X: + EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X) + else: + try: + with open(File, 'w') as Fd: + Fd.write(Content) + except IOError as X: + EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X) return True @@ -1060,7 +1073,10 @@ def ParseFieldValue (Value): if Value[0] == '"' and Value[-1] == '"': Value = Value[1:-1] try: - Value = "'" + uuid.UUID(Value).bytes_le + "'" + Value = str(uuid.UUID(Value).bytes_le) + if Value.startswith("b'"): + Value = Value[2:-1] + Value = "'" + Value + "'" except ValueError as Message: raise BadExpression(Message) Value, Size = ParseFieldValue(Value) @@ -1536,7 +1552,7 @@ class PeImageClass(): ByteArray = array.array('B') ByteArray.fromfile(PeObject, 4) # PE signature should be 'PE\0\0' - if ByteArray.tostring() != 'PE\0\0': + if ByteArray.tostring() != b'PE\0\0': self.ErrorInfo = self.FileName + ' has no valid PE signature PE00' return @@ -1752,7 +1768,7 @@ class SkuClass(): # @retval Value The integer value that the input represents # def GetIntegerValue(Input): - if type(Input) in (int, long): + if not isinstance(Input, str): return Input String = Input if String.endswith("U"): diff --git a/BaseTools/Source/Python/Common/StringUtils.py b/BaseTools/Source/Python/Common/StringUtils.py index 0fa51f365b..c6227271a4 100644 --- a/BaseTools/Source/Python/Common/StringUtils.py +++ b/BaseTools/Source/Python/Common/StringUtils.py @@ -816,11 +816,7 @@ def GetHelpTextList(HelpTextClassList): return List def StringToArray(String): - if isinstance(String, unicode): - if len(unicode) == 0: - return "{0x00,0x00}" - return "{%s,0x00,0x00}" % ",".join("0x%02x,0x00" % ord(C) for C in String) - elif String.startswith('L"'): + if String.startswith('L"'): if String == "L\"\"": return "{0x00,0x00}" else: @@ -843,9 +839,7 @@ def StringToArray(String): return '{%s,0,0}' % ','.join(String.split()) def StringArrayLength(String): - if isinstance(String, unicode): - return (len(String) + 1) * 2 + 1; - elif String.startswith('L"'): + if String.startswith('L"'): return (len(String) - 3 + 1) * 2 elif String.startswith('"'): return (len(String) - 2 + 1) diff --git a/BaseTools/Source/Python/Common/VpdInfoFile.py b/BaseTools/Source/Python/Common/VpdInfoFile.py index cebc1f7187..e6cc768ee1 100644 --- a/BaseTools/Source/Python/Common/VpdInfoFile.py +++ b/BaseTools/Source/Python/Common/VpdInfoFile.py @@ -92,18 +92,18 @@ class VpdInfoFile: if (Vpd is None): EdkLogger.error("VpdInfoFile", BuildToolError.ATTRIBUTE_UNKNOWN_ERROR, "Invalid VPD PCD entry.") - if not (Offset >= 0 or Offset == TAB_STAR): + if not (Offset >= "0" or Offset == TAB_STAR): EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID, "Invalid offset parameter: %s." % Offset) if Vpd.DatumType == TAB_VOID: - if Vpd.MaxDatumSize <= 0: + if Vpd.MaxDatumSize <= "0": EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID, "Invalid max datum size for VPD PCD %s.%s" % (Vpd.TokenSpaceGuidCName, Vpd.TokenCName)) elif Vpd.DatumType in TAB_PCD_NUMERIC_TYPES: if not Vpd.MaxDatumSize: Vpd.MaxDatumSize = MAX_SIZE_TYPE[Vpd.DatumType] else: - if Vpd.MaxDatumSize <= 0: + if Vpd.MaxDatumSize <= "0": EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID, "Invalid max datum size for VPD PCD %s.%s" % (Vpd.TokenSpaceGuidCName, Vpd.TokenCName)) @@ -127,7 +127,7 @@ class VpdInfoFile: "Invalid parameter FilePath: %s." % FilePath) Content = FILE_COMMENT_TEMPLATE - Pcds = sorted(self._VpdArray.keys()) + Pcds = sorted(self._VpdArray.keys(), key=lambda x: x.TokenCName) for Pcd in Pcds: i = 0 PcdTokenCName = Pcd.TokenCName @@ -249,7 +249,7 @@ def CallExtenalBPDGTool(ToolPath, VpdFileName): except Exception as X: EdkLogger.error("BPDG", BuildToolError.COMMAND_FAILURE, ExtraData=str(X)) (out, error) = PopenObject.communicate() - print(out) + print(out.decode(encoding='utf-8', errors='ignore')) while PopenObject.returncode is None : PopenObject.wait() diff --git a/BaseTools/Source/Python/GenFds/AprioriSection.py b/BaseTools/Source/Python/GenFds/AprioriSection.py index 55d99320c7..0a828278e8 100644 --- a/BaseTools/Source/Python/GenFds/AprioriSection.py +++ b/BaseTools/Source/Python/GenFds/AprioriSection.py @@ -53,7 +53,7 @@ class AprioriSection (object): # @retval string Generated file name # def GenFfs (self, FvName, Dict = {}, IsMakefile = False): - Buffer = BytesIO('') + Buffer = BytesIO() if self.AprioriType == "PEI": AprioriFileGuid = PEI_APRIORI_GUID else: diff --git a/BaseTools/Source/Python/GenFds/Capsule.py b/BaseTools/Source/Python/GenFds/Capsule.py index 1cdbdcf7ba..9013fca410 100644 --- a/BaseTools/Source/Python/GenFds/Capsule.py +++ b/BaseTools/Source/Python/GenFds/Capsule.py @@ -181,7 +181,7 @@ class Capsule (CapsuleClassObject): # # The real capsule header structure is 28 bytes # - Header.write('\x00'*(HdrSize-28)) + Header.write(b'\x00'*(HdrSize-28)) Header.write(FwMgrHdr.getvalue()) Header.write(Content.getvalue()) # @@ -206,18 +206,17 @@ class Capsule (CapsuleClassObject): return self.GenFmpCapsule() CapInfFile = self.GenCapInf() - CapInfFile.writelines("[files]" + TAB_LINE_BREAK) + CapInfFile.append("[files]" + TAB_LINE_BREAK) CapFileList = [] for CapsuleDataObj in self.CapsuleDataList: CapsuleDataObj.CapsuleName = self.CapsuleName FileName = CapsuleDataObj.GenCapsuleSubItem() CapsuleDataObj.CapsuleName = None CapFileList.append(FileName) - CapInfFile.writelines("EFI_FILE_NAME = " + \ + CapInfFile.append("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK) - SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) - CapInfFile.close() + SaveFileOnChange(self.CapInfFileName, ''.join(CapInfFile), False) # # Call GenFv tool to generate capsule # @@ -243,12 +242,12 @@ class Capsule (CapsuleClassObject): def GenCapInf(self): self.CapInfFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName + "_Cap" + '.inf') - CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+') + CapInfFile = [] - CapInfFile.writelines("[options]" + TAB_LINE_BREAK) + CapInfFile.append("[options]" + TAB_LINE_BREAK) for Item in self.TokensDict: - CapInfFile.writelines("EFI_" + \ + CapInfFile.append("EFI_" + \ Item + \ ' = ' + \ self.TokensDict[Item] + \ diff --git a/BaseTools/Source/Python/GenFds/CapsuleData.py b/BaseTools/Source/Python/GenFds/CapsuleData.py index db201c074b..ace4699a0e 100644 --- a/BaseTools/Source/Python/GenFds/CapsuleData.py +++ b/BaseTools/Source/Python/GenFds/CapsuleData.py @@ -82,7 +82,7 @@ class CapsuleFv (CapsuleData): if self.FvName.find('.fv') == -1: if self.FvName.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict: FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[self.FvName.upper()] - FdBuffer = BytesIO('') + FdBuffer = BytesIO() FvObj.CapsuleName = self.CapsuleName FvFile = FvObj.AddToBuffer(FdBuffer) FvObj.CapsuleName = None diff --git a/BaseTools/Source/Python/GenFds/Fd.py b/BaseTools/Source/Python/GenFds/Fd.py index 9c43a62cc3..e1849a356c 100644 --- a/BaseTools/Source/Python/GenFds/Fd.py +++ b/BaseTools/Source/Python/GenFds/Fd.py @@ -72,7 +72,7 @@ class FD(FDClassObject): HasCapsuleRegion = True break if HasCapsuleRegion: - TempFdBuffer = BytesIO('') + TempFdBuffer = BytesIO() PreviousRegionStart = -1 PreviousRegionSize = 1 @@ -101,7 +101,7 @@ class FD(FDClassObject): GenFdsGlobalVariable.VerboseLogger('Call each region\'s AddToBuffer function') RegionObj.AddToBuffer (TempFdBuffer, self.BaseAddress, self.BlockSizeList, self.ErasePolarity, GenFdsGlobalVariable.ImageBinDict, self.DefineVarDict) - FdBuffer = BytesIO('') + FdBuffer = BytesIO() PreviousRegionStart = -1 PreviousRegionSize = 1 for RegionObj in self.RegionList : diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source/Python/GenFds/FdfParser.py index 69cb7de8e5..63edf816ec 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -159,7 +159,7 @@ class IncludeFileProfile: self.FileName = FileName self.FileLinesList = [] try: - with open(FileName, "rb", 0) as fsock: + with open(FileName, "r") as fsock: self.FileLinesList = fsock.readlines() for index, line in enumerate(self.FileLinesList): if not line.endswith(TAB_LINE_BREAK): @@ -213,7 +213,7 @@ class FileProfile: def __init__(self, FileName): self.FileLinesList = [] try: - with open(FileName, "rb", 0) as fsock: + with open(FileName, "r") as fsock: self.FileLinesList = fsock.readlines() except: diff --git a/BaseTools/Source/Python/GenFds/FfsFileStatement.py b/BaseTools/Source/Python/GenFds/FfsFileStatement.py index 7479efff04..e05fb8ca42 100644 --- a/BaseTools/Source/Python/GenFds/FfsFileStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsFileStatement.py @@ -79,7 +79,7 @@ class FileStatement (FileStatementClassObject): Dict.update(self.DefineVarDict) SectionAlignments = None if self.FvName: - Buffer = BytesIO('') + Buffer = BytesIO() if self.FvName.upper() not in GenFdsGlobalVariable.FdfParser.Profile.FvDict: EdkLogger.error("GenFds", GENFDS_ERROR, "FV (%s) is NOT described in FDF file!" % (self.FvName)) Fv = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(self.FvName.upper()) @@ -96,7 +96,7 @@ class FileStatement (FileStatementClassObject): elif self.FileName: if hasattr(self, 'FvFileType') and self.FvFileType == 'RAW': if isinstance(self.FileName, list) and isinstance(self.SubAlignment, list) and len(self.FileName) == len(self.SubAlignment): - FileContent = '' + FileContent = BytesIO() MaxAlignIndex = 0 MaxAlignValue = 1 for Index, File in enumerate(self.FileName): @@ -112,15 +112,15 @@ class FileStatement (FileStatementClassObject): if AlignValue > MaxAlignValue: MaxAlignIndex = Index MaxAlignValue = AlignValue - FileContent += Content - if len(FileContent) % AlignValue != 0: - Size = AlignValue - len(FileContent) % AlignValue + FileContent.write(Content) + if len(FileContent.getvalue()) % AlignValue != 0: + Size = AlignValue - len(FileContent.getvalue()) % AlignValue for i in range(0, Size): - FileContent += pack('B', 0xFF) + FileContent.write(pack('B', 0xFF)) - if FileContent: + if FileContent.getvalue() != b'': OutputRAWFile = os.path.join(GenFdsGlobalVariable.FfsDir, self.NameGuid, self.NameGuid + '.raw') - SaveFileOnChange(OutputRAWFile, FileContent, True) + SaveFileOnChange(OutputRAWFile, FileContent.getvalue(), True) self.FileName = OutputRAWFile self.SubAlignment = self.SubAlignment[MaxAlignIndex] diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py b/BaseTools/Source/Python/GenFds/FfsInfStatement.py index 80257923f0..6dcb57deed 100644 --- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py @@ -1088,7 +1088,7 @@ class FfsInfStatement(FfsInfStatementClassObject): def __GenUniVfrOffsetFile(VfrUniOffsetList, UniVfrOffsetFileName): # Use a instance of StringIO to cache data - fStringIO = BytesIO('') + fStringIO = BytesIO() for Item in VfrUniOffsetList: if (Item[0].find("Strings") != -1): @@ -1097,9 +1097,8 @@ class FfsInfStatement(FfsInfStatementClassObject): # GUID + Offset # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } } # - UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66] - UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid] - fStringIO.write(''.join(UniGuid)) + UniGuid = b'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f' + fStringIO.write(UniGuid) UniValue = pack ('Q', int (Item[1], 16)) fStringIO.write (UniValue) else: @@ -1108,9 +1107,8 @@ class FfsInfStatement(FfsInfStatementClassObject): # GUID + Offset # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } }; # - VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2] - VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid] - fStringIO.write(''.join(VfrGuid)) + VfrGuid = b'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2' + fStringIO.write(VfrGuid) type (Item[1]) VfrValue = pack ('Q', int (Item[1], 16)) fStringIO.write (VfrValue) diff --git a/BaseTools/Source/Python/GenFds/Fv.py b/BaseTools/Source/Python/GenFds/Fv.py index b141d44dc4..2ae991128a 100644 --- a/BaseTools/Source/Python/GenFds/Fv.py +++ b/BaseTools/Source/Python/GenFds/Fv.py @@ -117,7 +117,7 @@ class FV (object): FfsFileList.append(FileName) # Add Apriori file name to Inf file if not Flag: - self.FvInfFile.writelines("EFI_FILE_NAME = " + \ + self.FvInfFile.append("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK) @@ -131,12 +131,12 @@ class FV (object): FileName = FfsFile.GenFfs(MacroDict, FvParentAddr=BaseAddress, IsMakefile=Flag, FvName=self.UiFvName) FfsFileList.append(FileName) if not Flag: - self.FvInfFile.writelines("EFI_FILE_NAME = " + \ + self.FvInfFile.append("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK) if not Flag: - SaveFileOnChange(self.InfFileName, self.FvInfFile.getvalue(), False) - self.FvInfFile.close() + FvInfFile = ''.join(self.FvInfFile) + SaveFileOnChange(self.InfFileName, FvInfFile, False) # # Call GenFv tool # @@ -208,14 +208,14 @@ class FV (object): # PI FvHeader is 0x48 byte FvHeaderBuffer = FvFileObj.read(0x48) Signature = FvHeaderBuffer[0x28:0x32] - if Signature and Signature.startswith('_FVH'): + if Signature and Signature.startswith(b'_FVH'): GenFdsGlobalVariable.VerboseLogger("\nGenerate %s FV Successfully" % self.UiFvName) GenFdsGlobalVariable.SharpCounter = 0 FvFileObj.seek(0) Buffer.write(FvFileObj.read()) # FV alignment position. - FvAlignmentValue = 1 << (ord(FvHeaderBuffer[0x2E]) & 0x1F) + FvAlignmentValue = 1 << (ord(FvHeaderBuffer[0x2E:0x2F]) & 0x1F) if FvAlignmentValue >= 0x400: if FvAlignmentValue >= 0x100000: if FvAlignmentValue >= 0x1000000: @@ -276,54 +276,54 @@ class FV (object): # self.InfFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiFvName + '.inf') - self.FvInfFile = BytesIO() + self.FvInfFile = [] # # Add [Options] # - self.FvInfFile.writelines("[options]" + TAB_LINE_BREAK) + self.FvInfFile.append("[options]" + TAB_LINE_BREAK) if BaseAddress is not None: - self.FvInfFile.writelines("EFI_BASE_ADDRESS = " + \ + self.FvInfFile.append("EFI_BASE_ADDRESS = " + \ BaseAddress + \ TAB_LINE_BREAK) if BlockSize is not None: - self.FvInfFile.writelines("EFI_BLOCK_SIZE = " + \ + self.FvInfFile.append("EFI_BLOCK_SIZE = " + \ '0x%X' %BlockSize + \ TAB_LINE_BREAK) if BlockNum is not None: - self.FvInfFile.writelines("EFI_NUM_BLOCKS = " + \ + self.FvInfFile.append("EFI_NUM_BLOCKS = " + \ ' 0x%X' %BlockNum + \ TAB_LINE_BREAK) else: if self.BlockSizeList == []: if not self._GetBlockSize(): #set default block size is 1 - self.FvInfFile.writelines("EFI_BLOCK_SIZE = 0x1" + TAB_LINE_BREAK) + self.FvInfFile.append("EFI_BLOCK_SIZE = 0x1" + TAB_LINE_BREAK) for BlockSize in self.BlockSizeList: if BlockSize[0] is not None: - self.FvInfFile.writelines("EFI_BLOCK_SIZE = " + \ + self.FvInfFile.append("EFI_BLOCK_SIZE = " + \ '0x%X' %BlockSize[0] + \ TAB_LINE_BREAK) if BlockSize[1] is not None: - self.FvInfFile.writelines("EFI_NUM_BLOCKS = " + \ + self.FvInfFile.append("EFI_NUM_BLOCKS = " + \ ' 0x%X' %BlockSize[1] + \ TAB_LINE_BREAK) if self.BsBaseAddress is not None: - self.FvInfFile.writelines('EFI_BOOT_DRIVER_BASE_ADDRESS = ' + \ + self.FvInfFile.append('EFI_BOOT_DRIVER_BASE_ADDRESS = ' + \ '0x%X' %self.BsBaseAddress) if self.RtBaseAddress is not None: - self.FvInfFile.writelines('EFI_RUNTIME_DRIVER_BASE_ADDRESS = ' + \ + self.FvInfFile.append('EFI_RUNTIME_DRIVER_BASE_ADDRESS = ' + \ '0x%X' %self.RtBaseAddress) # # Add attribute # - self.FvInfFile.writelines("[attributes]" + TAB_LINE_BREAK) + self.FvInfFile.append("[attributes]" + TAB_LINE_BREAK) - self.FvInfFile.writelines("EFI_ERASE_POLARITY = " + \ + self.FvInfFile.append("EFI_ERASE_POLARITY = " + \ ' %s' %ErasePloarity + \ TAB_LINE_BREAK) if not (self.FvAttributeDict is None): @@ -332,13 +332,13 @@ class FV (object): if self.FvAttributeDict[FvAttribute].upper() in ('TRUE', '1'): self.UsedSizeEnable = True continue - self.FvInfFile.writelines("EFI_" + \ + self.FvInfFile.append("EFI_" + \ FvAttribute + \ ' = ' + \ self.FvAttributeDict[FvAttribute] + \ TAB_LINE_BREAK ) if self.FvAlignment is not None: - self.FvInfFile.writelines("EFI_FVB2_ALIGNMENT_" + \ + self.FvInfFile.append("EFI_FVB2_ALIGNMENT_" + \ self.FvAlignment.strip() + \ " = TRUE" + \ TAB_LINE_BREAK) @@ -351,7 +351,7 @@ class FV (object): GenFdsGlobalVariable.ErrorLogger("FV Extension Header Entries declared for %s with no FvNameGuid declaration." % (self.UiFvName)) else: TotalSize = 16 + 4 - Buffer = '' + Buffer = bytearray() if self.UsedSizeEnable: TotalSize += (4 + 4) ## define EFI_FV_EXT_TYPE_USED_SIZE_TYPE 0x03 @@ -378,7 +378,7 @@ class FV (object): # Buffer += (pack('HH', (FvUiLen + 16 + 4), 0x0002) + PackGUID(Guid) - + self.UiFvName) + + self.UiFvName.encode('utf-8')) for Index in range (0, len(self.FvExtEntryType)): if self.FvExtEntryType[Index] == 'FILE': @@ -425,11 +425,11 @@ class FV (object): if Changed: if os.path.exists (self.InfFileName): os.remove (self.InfFileName) - self.FvInfFile.writelines("EFI_FV_EXT_HEADER_FILE_NAME = " + \ + self.FvInfFile.append("EFI_FV_EXT_HEADER_FILE_NAME = " + \ FvExtHeaderFileName + \ TAB_LINE_BREAK) # # Add [Files] # - self.FvInfFile.writelines("[files]" + TAB_LINE_BREAK) + self.FvInfFile.append("[files]" + TAB_LINE_BREAK) diff --git a/BaseTools/Source/Python/GenFds/FvImageSection.py b/BaseTools/Source/Python/GenFds/FvImageSection.py index 7ea931e1b5..85e59cc347 100644 --- a/BaseTools/Source/Python/GenFds/FvImageSection.py +++ b/BaseTools/Source/Python/GenFds/FvImageSection.py @@ -102,7 +102,7 @@ class FvImageSection(FvImageSectionClassObject): # Generate Fv # if self.FvName is not None: - Buffer = BytesIO('') + Buffer = BytesIO() Fv = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(self.FvName) if Fv is not None: self.Fv = Fv diff --git a/BaseTools/Source/Python/GenFds/GenFds.py b/BaseTools/Source/Python/GenFds/GenFds.py index 2efb2edd9a..a99d56a9fd 100644 --- a/BaseTools/Source/Python/GenFds/GenFds.py +++ b/BaseTools/Source/Python/GenFds/GenFds.py @@ -522,7 +522,7 @@ class GenFds(object): return elif GenFds.OnlyGenerateThisFv is None: for FvObj in GenFdsGlobalVariable.FdfParser.Profile.FvDict.values(): - Buffer = BytesIO('') + Buffer = BytesIO() FvObj.AddToBuffer(Buffer) Buffer.close() @@ -673,7 +673,7 @@ class GenFds(object): @staticmethod def GenerateGuidXRefFile(BuildDb, ArchList, FdfParserObj): GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref") - GuidXRefFile = BytesIO('') + GuidXRefFile = [] PkgGuidDict = {} GuidDict = {} ModuleList = [] @@ -700,9 +700,9 @@ class GenFds(object): else: ModuleList.append(Module) if GlobalData.gGuidPattern.match(ModuleFile.BaseName): - GuidXRefFile.write("%s %s\n" % (ModuleFile.BaseName, Module.BaseName)) + GuidXRefFile.append("%s %s\n" % (ModuleFile.BaseName, Module.BaseName)) else: - GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName)) + GuidXRefFile.append("%s %s\n" % (Module.Guid, Module.BaseName)) GuidDict.update(Module.Protocols) GuidDict.update(Module.Guids) GuidDict.update(Module.Ppis) @@ -715,7 +715,7 @@ class GenFds(object): continue else: ModuleList.append(FdfModule) - GuidXRefFile.write("%s %s\n" % (FdfModule.Guid, FdfModule.BaseName)) + GuidXRefFile.append("%s %s\n" % (FdfModule.Guid, FdfModule.BaseName)) GuidDict.update(FdfModule.Protocols) GuidDict.update(FdfModule.Guids) GuidDict.update(FdfModule.Ppis) @@ -776,19 +776,19 @@ class GenFds(object): continue Name = ' '.join(Name) if isinstance(Name, type([])) else Name - GuidXRefFile.write("%s %s\n" %(FileStatementGuid, Name)) + GuidXRefFile.append("%s %s\n" %(FileStatementGuid, Name)) # Append GUIDs, Protocols, and PPIs to the Xref file - GuidXRefFile.write("\n") + GuidXRefFile.append("\n") for key, item in GuidDict.items(): - GuidXRefFile.write("%s %s\n" % (GuidStructureStringToGuidString(item).upper(), key)) + GuidXRefFile.append("%s %s\n" % (GuidStructureStringToGuidString(item).upper(), key)) - if GuidXRefFile.getvalue(): - SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False) + if GuidXRefFile: + GuidXRefFile = ''.join(GuidXRefFile) + SaveFileOnChange(GuidXRefFileName, GuidXRefFile, False) GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName) elif os.path.exists(GuidXRefFileName): os.remove(GuidXRefFileName) - GuidXRefFile.close() if __name__ == '__main__': diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py index febe0737a2..028bcc480c 100644 --- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py +++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py @@ -722,8 +722,8 @@ class GenFdsGlobalVariable: return if PopenObject.returncode != 0 or GenFdsGlobalVariable.VerboseMode or GenFdsGlobalVariable.DebugLevel != -1: GenFdsGlobalVariable.InfLogger ("Return Value = %d" % PopenObject.returncode) - GenFdsGlobalVariable.InfLogger (out) - GenFdsGlobalVariable.InfLogger (error) + GenFdsGlobalVariable.InfLogger(out.decode(encoding='utf-8', errors='ignore')) + GenFdsGlobalVariable.InfLogger(error.decode(encoding='utf-8', errors='ignore')) if PopenObject.returncode != 0: print("###", cmd) EdkLogger.error("GenFds", COMMAND_FAILURE, errorMess) diff --git a/BaseTools/Source/Python/GenFds/Region.py b/BaseTools/Source/Python/GenFds/Region.py index 83363276d2..972847efae 100644 --- a/BaseTools/Source/Python/GenFds/Region.py +++ b/BaseTools/Source/Python/GenFds/Region.py @@ -62,8 +62,8 @@ class Region(object): PadByte = pack('B', 0xFF) else: PadByte = pack('B', 0) - PadData = ''.join(PadByte for i in range(0, Size)) - Buffer.write(PadData) + for i in range(0, Size): + Buffer.write(PadByte) ## AddToBuffer() # @@ -131,7 +131,7 @@ class Region(object): if self.FvAddress % FvAlignValue != 0: EdkLogger.error("GenFds", GENFDS_ERROR, "FV (%s) is NOT %s Aligned!" % (FvObj.UiFvName, FvObj.FvAlignment)) - FvBuffer = BytesIO('') + FvBuffer = BytesIO() FvBaseAddress = '0x%X' % self.FvAddress BlockSize = None BlockNum = None diff --git a/BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py b/BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py index 2a7c308895..003f052a90 100644 --- a/BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py +++ b/BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py @@ -122,7 +122,7 @@ if __name__ == '__main__': if Process.returncode != 0: print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH') sys.exit(Process.returncode) - print(Version[0]) + print(Version[0].decode()) # # Read input file into a buffer and save input filename diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py index f96ceb2637..c0b661d03c 100644 --- a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py @@ -84,7 +84,7 @@ if __name__ == '__main__': if Process.returncode != 0: print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH') sys.exit(Process.returncode) - print(Version[0]) + print(Version[0].decode()) args.PemFileName = [] @@ -119,19 +119,19 @@ if __name__ == '__main__': args.PemFileName.append(Item.name) Item.close() - PublicKeyHash = '' + PublicKeyHash = bytearray() for Item in args.PemFileName: # # Extract public key from private key into STDOUT # Process = subprocess.Popen('%s rsa -in %s -modulus -noout' % (OpenSslCommand, Item), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) - PublicKeyHexString = Process.communicate()[0].split('=')[1].strip() + PublicKeyHexString = Process.communicate()[0].split(b'=')[1].strip() if Process.returncode != 0: print('ERROR: Unable to extract public key from private key') sys.exit(Process.returncode) - PublicKey = '' + PublicKey = bytearray() for Index in range (0, len(PublicKeyHexString), 2): - PublicKey = PublicKey + chr(int(PublicKeyHexString[Index:Index + 2], 16)) + PublicKey = PublicKey + PublicKeyHexString[Index:Index + 2] # # Generate SHA 256 hash of RSA 2048 bit public key into STDOUT @@ -157,14 +157,14 @@ if __name__ == '__main__': # PublicKeyHashC = '{' for Item in PublicKeyHash: - PublicKeyHashC = PublicKeyHashC + '0x%02x, ' % (ord(Item)) + PublicKeyHashC = PublicKeyHashC + '0x%02x, ' % (Item) PublicKeyHashC = PublicKeyHashC[:-2] + '}' # # Write SHA 256 of 2048 bit binary public key to public key hash C structure file # try: - args.PublicKeyHashCFile.write (PublicKeyHashC) + args.PublicKeyHashCFile.write (bytes(PublicKeyHashC)) args.PublicKeyHashCFile.close () except: pass diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py index c285a69ec0..6cea885853 100644 --- a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py @@ -105,7 +105,7 @@ if __name__ == '__main__': if Process.returncode != 0: print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH') sys.exit(Process.returncode) - print(Version[0]) + print(Version[0].decode('utf-8')) # # Read input file into a buffer and save input filename @@ -153,7 +153,8 @@ if __name__ == '__main__': # Extract public key from private key into STDOUT # Process = subprocess.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand, args.PrivateKeyFileName), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) - PublicKeyHexString = Process.communicate()[0].split('=')[1].strip() + PublicKeyHexString = Process.communicate()[0].split(b'=')[1].strip() + PublicKeyHexString = PublicKeyHexString.decode('utf-8') PublicKey = '' while len(PublicKeyHexString) > 0: PublicKey = PublicKey + PublicKeyHexString[0:2] @@ -210,7 +211,7 @@ if __name__ == '__main__': # # Verify the public key # - if Header.PublicKey != PublicKey: + if Header.PublicKey != bytearray.fromhex(PublicKey): print('ERROR: Public key in input file does not match public key from private key file') sys.exit(1) diff --git a/BaseTools/Source/Python/Trim/Trim.py b/BaseTools/Source/Python/Trim/Trim.py index 51010bf326..428bf0d681 100644 --- a/BaseTools/Source/Python/Trim/Trim.py +++ b/BaseTools/Source/Python/Trim/Trim.py @@ -245,7 +245,7 @@ def TrimPreprocessedFile(Source, Target, ConvertHex, TrimLong): # save to file try: - f = open (Target, 'wb') + f = open (Target, 'w') except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target) f.writelines(NewLines) @@ -458,7 +458,7 @@ def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile): EdkLogger.error("Trim", FILE_OPEN_FAILURE, "File open failed for %s" %OutputFile, None) # Use a instance of BytesIO to cache data - fStringIO = BytesIO('') + fStringIO = BytesIO() for Item in VfrUniOffsetList: if (Item[0].find("Strings") != -1): @@ -467,9 +467,8 @@ def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile): # GUID + Offset # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } } # - UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66] - UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid] - fStringIO.write(''.join(UniGuid)) + UniGuid = b'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f' + fStringIO.write(UniGuid) UniValue = pack ('Q', int (Item[1], 16)) fStringIO.write (UniValue) else: @@ -478,9 +477,8 @@ def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile): # GUID + Offset # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } }; # - VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2] - VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid] - fStringIO.write(''.join(VfrGuid)) + VfrGuid = b'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2' + fStringIO.write(VfrGuid) type (Item[1]) VfrValue = pack ('Q', int (Item[1], 16)) fStringIO.write (VfrValue) @@ -562,7 +560,7 @@ def TrimEdkSourceCode(Source, Target): CreateDirectory(os.path.dirname(Target)) try: - f = open (Source, 'rb') + f = open (Source, 'r') except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Source) # read whole file @@ -581,7 +579,7 @@ def TrimEdkSourceCode(Source, Target): return try: - f = open (Target, 'wb') + f = open (Target, 'w') except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target) f.write(NewLines) diff --git a/BaseTools/Source/Python/UPT/Library/StringUtils.py b/BaseTools/Source/Python/UPT/Library/StringUtils.py index 90946337d0..a3391daa91 100644 --- a/BaseTools/Source/Python/UPT/Library/StringUtils.py +++ b/BaseTools/Source/Python/UPT/Library/StringUtils.py @@ -679,9 +679,7 @@ def GetHelpTextList(HelpTextClassList): # @param String: the source string # def StringArrayLength(String): - if isinstance(String, unicode): - return (len(String) + 1) * 2 + 1 - elif String.startswith('L"'): + if String.startswith('L"'): return (len(String) - 3 + 1) * 2 elif String.startswith('"'): return (len(String) - 2 + 1) diff --git a/BaseTools/Source/Python/Workspace/BuildClassObject.py b/BaseTools/Source/Python/Workspace/BuildClassObject.py index b67414b930..cff77a71ae 100644 --- a/BaseTools/Source/Python/Workspace/BuildClassObject.py +++ b/BaseTools/Source/Python/Workspace/BuildClassObject.py @@ -94,13 +94,13 @@ class PcdClassObject(object): deme = ArrayIndex.findall(demesionattr) for i in range(len(deme)-1): if int(deme[i].lstrip("[").rstrip("]").strip()) > int(self._Capacity[i]): - print "error" + print ("error") if hasattr(self,"DefaultValues"): for demesionattr in self.DefaultValues: deme = ArrayIndex.findall(demesionattr) for i in range(len(deme)-1): if int(deme[i].lstrip("[").rstrip("]").strip()) > int(self._Capacity[i]): - print "error" + print ("error") return self._Capacity @property def DatumType(self): diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/Source/Python/Workspace/DscBuildData.py index 13b2cef59d..a96502b4bf 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -156,7 +156,14 @@ def GetDependencyList(FileStack, SearchPathList): continue if FileContent[0] == 0xff or FileContent[0] == 0xfe: - FileContent = unicode(FileContent, "utf-16") + FileContent = FileContent.decode('utf-16') + IncludedFileList = gIncludePattern.findall(FileContent) + else: + try: + FileContent = str(FileContent) + IncludedFileList = gIncludePattern.findall(FileContent) + except: + pass IncludedFileList = gIncludePattern.findall(FileContent) for Inc in IncludedFileList: @@ -1615,7 +1622,7 @@ class DscBuildData(PlatformBuildClassObject): FdfInfList = GlobalData.gFdfParser.Profile.InfList FdfModuleList = [PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch=self._Arch) for Inf in FdfInfList] AllModulePcds = set() - ModuleSet = set(self._Modules.keys() + FdfModuleList) + ModuleSet = set(list(self._Modules.keys()) + FdfModuleList) for ModuleFile in ModuleSet: ModuleData = self._Bdb[ModuleFile, self._Arch, self._Target, self._Toolchain] AllModulePcds = AllModulePcds | ModuleData.PcdsName @@ -1743,7 +1750,7 @@ class DscBuildData(PlatformBuildClassObject): except: EdkLogger.error('Build', COMMAND_FAILURE, 'Can not execute command: %s' % Command) Result = Process.communicate() - return Process.returncode, Result[0], Result[1] + return Process.returncode, Result[0].decode(encoding='utf-8', errors='ignore'), Result[1].decode(encoding='utf-8', errors='ignore') @staticmethod def IntToCString(Value, ValueSize): diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTools/Source/Python/Workspace/MetaFileParser.py index f31dbc2649..b2428a535c 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -1999,10 +1999,10 @@ class DecParser(MetaFileParser): return if self._include_flag: - self._ValueList[1] = "_" + md5(self._CurrentLine).hexdigest() + self._ValueList[1] = "_" + md5(self._CurrentLine.encode('utf-8')).hexdigest() self._ValueList[2] = self._CurrentLine if self._package_flag and "}" != self._CurrentLine: - self._ValueList[1] = "_" + md5(self._CurrentLine).hexdigest() + self._ValueList[1] = "_" + md5(self._CurrentLine.encode('utf-8')).hexdigest() self._ValueList[2] = self._CurrentLine if self._CurrentLine == "}": self._package_flag = False diff --git a/BaseTools/Source/Python/build/BuildReport.py b/BaseTools/Source/Python/build/BuildReport.py index 1cd1b0886a..8d3b030151 100644 --- a/BaseTools/Source/Python/build/BuildReport.py +++ b/BaseTools/Source/Python/build/BuildReport.py @@ -143,7 +143,7 @@ VPDPcdList = [] def FileWrite(File, String, Wrapper=False): if Wrapper: String = textwrap.fill(String, 120) - File.write(String + gEndOfLine) + File.append(String + gEndOfLine) def ByteArrayForamt(Value): IsByteArray = False @@ -636,7 +636,7 @@ class ModuleReport(object): Match = gTimeStampPattern.search(FileContents) if Match: - self.BuildTimeStamp = datetime.fromtimestamp(int(Match.group(1))) + self.BuildTimeStamp = datetime.utcfromtimestamp(int(Match.group(1))) except IOError: EdkLogger.warn(None, "Fail to read report file", FwReportFileName) @@ -721,8 +721,8 @@ def ReadMessage(From, To, ExitFlag): # read one line a time Line = From.readline() # empty string means "end" - if Line is not None and Line != "": - To(Line.rstrip()) + if Line is not None and Line != b"": + To(Line.rstrip().decode(encoding='utf-8', errors='ignore')) else: break if ExitFlag.isSet(): @@ -2269,18 +2269,17 @@ class BuildReport(object): def GenerateReport(self, BuildDuration, AutoGenTime, MakeTime, GenFdsTime): if self.ReportFile: try: - File = BytesIO('') + File = [] for (Wa, MaList) in self.ReportList: PlatformReport(Wa, MaList, self.ReportType).GenerateReport(File, BuildDuration, AutoGenTime, MakeTime, GenFdsTime, self.ReportType) - Content = FileLinesSplit(File.getvalue(), gLineMaxLength) - SaveFileOnChange(self.ReportFile, Content, True) + Content = FileLinesSplit(''.join(File), gLineMaxLength) + SaveFileOnChange(self.ReportFile, Content, False) EdkLogger.quiet("Build report can be found at %s" % os.path.abspath(self.ReportFile)) except IOError: EdkLogger.error(None, FILE_WRITE_FAILURE, ExtraData=self.ReportFile) except: EdkLogger.error("BuildReport", CODE_ERROR, "Unknown fatal error when generating build report", ExtraData=self.ReportFile, RaiseError=False) EdkLogger.quiet("(Python %s on %s\n%s)" % (platform.python_version(), sys.platform, traceback.format_exc())) - File.close() # This acts like the main() function for the script, unless it is 'import'ed into another script. if __name__ == '__main__': diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 43fc3c8077..cdea312864 100644 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -20,7 +20,6 @@ from __future__ import print_function import Common.LongFilePathOs as os import re -from io import BytesIO import sys import glob import time @@ -182,8 +181,8 @@ def ReadMessage(From, To, ExitFlag): # read one line a time Line = From.readline() # empty string means "end" - if Line is not None and Line != "": - To(Line.rstrip()) + if Line is not None and Line != b"": + To(Line.rstrip().decode(encoding='utf-8', errors='ignore')) else: break if ExitFlag.isSet(): @@ -1410,11 +1409,11 @@ class Build(): # Add general information. # if ModeIsSmm: - MapBuffer.write('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint)) + MapBuffer.append('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint)) elif AddrIsOffset: - MapBuffer.write('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName, 0 - BaseAddress, 0 - (BaseAddress + ModuleInfo.Image.EntryPoint))) + MapBuffer.append('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName, 0 - BaseAddress, 0 - (BaseAddress + ModuleInfo.Image.EntryPoint))) else: - MapBuffer.write('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint)) + MapBuffer.append('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint)) # # Add guid and general seciton section. # @@ -1426,21 +1425,21 @@ class Build(): elif SectionHeader[0] in ['.data', '.sdata']: DataSectionAddress = SectionHeader[1] if AddrIsOffset: - MapBuffer.write('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + TextSectionAddress), 0 - (BaseAddress + DataSectionAddress))) + MapBuffer.append('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + TextSectionAddress), 0 - (BaseAddress + DataSectionAddress))) else: - MapBuffer.write('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo.Guid, BaseAddress + TextSectionAddress, BaseAddress + DataSectionAddress)) + MapBuffer.append('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo.Guid, BaseAddress + TextSectionAddress, BaseAddress + DataSectionAddress)) # # Add debug image full path. # - MapBuffer.write('(IMAGE=%s)\n\n' % (ModuleDebugImage)) + MapBuffer.append('(IMAGE=%s)\n\n' % (ModuleDebugImage)) # # Add funtion address # for Function in FunctionList: if AddrIsOffset: - MapBuffer.write(' -0x%010X %s\n' % (0 - (BaseAddress + Function[1]), Function[0])) + MapBuffer.append(' -0x%010X %s\n' % (0 - (BaseAddress + Function[1]), Function[0])) else: - MapBuffer.write(' 0x%010X %s\n' % (BaseAddress + Function[1], Function[0])) + MapBuffer.append(' 0x%010X %s\n' % (BaseAddress + Function[1], Function[0])) ImageMap.close() # @@ -1475,7 +1474,7 @@ class Build(): GuidString = MatchGuid.group() if GuidString.upper() in ModuleList: Line = Line.replace(GuidString, ModuleList[GuidString.upper()].Name) - MapBuffer.write(Line) + MapBuffer.append(Line) # # Add the debug image full path. # @@ -1483,7 +1482,7 @@ class Build(): if MatchGuid is not None: GuidString = MatchGuid.group().split("=")[1] if GuidString.upper() in ModuleList: - MapBuffer.write('(IMAGE=%s)\n' % (os.path.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].Name + '.efi'))) + MapBuffer.append('(IMAGE=%s)\n' % (os.path.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].Name + '.efi'))) FvMap.close() @@ -1599,11 +1598,11 @@ class Build(): if ReturnValue != 0: EdkLogger.error("build", PARAMETER_INVALID, "Patch PCD value failed", ExtraData=ErrorInfo) - MapBuffer.write('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize // 0x1000)) - MapBuffer.write('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize // 0x1000)) - MapBuffer.write('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize // 0x1000)) + MapBuffer.append('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize // 0x1000)) + MapBuffer.append('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize // 0x1000)) + MapBuffer.append('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize // 0x1000)) if len (SmmModuleList) > 0: - MapBuffer.write('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize // 0x1000)) + MapBuffer.append('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize // 0x1000)) PeiBaseAddr = TopMemoryAddress - RtSize - BtSize BtBaseAddr = TopMemoryAddress - RtSize @@ -1613,7 +1612,7 @@ class Build(): self._RebaseModule (MapBuffer, BtBaseAddr, BtModuleList, TopMemoryAddress == 0) self._RebaseModule (MapBuffer, RtBaseAddr, RtModuleList, TopMemoryAddress == 0) self._RebaseModule (MapBuffer, 0x1000, SmmModuleList, AddrIsOffset=False, ModeIsSmm=True) - MapBuffer.write('\n\n') + MapBuffer.append('\n\n') sys.stdout.write ("\n") sys.stdout.flush() @@ -1627,8 +1626,7 @@ class Build(): # # Save address map into MAP file. # - SaveFileOnChange(MapFilePath, MapBuffer.getvalue(), False) - MapBuffer.close() + SaveFileOnChange(MapFilePath, ''.join(MapBuffer), False) if self.LoadFixAddress != 0: sys.stdout.write ("\nLoad Module At Fix Address Map file can be found at %s\n" % (MapFilePath)) sys.stdout.flush() @@ -1703,7 +1701,7 @@ class Build(): if not Ma.IsLibrary: ModuleList[Ma.Guid.upper()] = Ma - MapBuffer = BytesIO('') + MapBuffer = [] if self.LoadFixAddress != 0: # # Rebase module to the preferred memory address before GenFds @@ -1861,7 +1859,7 @@ class Build(): if not Ma.IsLibrary: ModuleList[Ma.Guid.upper()] = Ma - MapBuffer = BytesIO('') + MapBuffer = [] if self.LoadFixAddress != 0: # # Rebase module to the preferred memory address before GenFds @@ -2042,7 +2040,7 @@ class Build(): # # Rebase module to the preferred memory address before GenFds # - MapBuffer = BytesIO('') + MapBuffer = [] if self.LoadFixAddress != 0: self._CollectModuleMapBuffer(MapBuffer, ModuleList)