BaseTools: Add DevicePath support for PCD values
[mirror_edk2.git] / BaseTools / Source / Python / Common / Misc.py
1 ## @file
2 # Common routines used by all tools
3 #
4 # Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
9 #
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12 #
13
14 ##
15 # Import Modules
16 #
17 import Common.LongFilePathOs as os
18 import sys
19 import string
20 import thread
21 import threading
22 import time
23 import re
24 import cPickle
25 import array
26 import shutil
27 from struct import pack
28 from UserDict import IterableUserDict
29 from UserList import UserList
30
31 from Common import EdkLogger as EdkLogger
32 from Common import GlobalData as GlobalData
33 from DataType import *
34 from BuildToolError import *
35 from CommonDataClass.DataClass import *
36 from Parsing import GetSplitValueList
37 from Common.LongFilePathSupport import OpenLongFilePath as open
38 from Common.MultipleWorkspace import MultipleWorkspace as mws
39 import uuid
40 from CommonDataClass.Exceptions import BadExpression
41 import subprocess
42 ## Regular expression used to find out place holders in string template
43 gPlaceholderPattern = re.compile("\$\{([^$()\s]+)\}", re.MULTILINE | re.UNICODE)
44
45 ## Dictionary used to store file time stamp for quick re-access
46 gFileTimeStampCache = {} # {file path : file time stamp}
47
48 ## Dictionary used to store dependencies of files
49 gDependencyDatabase = {} # arch : {file path : [dependent files list]}
50
51 def GetVariableOffset(mapfilepath, efifilepath, varnames):
52 """ Parse map file to get variable offset in current EFI file
53 @param mapfilepath Map file absolution path
54 @param efifilepath: EFI binary file full path
55 @param varnames iteratable container whose elements are variable names to be searched
56
57 @return List whos elements are tuple with variable name and raw offset
58 """
59 lines = []
60 try:
61 f = open(mapfilepath, 'r')
62 lines = f.readlines()
63 f.close()
64 except:
65 return None
66
67 if len(lines) == 0: return None
68 firstline = lines[0].strip()
69 if (firstline.startswith("Archive member included ") and
70 firstline.endswith(" file (symbol)")):
71 return _parseForGCC(lines, efifilepath, varnames)
72 if firstline.startswith("# Path:"):
73 return _parseForXcode(lines, efifilepath, varnames)
74 return _parseGeneral(lines, efifilepath, varnames)
75
76 def _parseForXcode(lines, efifilepath, varnames):
77 status = 0
78 ret = []
79 for index, line in enumerate(lines):
80 line = line.strip()
81 if status == 0 and line == "# Symbols:":
82 status = 1
83 continue
84 if status == 1 and len(line) != 0:
85 for varname in varnames:
86 if varname in line:
87 m = re.match('^([\da-fA-FxX]+)([\s\S]*)([_]*%s)$' % varname, line)
88 if m != None:
89 ret.append((varname, m.group(1)))
90 return ret
91
92 def _parseForGCC(lines, efifilepath, varnames):
93 """ Parse map file generated by GCC linker """
94 status = 0
95 sections = []
96 varoffset = []
97 for index, line in enumerate(lines):
98 line = line.strip()
99 # status machine transection
100 if status == 0 and line == "Memory Configuration":
101 status = 1
102 continue
103 elif status == 1 and line == 'Linker script and memory map':
104 status = 2
105 continue
106 elif status ==2 and line == 'START GROUP':
107 status = 3
108 continue
109
110 # status handler
111 if status == 3:
112 m = re.match('^([\w_\.]+) +([\da-fA-Fx]+) +([\da-fA-Fx]+)$', line)
113 if m != None:
114 sections.append(m.groups(0))
115 for varname in varnames:
116 Str = ''
117 m = re.match("^.data.(%s)" % varname, line)
118 if m != None:
119 m = re.match(".data.(%s)$" % varname, line)
120 if m != None:
121 Str = lines[index + 1]
122 else:
123 Str = line[len(".data.%s" % varname):]
124 if Str:
125 m = re.match('^([\da-fA-Fx]+) +([\da-fA-Fx]+)', Str.strip())
126 if m != None:
127 varoffset.append((varname, int(m.groups(0)[0], 16) , int(sections[-1][1], 16), sections[-1][0]))
128
129 if not varoffset:
130 return []
131 # get section information from efi file
132 efisecs = PeImageClass(efifilepath).SectionHeaderList
133 if efisecs == None or len(efisecs) == 0:
134 return []
135 #redirection
136 redirection = 0
137 for efisec in efisecs:
138 for section in sections:
139 if section[0].strip() == efisec[0].strip() and section[0].strip() == '.text':
140 redirection = int(section[1], 16) - efisec[1]
141
142 ret = []
143 for var in varoffset:
144 for efisec in efisecs:
145 if var[1] >= efisec[1] and var[1] < efisec[1]+efisec[3]:
146 ret.append((var[0], hex(efisec[2] + var[1] - efisec[1] - redirection)))
147 return ret
148
149 def _parseGeneral(lines, efifilepath, varnames):
150 status = 0 #0 - beginning of file; 1 - PE section definition; 2 - symbol table
151 secs = [] # key = section name
152 varoffset = []
153 secRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\da-fA-F]+)[Hh]? +([.\w\$]+) +(\w+)', re.UNICODE)
154 symRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\.:\\\\\w\?@\$]+) +([\da-fA-F]+)', re.UNICODE)
155
156 for line in lines:
157 line = line.strip()
158 if re.match("^Start[' ']+Length[' ']+Name[' ']+Class", line):
159 status = 1
160 continue
161 if re.match("^Address[' ']+Publics by Value[' ']+Rva\+Base", line):
162 status = 2
163 continue
164 if re.match("^entry point at", line):
165 status = 3
166 continue
167 if status == 1 and len(line) != 0:
168 m = secRe.match(line)
169 assert m != None, "Fail to parse the section in map file , line is %s" % line
170 sec_no, sec_start, sec_length, sec_name, sec_class = m.groups(0)
171 secs.append([int(sec_no, 16), int(sec_start, 16), int(sec_length, 16), sec_name, sec_class])
172 if status == 2 and len(line) != 0:
173 for varname in varnames:
174 m = symRe.match(line)
175 assert m != None, "Fail to parse the symbol in map file, line is %s" % line
176 sec_no, sym_offset, sym_name, vir_addr = m.groups(0)
177 sec_no = int(sec_no, 16)
178 sym_offset = int(sym_offset, 16)
179 vir_addr = int(vir_addr, 16)
180 m2 = re.match('^[_]*(%s)' % varname, sym_name)
181 if m2 != None:
182 # fond a binary pcd entry in map file
183 for sec in secs:
184 if sec[0] == sec_no and (sym_offset >= sec[1] and sym_offset < sec[1] + sec[2]):
185 varoffset.append([varname, sec[3], sym_offset, vir_addr, sec_no])
186
187 if not varoffset: return []
188
189 # get section information from efi file
190 efisecs = PeImageClass(efifilepath).SectionHeaderList
191 if efisecs == None or len(efisecs) == 0:
192 return []
193
194 ret = []
195 for var in varoffset:
196 index = 0
197 for efisec in efisecs:
198 index = index + 1
199 if var[1].strip() == efisec[0].strip():
200 ret.append((var[0], hex(efisec[2] + var[2])))
201 elif var[4] == index:
202 ret.append((var[0], hex(efisec[2] + var[2])))
203
204 return ret
205
206 ## Routine to process duplicated INF
207 #
208 # This function is called by following two cases:
209 # Case 1 in DSC:
210 # [components.arch]
211 # Pkg/module/module.inf
212 # Pkg/module/module.inf {
213 # <Defines>
214 # FILE_GUID = 0D1B936F-68F3-4589-AFCC-FB8B7AEBC836
215 # }
216 # Case 2 in FDF:
217 # INF Pkg/module/module.inf
218 # INF FILE_GUID = 0D1B936F-68F3-4589-AFCC-FB8B7AEBC836 Pkg/module/module.inf
219 #
220 # This function copies Pkg/module/module.inf to
221 # Conf/.cache/0D1B936F-68F3-4589-AFCC-FB8B7AEBC836module.inf
222 #
223 # @param Path Original PathClass object
224 # @param BaseName New file base name
225 #
226 # @retval return the new PathClass object
227 #
228 def ProcessDuplicatedInf(Path, BaseName, Workspace):
229 Filename = os.path.split(Path.File)[1]
230 if '.' in Filename:
231 Filename = BaseName + Path.BaseName + Filename[Filename.rfind('.'):]
232 else:
233 Filename = BaseName + Path.BaseName
234
235 #
236 # If -N is specified on command line, cache is disabled
237 # The directory has to be created
238 #
239 DbDir = os.path.split(GlobalData.gDatabasePath)[0]
240 if not os.path.exists(DbDir):
241 os.makedirs(DbDir)
242 #
243 # A temporary INF is copied to database path which must have write permission
244 # The temporary will be removed at the end of build
245 # In case of name conflict, the file name is
246 # FILE_GUIDBaseName (0D1B936F-68F3-4589-AFCC-FB8B7AEBC836module.inf)
247 #
248 TempFullPath = os.path.join(DbDir,
249 Filename)
250 RtPath = PathClass(Path.File, Workspace)
251 #
252 # Modify the full path to temporary path, keep other unchanged
253 #
254 # To build same module more than once, the module path with FILE_GUID overridden has
255 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the real path
256 # in DSC which is used as relative path by C files and other files in INF.
257 # A trick was used: all module paths are PathClass instances, after the initialization
258 # of PathClass, the PathClass.Path is overridden by the temporary INF path.
259 #
260 # The reason for creating a temporary INF is:
261 # Platform.Modules which is the base to create ModuleAutoGen objects is a dictionary,
262 # the key is the full path of INF, the value is an object to save overridden library instances, PCDs.
263 # A different key for the same module is needed to create different output directory,
264 # retrieve overridden PCDs, library instances.
265 #
266 # The BaseName is the FILE_GUID which is also the output directory name.
267 #
268 #
269 RtPath.Path = TempFullPath
270 RtPath.BaseName = BaseName
271 #
272 # If file exists, compare contents
273 #
274 if os.path.exists(TempFullPath):
275 with open(str(Path), 'rb') as f1: Src = f1.read()
276 with open(TempFullPath, 'rb') as f2: Dst = f2.read()
277 if Src == Dst:
278 return RtPath
279 GlobalData.gTempInfs.append(TempFullPath)
280 shutil.copy2(str(Path), TempFullPath)
281 return RtPath
282
283 ## Remove temporary created INFs whose paths were saved in gTempInfs
284 #
285 def ClearDuplicatedInf():
286 for File in GlobalData.gTempInfs:
287 if os.path.exists(File):
288 os.remove(File)
289
290 ## callback routine for processing variable option
291 #
292 # This function can be used to process variable number of option values. The
293 # typical usage of it is specify architecure list on command line.
294 # (e.g. <tool> -a IA32 X64 IPF)
295 #
296 # @param Option Standard callback function parameter
297 # @param OptionString Standard callback function parameter
298 # @param Value Standard callback function parameter
299 # @param Parser Standard callback function parameter
300 #
301 # @retval
302 #
303 def ProcessVariableArgument(Option, OptionString, Value, Parser):
304 assert Value is None
305 Value = []
306 RawArgs = Parser.rargs
307 while RawArgs:
308 Arg = RawArgs[0]
309 if (Arg[:2] == "--" and len(Arg) > 2) or \
310 (Arg[:1] == "-" and len(Arg) > 1 and Arg[1] != "-"):
311 break
312 Value.append(Arg)
313 del RawArgs[0]
314 setattr(Parser.values, Option.dest, Value)
315
316 ## Convert GUID string in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx style to C structure style
317 #
318 # @param Guid The GUID string
319 #
320 # @retval string The GUID string in C structure style
321 #
322 def GuidStringToGuidStructureString(Guid):
323 GuidList = Guid.split('-')
324 Result = '{'
325 for Index in range(0, 3, 1):
326 Result = Result + '0x' + GuidList[Index] + ', '
327 Result = Result + '{0x' + GuidList[3][0:2] + ', 0x' + GuidList[3][2:4]
328 for Index in range(0, 12, 2):
329 Result = Result + ', 0x' + GuidList[4][Index:Index + 2]
330 Result += '}}'
331 return Result
332
333 ## Convert GUID structure in byte array to xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
334 #
335 # @param GuidValue The GUID value in byte array
336 #
337 # @retval string The GUID value in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format
338 #
339 def GuidStructureByteArrayToGuidString(GuidValue):
340 guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "").replace(";", "")
341 guidValueList = guidValueString.split(",")
342 if len(guidValueList) != 16:
343 return ''
344 #EdkLogger.error(None, None, "Invalid GUID value string %s" % GuidValue)
345 try:
346 return "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x" % (
347 int(guidValueList[3], 16),
348 int(guidValueList[2], 16),
349 int(guidValueList[1], 16),
350 int(guidValueList[0], 16),
351 int(guidValueList[5], 16),
352 int(guidValueList[4], 16),
353 int(guidValueList[7], 16),
354 int(guidValueList[6], 16),
355 int(guidValueList[8], 16),
356 int(guidValueList[9], 16),
357 int(guidValueList[10], 16),
358 int(guidValueList[11], 16),
359 int(guidValueList[12], 16),
360 int(guidValueList[13], 16),
361 int(guidValueList[14], 16),
362 int(guidValueList[15], 16)
363 )
364 except:
365 return ''
366
367 ## Convert GUID string in C structure style to xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
368 #
369 # @param GuidValue The GUID value in C structure format
370 #
371 # @retval string The GUID value in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format
372 #
373 def GuidStructureStringToGuidString(GuidValue):
374 guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "").replace(";", "")
375 guidValueList = guidValueString.split(",")
376 if len(guidValueList) != 11:
377 return ''
378 #EdkLogger.error(None, None, "Invalid GUID value string %s" % GuidValue)
379 try:
380 return "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" % (
381 int(guidValueList[0], 16),
382 int(guidValueList[1], 16),
383 int(guidValueList[2], 16),
384 int(guidValueList[3], 16),
385 int(guidValueList[4], 16),
386 int(guidValueList[5], 16),
387 int(guidValueList[6], 16),
388 int(guidValueList[7], 16),
389 int(guidValueList[8], 16),
390 int(guidValueList[9], 16),
391 int(guidValueList[10], 16)
392 )
393 except:
394 return ''
395
396 ## Convert GUID string in C structure style to xxxxxxxx_xxxx_xxxx_xxxx_xxxxxxxxxxxx
397 #
398 # @param GuidValue The GUID value in C structure format
399 #
400 # @retval string The GUID value in xxxxxxxx_xxxx_xxxx_xxxx_xxxxxxxxxxxx format
401 #
402 def GuidStructureStringToGuidValueName(GuidValue):
403 guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "")
404 guidValueList = guidValueString.split(",")
405 if len(guidValueList) != 11:
406 EdkLogger.error(None, FORMAT_INVALID, "Invalid GUID value string [%s]" % GuidValue)
407 return "%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x" % (
408 int(guidValueList[0], 16),
409 int(guidValueList[1], 16),
410 int(guidValueList[2], 16),
411 int(guidValueList[3], 16),
412 int(guidValueList[4], 16),
413 int(guidValueList[5], 16),
414 int(guidValueList[6], 16),
415 int(guidValueList[7], 16),
416 int(guidValueList[8], 16),
417 int(guidValueList[9], 16),
418 int(guidValueList[10], 16)
419 )
420
421 ## Create directories
422 #
423 # @param Directory The directory name
424 #
425 def CreateDirectory(Directory):
426 if Directory == None or Directory.strip() == "":
427 return True
428 try:
429 if not os.access(Directory, os.F_OK):
430 os.makedirs(Directory)
431 except:
432 return False
433 return True
434
435 ## Remove directories, including files and sub-directories in it
436 #
437 # @param Directory The directory name
438 #
439 def RemoveDirectory(Directory, Recursively=False):
440 if Directory == None or Directory.strip() == "" or not os.path.exists(Directory):
441 return
442 if Recursively:
443 CurrentDirectory = os.getcwd()
444 os.chdir(Directory)
445 for File in os.listdir("."):
446 if os.path.isdir(File):
447 RemoveDirectory(File, Recursively)
448 else:
449 os.remove(File)
450 os.chdir(CurrentDirectory)
451 os.rmdir(Directory)
452
453 ## Check if given file is changed or not
454 #
455 # This method is used to check if a file is changed or not between two build
456 # actions. It makes use a cache to store files timestamp.
457 #
458 # @param File The path of file
459 #
460 # @retval True If the given file is changed, doesn't exist, or can't be
461 # found in timestamp cache
462 # @retval False If the given file is changed
463 #
464 def IsChanged(File):
465 if not os.path.exists(File):
466 return True
467
468 FileState = os.stat(File)
469 TimeStamp = FileState[-2]
470
471 if File in gFileTimeStampCache and TimeStamp == gFileTimeStampCache[File]:
472 FileChanged = False
473 else:
474 FileChanged = True
475 gFileTimeStampCache[File] = TimeStamp
476
477 return FileChanged
478
479 ## Store content in file
480 #
481 # This method is used to save file only when its content is changed. This is
482 # quite useful for "make" system to decide what will be re-built and what won't.
483 #
484 # @param File The path of file
485 # @param Content The new content of the file
486 # @param IsBinaryFile The flag indicating if the file is binary file or not
487 #
488 # @retval True If the file content is changed and the file is renewed
489 # @retval False If the file content is the same
490 #
491 def SaveFileOnChange(File, Content, IsBinaryFile=True):
492 if not IsBinaryFile:
493 Content = Content.replace("\n", os.linesep)
494
495 if os.path.exists(File):
496 try:
497 if Content == open(File, "rb").read():
498 return False
499 except:
500 EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File)
501
502 DirName = os.path.dirname(File)
503 if not CreateDirectory(DirName):
504 EdkLogger.error(None, FILE_CREATE_FAILURE, "Could not create directory %s" % DirName)
505 else:
506 if DirName == '':
507 DirName = os.getcwd()
508 if not os.access(DirName, os.W_OK):
509 EdkLogger.error(None, PERMISSION_FAILURE, "Do not have write permission on directory %s" % DirName)
510
511 try:
512 if GlobalData.gIsWindows:
513 try:
514 from PyUtility import SaveFileToDisk
515 if not SaveFileToDisk(File, Content):
516 EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData=File)
517 except:
518 Fd = open(File, "wb")
519 Fd.write(Content)
520 Fd.close()
521 else:
522 Fd = open(File, "wb")
523 Fd.write(Content)
524 Fd.close()
525 except IOError, X:
526 EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X)
527
528 return True
529
530 ## Make a Python object persistent on file system
531 #
532 # @param Data The object to be stored in file
533 # @param File The path of file to store the object
534 #
535 def DataDump(Data, File):
536 Fd = None
537 try:
538 Fd = open(File, 'wb')
539 cPickle.dump(Data, Fd, cPickle.HIGHEST_PROTOCOL)
540 except:
541 EdkLogger.error("", FILE_OPEN_FAILURE, ExtraData=File, RaiseError=False)
542 finally:
543 if Fd != None:
544 Fd.close()
545
546 ## Restore a Python object from a file
547 #
548 # @param File The path of file stored the object
549 #
550 # @retval object A python object
551 # @retval None If failure in file operation
552 #
553 def DataRestore(File):
554 Data = None
555 Fd = None
556 try:
557 Fd = open(File, 'rb')
558 Data = cPickle.load(Fd)
559 except Exception, e:
560 EdkLogger.verbose("Failed to load [%s]\n\t%s" % (File, str(e)))
561 Data = None
562 finally:
563 if Fd != None:
564 Fd.close()
565 return Data
566
567 ## Retrieve and cache the real path name in file system
568 #
569 # @param Root The root directory of path relative to
570 #
571 # @retval str The path string if the path exists
572 # @retval None If path doesn't exist
573 #
574 class DirCache:
575 _CACHE_ = set()
576 _UPPER_CACHE_ = {}
577
578 def __init__(self, Root):
579 self._Root = Root
580 for F in os.listdir(Root):
581 self._CACHE_.add(F)
582 self._UPPER_CACHE_[F.upper()] = F
583
584 # =[] operator
585 def __getitem__(self, Path):
586 Path = Path[len(os.path.commonprefix([Path, self._Root])):]
587 if not Path:
588 return self._Root
589 if Path and Path[0] == os.path.sep:
590 Path = Path[1:]
591 if Path in self._CACHE_:
592 return os.path.join(self._Root, Path)
593 UpperPath = Path.upper()
594 if UpperPath in self._UPPER_CACHE_:
595 return os.path.join(self._Root, self._UPPER_CACHE_[UpperPath])
596
597 IndexList = []
598 LastSepIndex = -1
599 SepIndex = Path.find(os.path.sep)
600 while SepIndex > -1:
601 Parent = UpperPath[:SepIndex]
602 if Parent not in self._UPPER_CACHE_:
603 break
604 LastSepIndex = SepIndex
605 SepIndex = Path.find(os.path.sep, LastSepIndex + 1)
606
607 if LastSepIndex == -1:
608 return None
609
610 Cwd = os.getcwd()
611 os.chdir(self._Root)
612 SepIndex = LastSepIndex
613 while SepIndex > -1:
614 Parent = Path[:SepIndex]
615 ParentKey = UpperPath[:SepIndex]
616 if ParentKey not in self._UPPER_CACHE_:
617 os.chdir(Cwd)
618 return None
619
620 if Parent in self._CACHE_:
621 ParentDir = Parent
622 else:
623 ParentDir = self._UPPER_CACHE_[ParentKey]
624 for F in os.listdir(ParentDir):
625 Dir = os.path.join(ParentDir, F)
626 self._CACHE_.add(Dir)
627 self._UPPER_CACHE_[Dir.upper()] = Dir
628
629 SepIndex = Path.find(os.path.sep, SepIndex + 1)
630
631 os.chdir(Cwd)
632 if Path in self._CACHE_:
633 return os.path.join(self._Root, Path)
634 elif UpperPath in self._UPPER_CACHE_:
635 return os.path.join(self._Root, self._UPPER_CACHE_[UpperPath])
636 return None
637
638 ## Get all files of a directory
639 #
640 # @param Root: Root dir
641 # @param SkipList : The files need be skipped
642 #
643 # @retval A list of all files
644 #
645 def GetFiles(Root, SkipList=None, FullPath=True):
646 OriPath = Root
647 FileList = []
648 for Root, Dirs, Files in os.walk(Root):
649 if SkipList:
650 for Item in SkipList:
651 if Item in Dirs:
652 Dirs.remove(Item)
653
654 for File in Files:
655 File = os.path.normpath(os.path.join(Root, File))
656 if not FullPath:
657 File = File[len(OriPath) + 1:]
658 FileList.append(File)
659
660 return FileList
661
662 ## Check if gvien file exists or not
663 #
664 # @param File File name or path to be checked
665 # @param Dir The directory the file is relative to
666 #
667 # @retval True if file exists
668 # @retval False if file doesn't exists
669 #
670 def ValidFile(File, Ext=None):
671 if Ext != None:
672 Dummy, FileExt = os.path.splitext(File)
673 if FileExt.lower() != Ext.lower():
674 return False
675 if not os.path.exists(File):
676 return False
677 return True
678
679 def RealPath(File, Dir='', OverrideDir=''):
680 NewFile = os.path.normpath(os.path.join(Dir, File))
681 NewFile = GlobalData.gAllFiles[NewFile]
682 if not NewFile and OverrideDir:
683 NewFile = os.path.normpath(os.path.join(OverrideDir, File))
684 NewFile = GlobalData.gAllFiles[NewFile]
685 return NewFile
686
687 def RealPath2(File, Dir='', OverrideDir=''):
688 NewFile = None
689 if OverrideDir:
690 NewFile = GlobalData.gAllFiles[os.path.normpath(os.path.join(OverrideDir, File))]
691 if NewFile:
692 if OverrideDir[-1] == os.path.sep:
693 return NewFile[len(OverrideDir):], NewFile[0:len(OverrideDir)]
694 else:
695 return NewFile[len(OverrideDir) + 1:], NewFile[0:len(OverrideDir)]
696 if GlobalData.gAllFiles:
697 NewFile = GlobalData.gAllFiles[os.path.normpath(os.path.join(Dir, File))]
698 if not NewFile:
699 NewFile = os.path.normpath(os.path.join(Dir, File))
700 if not os.path.exists(NewFile):
701 return None, None
702 if NewFile:
703 if Dir:
704 if Dir[-1] == os.path.sep:
705 return NewFile[len(Dir):], NewFile[0:len(Dir)]
706 else:
707 return NewFile[len(Dir) + 1:], NewFile[0:len(Dir)]
708 else:
709 return NewFile, ''
710
711 return None, None
712
713 ## Check if gvien file exists or not
714 #
715 #
716 def ValidFile2(AllFiles, File, Ext=None, Workspace='', EfiSource='', EdkSource='', Dir='.', OverrideDir=''):
717 NewFile = File
718 if Ext != None:
719 Dummy, FileExt = os.path.splitext(File)
720 if FileExt.lower() != Ext.lower():
721 return False, File
722
723 # Replace the Edk macros
724 if OverrideDir != '' and OverrideDir != None:
725 if OverrideDir.find('$(EFI_SOURCE)') > -1:
726 OverrideDir = OverrideDir.replace('$(EFI_SOURCE)', EfiSource)
727 if OverrideDir.find('$(EDK_SOURCE)') > -1:
728 OverrideDir = OverrideDir.replace('$(EDK_SOURCE)', EdkSource)
729
730 # Replace the default dir to current dir
731 if Dir == '.':
732 Dir = os.getcwd()
733 Dir = Dir[len(Workspace) + 1:]
734
735 # First check if File has Edk definition itself
736 if File.find('$(EFI_SOURCE)') > -1 or File.find('$(EDK_SOURCE)') > -1:
737 NewFile = File.replace('$(EFI_SOURCE)', EfiSource)
738 NewFile = NewFile.replace('$(EDK_SOURCE)', EdkSource)
739 NewFile = AllFiles[os.path.normpath(NewFile)]
740 if NewFile != None:
741 return True, NewFile
742
743 # Second check the path with override value
744 if OverrideDir != '' and OverrideDir != None:
745 NewFile = AllFiles[os.path.normpath(os.path.join(OverrideDir, File))]
746 if NewFile != None:
747 return True, NewFile
748
749 # Last check the path with normal definitions
750 File = os.path.join(Dir, File)
751 NewFile = AllFiles[os.path.normpath(File)]
752 if NewFile != None:
753 return True, NewFile
754
755 return False, File
756
757 ## Check if gvien file exists or not
758 #
759 #
760 def ValidFile3(AllFiles, File, Workspace='', EfiSource='', EdkSource='', Dir='.', OverrideDir=''):
761 # Replace the Edk macros
762 if OverrideDir != '' and OverrideDir != None:
763 if OverrideDir.find('$(EFI_SOURCE)') > -1:
764 OverrideDir = OverrideDir.replace('$(EFI_SOURCE)', EfiSource)
765 if OverrideDir.find('$(EDK_SOURCE)') > -1:
766 OverrideDir = OverrideDir.replace('$(EDK_SOURCE)', EdkSource)
767
768 # Replace the default dir to current dir
769 # Dir is current module dir related to workspace
770 if Dir == '.':
771 Dir = os.getcwd()
772 Dir = Dir[len(Workspace) + 1:]
773
774 NewFile = File
775 RelaPath = AllFiles[os.path.normpath(Dir)]
776 NewRelaPath = RelaPath
777
778 while(True):
779 # First check if File has Edk definition itself
780 if File.find('$(EFI_SOURCE)') > -1 or File.find('$(EDK_SOURCE)') > -1:
781 File = File.replace('$(EFI_SOURCE)', EfiSource)
782 File = File.replace('$(EDK_SOURCE)', EdkSource)
783 NewFile = AllFiles[os.path.normpath(File)]
784 if NewFile != None:
785 NewRelaPath = os.path.dirname(NewFile)
786 File = os.path.basename(NewFile)
787 #NewRelaPath = NewFile[:len(NewFile) - len(File.replace("..\\", '').replace("../", '')) - 1]
788 break
789
790 # Second check the path with override value
791 if OverrideDir != '' and OverrideDir != None:
792 NewFile = AllFiles[os.path.normpath(os.path.join(OverrideDir, File))]
793 if NewFile != None:
794 #NewRelaPath = os.path.dirname(NewFile)
795 NewRelaPath = NewFile[:len(NewFile) - len(File.replace("..\\", '').replace("../", '')) - 1]
796 break
797
798 # Last check the path with normal definitions
799 NewFile = AllFiles[os.path.normpath(os.path.join(Dir, File))]
800 if NewFile != None:
801 break
802
803 # No file found
804 break
805
806 return NewRelaPath, RelaPath, File
807
808
809 def GetRelPath(Path1, Path2):
810 FileName = os.path.basename(Path2)
811 L1 = os.path.normpath(Path1).split(os.path.normpath('/'))
812 L2 = os.path.normpath(Path2).split(os.path.normpath('/'))
813 for Index in range(0, len(L1)):
814 if L1[Index] != L2[Index]:
815 FileName = '../' * (len(L1) - Index)
816 for Index2 in range(Index, len(L2)):
817 FileName = os.path.join(FileName, L2[Index2])
818 break
819 return os.path.normpath(FileName)
820
821
822 ## Get GUID value from given packages
823 #
824 # @param CName The CName of the GUID
825 # @param PackageList List of packages looking-up in
826 # @param Inffile The driver file
827 #
828 # @retval GuidValue if the CName is found in any given package
829 # @retval None if the CName is not found in all given packages
830 #
831 def GuidValue(CName, PackageList, Inffile = None):
832 for P in PackageList:
833 GuidKeys = P.Guids.keys()
834 if Inffile and P._PrivateGuids:
835 if not Inffile.startswith(P.MetaFile.Dir):
836 GuidKeys = (dict.fromkeys(x for x in P.Guids if x not in P._PrivateGuids)).keys()
837 if CName in GuidKeys:
838 return P.Guids[CName]
839 return None
840
841 ## Get Protocol value from given packages
842 #
843 # @param CName The CName of the GUID
844 # @param PackageList List of packages looking-up in
845 # @param Inffile The driver file
846 #
847 # @retval GuidValue if the CName is found in any given package
848 # @retval None if the CName is not found in all given packages
849 #
850 def ProtocolValue(CName, PackageList, Inffile = None):
851 for P in PackageList:
852 ProtocolKeys = P.Protocols.keys()
853 if Inffile and P._PrivateProtocols:
854 if not Inffile.startswith(P.MetaFile.Dir):
855 ProtocolKeys = (dict.fromkeys(x for x in P.Protocols if x not in P._PrivateProtocols)).keys()
856 if CName in ProtocolKeys:
857 return P.Protocols[CName]
858 return None
859
860 ## Get PPI value from given packages
861 #
862 # @param CName The CName of the GUID
863 # @param PackageList List of packages looking-up in
864 # @param Inffile The driver file
865 #
866 # @retval GuidValue if the CName is found in any given package
867 # @retval None if the CName is not found in all given packages
868 #
869 def PpiValue(CName, PackageList, Inffile = None):
870 for P in PackageList:
871 PpiKeys = P.Ppis.keys()
872 if Inffile and P._PrivatePpis:
873 if not Inffile.startswith(P.MetaFile.Dir):
874 PpiKeys = (dict.fromkeys(x for x in P.Ppis if x not in P._PrivatePpis)).keys()
875 if CName in PpiKeys:
876 return P.Ppis[CName]
877 return None
878
879 ## A string template class
880 #
881 # This class implements a template for string replacement. A string template
882 # looks like following
883 #
884 # ${BEGIN} other_string ${placeholder_name} other_string ${END}
885 #
886 # The string between ${BEGIN} and ${END} will be repeated as many times as the
887 # length of "placeholder_name", which is a list passed through a dict. The
888 # "placeholder_name" is the key name of the dict. The ${BEGIN} and ${END} can
889 # be not used and, in this case, the "placeholder_name" must not a list and it
890 # will just be replaced once.
891 #
892 class TemplateString(object):
893 _REPEAT_START_FLAG = "BEGIN"
894 _REPEAT_END_FLAG = "END"
895
896 class Section(object):
897 _LIST_TYPES = [type([]), type(set()), type((0,))]
898
899 def __init__(self, TemplateSection, PlaceHolderList):
900 self._Template = TemplateSection
901 self._PlaceHolderList = []
902
903 # Split the section into sub-sections according to the position of placeholders
904 if PlaceHolderList:
905 self._SubSectionList = []
906 SubSectionStart = 0
907 #
908 # The placeholders passed in must be in the format of
909 #
910 # PlaceHolderName, PlaceHolderStartPoint, PlaceHolderEndPoint
911 #
912 for PlaceHolder, Start, End in PlaceHolderList:
913 self._SubSectionList.append(TemplateSection[SubSectionStart:Start])
914 self._SubSectionList.append(TemplateSection[Start:End])
915 self._PlaceHolderList.append(PlaceHolder)
916 SubSectionStart = End
917 if SubSectionStart < len(TemplateSection):
918 self._SubSectionList.append(TemplateSection[SubSectionStart:])
919 else:
920 self._SubSectionList = [TemplateSection]
921
922 def __str__(self):
923 return self._Template + " : " + str(self._PlaceHolderList)
924
925 def Instantiate(self, PlaceHolderValues):
926 RepeatTime = -1
927 RepeatPlaceHolders = {}
928 NonRepeatPlaceHolders = {}
929
930 for PlaceHolder in self._PlaceHolderList:
931 if PlaceHolder not in PlaceHolderValues:
932 continue
933 Value = PlaceHolderValues[PlaceHolder]
934 if type(Value) in self._LIST_TYPES:
935 if RepeatTime < 0:
936 RepeatTime = len(Value)
937 elif RepeatTime != len(Value):
938 EdkLogger.error(
939 "TemplateString",
940 PARAMETER_INVALID,
941 "${%s} has different repeat time from others!" % PlaceHolder,
942 ExtraData=str(self._Template)
943 )
944 RepeatPlaceHolders["${%s}" % PlaceHolder] = Value
945 else:
946 NonRepeatPlaceHolders["${%s}" % PlaceHolder] = Value
947
948 if NonRepeatPlaceHolders:
949 StringList = []
950 for S in self._SubSectionList:
951 if S not in NonRepeatPlaceHolders:
952 StringList.append(S)
953 else:
954 StringList.append(str(NonRepeatPlaceHolders[S]))
955 else:
956 StringList = self._SubSectionList
957
958 if RepeatPlaceHolders:
959 TempStringList = []
960 for Index in range(RepeatTime):
961 for S in StringList:
962 if S not in RepeatPlaceHolders:
963 TempStringList.append(S)
964 else:
965 TempStringList.append(str(RepeatPlaceHolders[S][Index]))
966 StringList = TempStringList
967
968 return "".join(StringList)
969
970 ## Constructor
971 def __init__(self, Template=None):
972 self.String = ''
973 self.IsBinary = False
974 self._Template = Template
975 self._TemplateSectionList = self._Parse(Template)
976
977 ## str() operator
978 #
979 # @retval string The string replaced
980 #
981 def __str__(self):
982 return self.String
983
984 ## Split the template string into fragments per the ${BEGIN} and ${END} flags
985 #
986 # @retval list A list of TemplateString.Section objects
987 #
988 def _Parse(self, Template):
989 SectionStart = 0
990 SearchFrom = 0
991 MatchEnd = 0
992 PlaceHolderList = []
993 TemplateSectionList = []
994 while Template:
995 MatchObj = gPlaceholderPattern.search(Template, SearchFrom)
996 if not MatchObj:
997 if MatchEnd <= len(Template):
998 TemplateSection = TemplateString.Section(Template[SectionStart:], PlaceHolderList)
999 TemplateSectionList.append(TemplateSection)
1000 break
1001
1002 MatchString = MatchObj.group(1)
1003 MatchStart = MatchObj.start()
1004 MatchEnd = MatchObj.end()
1005
1006 if MatchString == self._REPEAT_START_FLAG:
1007 if MatchStart > SectionStart:
1008 TemplateSection = TemplateString.Section(Template[SectionStart:MatchStart], PlaceHolderList)
1009 TemplateSectionList.append(TemplateSection)
1010 SectionStart = MatchEnd
1011 PlaceHolderList = []
1012 elif MatchString == self._REPEAT_END_FLAG:
1013 TemplateSection = TemplateString.Section(Template[SectionStart:MatchStart], PlaceHolderList)
1014 TemplateSectionList.append(TemplateSection)
1015 SectionStart = MatchEnd
1016 PlaceHolderList = []
1017 else:
1018 PlaceHolderList.append((MatchString, MatchStart - SectionStart, MatchEnd - SectionStart))
1019 SearchFrom = MatchEnd
1020 return TemplateSectionList
1021
1022 ## Replace the string template with dictionary of placeholders and append it to previous one
1023 #
1024 # @param AppendString The string template to append
1025 # @param Dictionary The placeholder dictionaries
1026 #
1027 def Append(self, AppendString, Dictionary=None):
1028 if Dictionary:
1029 SectionList = self._Parse(AppendString)
1030 self.String += "".join([S.Instantiate(Dictionary) for S in SectionList])
1031 else:
1032 self.String += AppendString
1033
1034 ## Replace the string template with dictionary of placeholders
1035 #
1036 # @param Dictionary The placeholder dictionaries
1037 #
1038 # @retval str The string replaced with placeholder values
1039 #
1040 def Replace(self, Dictionary=None):
1041 return "".join([S.Instantiate(Dictionary) for S in self._TemplateSectionList])
1042
1043 ## Progress indicator class
1044 #
1045 # This class makes use of thread to print progress on console.
1046 #
1047 class Progressor:
1048 # for avoiding deadloop
1049 _StopFlag = None
1050 _ProgressThread = None
1051 _CheckInterval = 0.25
1052
1053 ## Constructor
1054 #
1055 # @param OpenMessage The string printed before progress charaters
1056 # @param CloseMessage The string printed after progress charaters
1057 # @param ProgressChar The charater used to indicate the progress
1058 # @param Interval The interval in seconds between two progress charaters
1059 #
1060 def __init__(self, OpenMessage="", CloseMessage="", ProgressChar='.', Interval=1.0):
1061 self.PromptMessage = OpenMessage
1062 self.CodaMessage = CloseMessage
1063 self.ProgressChar = ProgressChar
1064 self.Interval = Interval
1065 if Progressor._StopFlag == None:
1066 Progressor._StopFlag = threading.Event()
1067
1068 ## Start to print progress charater
1069 #
1070 # @param OpenMessage The string printed before progress charaters
1071 #
1072 def Start(self, OpenMessage=None):
1073 if OpenMessage != None:
1074 self.PromptMessage = OpenMessage
1075 Progressor._StopFlag.clear()
1076 if Progressor._ProgressThread == None:
1077 Progressor._ProgressThread = threading.Thread(target=self._ProgressThreadEntry)
1078 Progressor._ProgressThread.setDaemon(False)
1079 Progressor._ProgressThread.start()
1080
1081 ## Stop printing progress charater
1082 #
1083 # @param CloseMessage The string printed after progress charaters
1084 #
1085 def Stop(self, CloseMessage=None):
1086 OriginalCodaMessage = self.CodaMessage
1087 if CloseMessage != None:
1088 self.CodaMessage = CloseMessage
1089 self.Abort()
1090 self.CodaMessage = OriginalCodaMessage
1091
1092 ## Thread entry method
1093 def _ProgressThreadEntry(self):
1094 sys.stdout.write(self.PromptMessage + " ")
1095 sys.stdout.flush()
1096 TimeUp = 0.0
1097 while not Progressor._StopFlag.isSet():
1098 if TimeUp <= 0.0:
1099 sys.stdout.write(self.ProgressChar)
1100 sys.stdout.flush()
1101 TimeUp = self.Interval
1102 time.sleep(self._CheckInterval)
1103 TimeUp -= self._CheckInterval
1104 sys.stdout.write(" " + self.CodaMessage + "\n")
1105 sys.stdout.flush()
1106
1107 ## Abort the progress display
1108 @staticmethod
1109 def Abort():
1110 if Progressor._StopFlag != None:
1111 Progressor._StopFlag.set()
1112 if Progressor._ProgressThread != None:
1113 Progressor._ProgressThread.join()
1114 Progressor._ProgressThread = None
1115
1116 ## A dict which can access its keys and/or values orderly
1117 #
1118 # The class implements a new kind of dict which its keys or values can be
1119 # accessed in the order they are added into the dict. It guarantees the order
1120 # by making use of an internal list to keep a copy of keys.
1121 #
1122 class sdict(IterableUserDict):
1123 ## Constructor
1124 def __init__(self):
1125 IterableUserDict.__init__(self)
1126 self._key_list = []
1127
1128 ## [] operator
1129 def __setitem__(self, key, value):
1130 if key not in self._key_list:
1131 self._key_list.append(key)
1132 IterableUserDict.__setitem__(self, key, value)
1133
1134 ## del operator
1135 def __delitem__(self, key):
1136 self._key_list.remove(key)
1137 IterableUserDict.__delitem__(self, key)
1138
1139 ## used in "for k in dict" loop to ensure the correct order
1140 def __iter__(self):
1141 return self.iterkeys()
1142
1143 ## len() support
1144 def __len__(self):
1145 return len(self._key_list)
1146
1147 ## "in" test support
1148 def __contains__(self, key):
1149 return key in self._key_list
1150
1151 ## indexof support
1152 def index(self, key):
1153 return self._key_list.index(key)
1154
1155 ## insert support
1156 def insert(self, key, newkey, newvalue, order):
1157 index = self._key_list.index(key)
1158 if order == 'BEFORE':
1159 self._key_list.insert(index, newkey)
1160 IterableUserDict.__setitem__(self, newkey, newvalue)
1161 elif order == 'AFTER':
1162 self._key_list.insert(index + 1, newkey)
1163 IterableUserDict.__setitem__(self, newkey, newvalue)
1164
1165 ## append support
1166 def append(self, sdict):
1167 for key in sdict:
1168 if key not in self._key_list:
1169 self._key_list.append(key)
1170 IterableUserDict.__setitem__(self, key, sdict[key])
1171
1172 def has_key(self, key):
1173 return key in self._key_list
1174
1175 ## Empty the dict
1176 def clear(self):
1177 self._key_list = []
1178 IterableUserDict.clear(self)
1179
1180 ## Return a copy of keys
1181 def keys(self):
1182 keys = []
1183 for key in self._key_list:
1184 keys.append(key)
1185 return keys
1186
1187 ## Return a copy of values
1188 def values(self):
1189 values = []
1190 for key in self._key_list:
1191 values.append(self[key])
1192 return values
1193
1194 ## Return a copy of (key, value) list
1195 def items(self):
1196 items = []
1197 for key in self._key_list:
1198 items.append((key, self[key]))
1199 return items
1200
1201 ## Iteration support
1202 def iteritems(self):
1203 return iter(self.items())
1204
1205 ## Keys interation support
1206 def iterkeys(self):
1207 return iter(self.keys())
1208
1209 ## Values interation support
1210 def itervalues(self):
1211 return iter(self.values())
1212
1213 ## Return value related to a key, and remove the (key, value) from the dict
1214 def pop(self, key, *dv):
1215 value = None
1216 if key in self._key_list:
1217 value = self[key]
1218 self.__delitem__(key)
1219 elif len(dv) != 0 :
1220 value = kv[0]
1221 return value
1222
1223 ## Return (key, value) pair, and remove the (key, value) from the dict
1224 def popitem(self):
1225 key = self._key_list[-1]
1226 value = self[key]
1227 self.__delitem__(key)
1228 return key, value
1229
1230 def update(self, dict=None, **kwargs):
1231 if dict != None:
1232 for k, v in dict.items():
1233 self[k] = v
1234 if len(kwargs):
1235 for k, v in kwargs.items():
1236 self[k] = v
1237
1238 ## Dictionary with restricted keys
1239 #
1240 class rdict(dict):
1241 ## Constructor
1242 def __init__(self, KeyList):
1243 for Key in KeyList:
1244 dict.__setitem__(self, Key, "")
1245
1246 ## []= operator
1247 def __setitem__(self, key, value):
1248 if key not in self:
1249 EdkLogger.error("RestrictedDict", ATTRIBUTE_SET_FAILURE, "Key [%s] is not allowed" % key,
1250 ExtraData=", ".join(dict.keys(self)))
1251 dict.__setitem__(self, key, value)
1252
1253 ## =[] operator
1254 def __getitem__(self, key):
1255 if key not in self:
1256 return ""
1257 return dict.__getitem__(self, key)
1258
1259 ## del operator
1260 def __delitem__(self, key):
1261 EdkLogger.error("RestrictedDict", ATTRIBUTE_ACCESS_DENIED, ExtraData="del")
1262
1263 ## Empty the dict
1264 def clear(self):
1265 for Key in self:
1266 self.__setitem__(Key, "")
1267
1268 ## Return value related to a key, and remove the (key, value) from the dict
1269 def pop(self, key, *dv):
1270 EdkLogger.error("RestrictedDict", ATTRIBUTE_ACCESS_DENIED, ExtraData="pop")
1271
1272 ## Return (key, value) pair, and remove the (key, value) from the dict
1273 def popitem(self):
1274 EdkLogger.error("RestrictedDict", ATTRIBUTE_ACCESS_DENIED, ExtraData="popitem")
1275
1276 ## Dictionary using prioritized list as key
1277 #
1278 class tdict:
1279 _ListType = type([])
1280 _TupleType = type(())
1281 _Wildcard = 'COMMON'
1282 _ValidWildcardList = ['COMMON', 'DEFAULT', 'ALL', '*', 'PLATFORM']
1283
1284 def __init__(self, _Single_=False, _Level_=2):
1285 self._Level_ = _Level_
1286 self.data = {}
1287 self._Single_ = _Single_
1288
1289 # =[] operator
1290 def __getitem__(self, key):
1291 KeyType = type(key)
1292 RestKeys = None
1293 if KeyType == self._ListType or KeyType == self._TupleType:
1294 FirstKey = key[0]
1295 if len(key) > 1:
1296 RestKeys = key[1:]
1297 elif self._Level_ > 1:
1298 RestKeys = [self._Wildcard for i in range(0, self._Level_ - 1)]
1299 else:
1300 FirstKey = key
1301 if self._Level_ > 1:
1302 RestKeys = [self._Wildcard for i in range(0, self._Level_ - 1)]
1303
1304 if FirstKey == None or str(FirstKey).upper() in self._ValidWildcardList:
1305 FirstKey = self._Wildcard
1306
1307 if self._Single_:
1308 return self._GetSingleValue(FirstKey, RestKeys)
1309 else:
1310 return self._GetAllValues(FirstKey, RestKeys)
1311
1312 def _GetSingleValue(self, FirstKey, RestKeys):
1313 Value = None
1314 #print "%s-%s" % (FirstKey, self._Level_) ,
1315 if self._Level_ > 1:
1316 if FirstKey == self._Wildcard:
1317 if FirstKey in self.data:
1318 Value = self.data[FirstKey][RestKeys]
1319 if Value == None:
1320 for Key in self.data:
1321 Value = self.data[Key][RestKeys]
1322 if Value != None: break
1323 else:
1324 if FirstKey in self.data:
1325 Value = self.data[FirstKey][RestKeys]
1326 if Value == None and self._Wildcard in self.data:
1327 #print "Value=None"
1328 Value = self.data[self._Wildcard][RestKeys]
1329 else:
1330 if FirstKey == self._Wildcard:
1331 if FirstKey in self.data:
1332 Value = self.data[FirstKey]
1333 if Value == None:
1334 for Key in self.data:
1335 Value = self.data[Key]
1336 if Value != None: break
1337 else:
1338 if FirstKey in self.data:
1339 Value = self.data[FirstKey]
1340 elif self._Wildcard in self.data:
1341 Value = self.data[self._Wildcard]
1342 return Value
1343
1344 def _GetAllValues(self, FirstKey, RestKeys):
1345 Value = []
1346 if self._Level_ > 1:
1347 if FirstKey == self._Wildcard:
1348 for Key in self.data:
1349 Value += self.data[Key][RestKeys]
1350 else:
1351 if FirstKey in self.data:
1352 Value += self.data[FirstKey][RestKeys]
1353 if self._Wildcard in self.data:
1354 Value += self.data[self._Wildcard][RestKeys]
1355 else:
1356 if FirstKey == self._Wildcard:
1357 for Key in self.data:
1358 Value.append(self.data[Key])
1359 else:
1360 if FirstKey in self.data:
1361 Value.append(self.data[FirstKey])
1362 if self._Wildcard in self.data:
1363 Value.append(self.data[self._Wildcard])
1364 return Value
1365
1366 ## []= operator
1367 def __setitem__(self, key, value):
1368 KeyType = type(key)
1369 RestKeys = None
1370 if KeyType == self._ListType or KeyType == self._TupleType:
1371 FirstKey = key[0]
1372 if len(key) > 1:
1373 RestKeys = key[1:]
1374 else:
1375 RestKeys = [self._Wildcard for i in range(0, self._Level_ - 1)]
1376 else:
1377 FirstKey = key
1378 if self._Level_ > 1:
1379 RestKeys = [self._Wildcard for i in range(0, self._Level_ - 1)]
1380
1381 if FirstKey in self._ValidWildcardList:
1382 FirstKey = self._Wildcard
1383
1384 if FirstKey not in self.data and self._Level_ > 0:
1385 self.data[FirstKey] = tdict(self._Single_, self._Level_ - 1)
1386
1387 if self._Level_ > 1:
1388 self.data[FirstKey][RestKeys] = value
1389 else:
1390 self.data[FirstKey] = value
1391
1392 def SetGreedyMode(self):
1393 self._Single_ = False
1394 if self._Level_ > 1:
1395 for Key in self.data:
1396 self.data[Key].SetGreedyMode()
1397
1398 def SetSingleMode(self):
1399 self._Single_ = True
1400 if self._Level_ > 1:
1401 for Key in self.data:
1402 self.data[Key].SetSingleMode()
1403
1404 def GetKeys(self, KeyIndex=0):
1405 assert KeyIndex >= 0
1406 if KeyIndex == 0:
1407 return set(self.data.keys())
1408 else:
1409 keys = set()
1410 for Key in self.data:
1411 keys |= self.data[Key].GetKeys(KeyIndex - 1)
1412 return keys
1413
1414 ## Boolean chain list
1415 #
1416 class Blist(UserList):
1417 def __init__(self, initlist=None):
1418 UserList.__init__(self, initlist)
1419 def __setitem__(self, i, item):
1420 if item not in [True, False]:
1421 if item == 0:
1422 item = False
1423 else:
1424 item = True
1425 self.data[i] = item
1426 def _GetResult(self):
1427 Value = True
1428 for item in self.data:
1429 Value &= item
1430 return Value
1431 Result = property(_GetResult)
1432
1433 def ParseConsoleLog(Filename):
1434 Opr = open(os.path.normpath(Filename), 'r')
1435 Opw = open(os.path.normpath(Filename + '.New'), 'w+')
1436 for Line in Opr.readlines():
1437 if Line.find('.efi') > -1:
1438 Line = Line[Line.rfind(' ') : Line.rfind('.efi')].strip()
1439 Opw.write('%s\n' % Line)
1440
1441 Opr.close()
1442 Opw.close()
1443
1444 def AnalyzePcdExpression(Setting):
1445 Setting = Setting.strip()
1446 # There might be escaped quote in a string: \", \\\"
1447 Data = Setting.replace('\\\\', '//').replace('\\\"', '\\\'')
1448 # There might be '|' in string and in ( ... | ... ), replace it with '-'
1449 NewStr = ''
1450 InStr = False
1451 Pair = 0
1452 for ch in Data:
1453 if ch == '"':
1454 InStr = not InStr
1455 elif ch == '(' and not InStr:
1456 Pair += 1
1457 elif ch == ')' and not InStr:
1458 Pair -= 1
1459
1460 if (Pair > 0 or InStr) and ch == TAB_VALUE_SPLIT:
1461 NewStr += '-'
1462 else:
1463 NewStr += ch
1464 FieldList = []
1465 StartPos = 0
1466 while True:
1467 Pos = NewStr.find(TAB_VALUE_SPLIT, StartPos)
1468 if Pos < 0:
1469 FieldList.append(Setting[StartPos:].strip())
1470 break
1471 FieldList.append(Setting[StartPos:Pos].strip())
1472 StartPos = Pos + 1
1473
1474 return FieldList
1475
1476 def ParseDevPathValue (Value):
1477 DevPathList = [ "Path","HardwarePath","Pci","PcCard","MemoryMapped","VenHw","Ctrl","BMC","AcpiPath","Acpi","PciRoot",
1478 "PcieRoot","Floppy","Keyboard","Serial","ParallelPort","AcpiEx","AcpiExp","AcpiAdr","Msg","Ata","Scsi",
1479 "Fibre","FibreEx","I1394","USB","I2O","Infiniband","VenMsg","VenPcAnsi","VenVt100","VenVt100Plus",
1480 "VenUtf8","UartFlowCtrl","SAS","SasEx","NVMe","UFS","SD","eMMC","DebugPort","MAC","IPv4","IPv6","Uart",
1481 "UsbClass","UsbAudio","UsbCDCControl","UsbHID","UsbImage","UsbPrinter","UsbMassStorage","UsbHub",
1482 "UsbCDCData","UsbSmartCard","UsbVideo","UsbDiagnostic","UsbWireless","UsbDeviceFirmwareUpdate",
1483 "UsbIrdaBridge","UsbTestAndMeasurement","UsbWwid","Unit","iSCSI","Vlan","Uri","Bluetooth","Wi-Fi",
1484 "MediaPath","HD","CDROM","VenMedia","Media","Fv","FvFile","Offset","RamDisk","VirtualDisk","VirtualCD",
1485 "PersistentVirtualDisk","PersistentVirtualCD","BbsPath","BBS","Sata" ]
1486 if '\\' in Value:
1487 Value.replace('\\', '/').replace(' ', '')
1488 for Item in Value.split('/'):
1489 Key = Item.strip().split('(')[0]
1490 if Key not in DevPathList:
1491 pass
1492
1493 Cmd = 'DevicePath ' + '"' + Value + '"'
1494 try:
1495 p = subprocess.Popen(Cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
1496 out, err = p.communicate()
1497 except Exception, X:
1498 raise BadExpression("DevicePath: %s" % (str(X)) )
1499 finally:
1500 subprocess._cleanup()
1501 p.stdout.close()
1502 p.stderr.close()
1503 if err:
1504 raise BadExpression("DevicePath: %s" % str(err))
1505 Size = len(out.split())
1506 out = ','.join(out.split())
1507 return '{' + out + '}', Size
1508
1509 def ParseFieldValue (Value):
1510 if type(Value) == type(0):
1511 return Value, (Value.bit_length() + 7) / 8
1512 if type(Value) <> type(''):
1513 raise BadExpression('Type %s is %s' %(Value, type(Value)))
1514 Value = Value.strip()
1515 if Value.startswith('UINT8') and Value.endswith(')'):
1516 Value, Size = ParseFieldValue(Value.split('(', 1)[1][:-1])
1517 if Size > 1:
1518 raise BadExpression('Value (%s) Size larger than %d' %(Value, Size))
1519 return Value, 1
1520 if Value.startswith('UINT16') and Value.endswith(')'):
1521 Value, Size = ParseFieldValue(Value.split('(', 1)[1][:-1])
1522 if Size > 2:
1523 raise BadExpression('Value (%s) Size larger than %d' %(Value, Size))
1524 return Value, 2
1525 if Value.startswith('UINT32') and Value.endswith(')'):
1526 Value, Size = ParseFieldValue(Value.split('(', 1)[1][:-1])
1527 if Size > 4:
1528 raise BadExpression('Value (%s) Size larger than %d' %(Value, Size))
1529 return Value, 4
1530 if Value.startswith('UINT64') and Value.endswith(')'):
1531 Value, Size = ParseFieldValue(Value.split('(', 1)[1][:-1])
1532 if Size > 8:
1533 raise BadExpression('Value (%s) Size larger than %d' % (Value, Size))
1534 return Value, 8
1535 if Value.startswith('GUID') and Value.endswith(')'):
1536 Value = Value.split('(', 1)[1][:-1].strip()
1537 if Value[0] == '{' and Value[-1] == '}':
1538 Value = Value[1:-1].strip()
1539 Value = Value.split('{', 1)
1540 Value = ['%02x' % int(Item, 16) for Item in (Value[0] + Value[1][:-1]).split(',')]
1541 if len(Value[0]) != 8:
1542 Value[0] = '%08X' % int(Value[0], 16)
1543 if len(Value[1]) != 4:
1544 Value[1] = '%04X' % int(Value[1], 16)
1545 if len(Value[2]) != 4:
1546 Value[2] = '%04X' % int(Value[2], 16)
1547 Value = '-'.join(Value[0:3]) + '-' + ''.join(Value[3:5]) + '-' + ''.join(Value[5:11])
1548 if Value[0] == '"' and Value[-1] == '"':
1549 Value = Value[1:-1]
1550 try:
1551 Value = "'" + uuid.UUID(Value).get_bytes_le() + "'"
1552 except ValueError, Message:
1553 raise BadExpression('%s' % Message)
1554 Value, Size = ParseFieldValue(Value)
1555 return Value, 16
1556 if Value.startswith('L"') and Value.endswith('"'):
1557 # Unicode String
1558 List = list(Value[2:-1])
1559 List.reverse()
1560 Value = 0
1561 for Char in List:
1562 Value = (Value << 16) | ord(Char)
1563 return Value, (len(List) + 1) * 2
1564 if Value.startswith('"') and Value.endswith('"'):
1565 # ASCII String
1566 List = list(Value[1:-1])
1567 List.reverse()
1568 Value = 0
1569 for Char in List:
1570 Value = (Value << 8) | ord(Char)
1571 return Value, len(List) + 1
1572 if Value.startswith("L'") and Value.endswith("'"):
1573 # Unicode Character Constant
1574 List = list(Value[2:-1])
1575 List.reverse()
1576 Value = 0
1577 for Char in List:
1578 Value = (Value << 16) | ord(Char)
1579 return Value, len(List) * 2
1580 if Value.startswith("'") and Value.endswith("'"):
1581 # Character constant
1582 List = list(Value[1:-1])
1583 List.reverse()
1584 Value = 0
1585 for Char in List:
1586 Value = (Value << 8) | ord(Char)
1587 return Value, len(List)
1588 if Value.startswith('{') and Value.endswith('}'):
1589 # Byte array
1590 Value = Value[1:-1]
1591 List = [Item.strip() for Item in Value.split(',')]
1592 List.reverse()
1593 Value = 0
1594 RetSize = 0
1595 for Item in List:
1596 ItemValue, Size = ParseFieldValue(Item)
1597 RetSize += Size
1598 for I in range(Size):
1599 Value = (Value << 8) | ((ItemValue >> 8 * I) & 0xff)
1600 return Value, RetSize
1601 if Value.startswith('DEVICE_PATH(') and Value.endswith(')'):
1602 Value = Value.split('"')[1]
1603 return ParseDevPathValue(Value)
1604 if Value.lower().startswith('0x'):
1605 Value = int(Value, 16)
1606 if Value == 0:
1607 return 0, 1
1608 return Value, (Value.bit_length() + 7) / 8
1609 if Value[0].isdigit():
1610 Value = int(Value, 10)
1611 if Value == 0:
1612 return 0, 1
1613 return Value, (Value.bit_length() + 7) / 8
1614 if Value.lower() == 'true':
1615 return 1, 1
1616 if Value.lower() == 'false':
1617 return 0, 1
1618 return Value, 1
1619
1620 ## AnalyzeDscPcd
1621 #
1622 # Analyze DSC PCD value, since there is no data type info in DSC
1623 # This fuction is used to match functions (AnalyzePcdData, AnalyzeHiiPcdData, AnalyzeVpdPcdData) used for retrieving PCD value from database
1624 # 1. Feature flag: TokenSpace.PcdCName|PcdValue
1625 # 2. Fix and Patch:TokenSpace.PcdCName|PcdValue[|MaxSize]
1626 # 3. Dynamic default:
1627 # TokenSpace.PcdCName|PcdValue[|VOID*[|MaxSize]]
1628 # TokenSpace.PcdCName|PcdValue
1629 # 4. Dynamic VPD:
1630 # TokenSpace.PcdCName|VpdOffset[|VpdValue]
1631 # TokenSpace.PcdCName|VpdOffset[|MaxSize[|VpdValue]]
1632 # 5. Dynamic HII:
1633 # TokenSpace.PcdCName|HiiString|VaiableGuid|VariableOffset[|HiiValue]
1634 # PCD value needs to be located in such kind of string, and the PCD value might be an expression in which
1635 # there might have "|" operator, also in string value.
1636 #
1637 # @param Setting: String contain information described above with "TokenSpace.PcdCName|" stripped
1638 # @param PcdType: PCD type: feature, fixed, dynamic default VPD HII
1639 # @param DataType: The datum type of PCD: VOID*, UNIT, BOOL
1640 # @retval:
1641 # ValueList: A List contain fields described above
1642 # IsValid: True if conforming EBNF, otherwise False
1643 # Index: The index where PcdValue is in ValueList
1644 #
1645 def AnalyzeDscPcd(Setting, PcdType, DataType=''):
1646 FieldList = AnalyzePcdExpression(Setting)
1647
1648 IsValid = True
1649 if PcdType in (MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_FEATURE_FLAG):
1650 Value = FieldList[0]
1651 Size = ''
1652 if len(FieldList) > 1:
1653 if FieldList[1].upper().startswith("0X") or FieldList[1].isdigit():
1654 Size = FieldList[1]
1655 else:
1656 DataType = FieldList[1]
1657
1658 if len(FieldList) > 2:
1659 Size = FieldList[2]
1660 if DataType == "":
1661 IsValid = (len(FieldList) <= 1)
1662 else:
1663 IsValid = (len(FieldList) <= 3)
1664 # Value, Size = ParseFieldValue(Value)
1665 if Size:
1666 try:
1667 int(Size,16) if Size.upper().startswith("0X") else int(Size)
1668 except:
1669 IsValid = False
1670 Size = -1
1671 return [str(Value), '', str(Size)], IsValid, 0
1672 elif PcdType in (MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT):
1673 Value = FieldList[0]
1674 Size = Type = ''
1675 if len(FieldList) > 1:
1676 Type = FieldList[1]
1677 else:
1678 Type = DataType
1679 if len(FieldList) > 2:
1680 Size = FieldList[2]
1681 else:
1682 if Type == 'VOID*':
1683 if Value.startswith("L"):
1684 Size = str((len(Value)- 3 + 1) * 2)
1685 elif Value.startswith("{"):
1686 Size = str(len(Value.split(",")))
1687 else:
1688 Size = str(len(Value) -2 + 1 )
1689 if DataType == "":
1690 IsValid = (len(FieldList) <= 1)
1691 else:
1692 IsValid = (len(FieldList) <= 3)
1693
1694 if Size:
1695 try:
1696 int(Size,16) if Size.upper().startswith("0X") else int(Size)
1697 except:
1698 IsValid = False
1699 Size = -1
1700 return [Value, Type, str(Size)], IsValid, 0
1701 elif PcdType in (MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_VPD):
1702 VpdOffset = FieldList[0]
1703 Value = Size = ''
1704 if not DataType == 'VOID*':
1705 if len(FieldList) > 1:
1706 Value = FieldList[1]
1707 else:
1708 if len(FieldList) > 1:
1709 Size = FieldList[1]
1710 if len(FieldList) > 2:
1711 Value = FieldList[2]
1712 if DataType == "":
1713 IsValid = (len(FieldList) <= 1)
1714 else:
1715 IsValid = (len(FieldList) <= 3)
1716 if Size:
1717 try:
1718 int(Size,16) if Size.upper().startswith("0X") else int(Size)
1719 except:
1720 IsValid = False
1721 Size = -1
1722 return [VpdOffset, str(Size), Value], IsValid, 2
1723 elif PcdType in (MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_HII):
1724 HiiString = FieldList[0]
1725 Guid = Offset = Value = Attribute = ''
1726 if len(FieldList) > 1:
1727 Guid = FieldList[1]
1728 if len(FieldList) > 2:
1729 Offset = FieldList[2]
1730 if len(FieldList) > 3:
1731 Value = FieldList[3]
1732 if len(FieldList) > 4:
1733 Attribute = FieldList[4]
1734 IsValid = (3 <= len(FieldList) <= 5)
1735 return [HiiString, Guid, Offset, Value, Attribute], IsValid, 3
1736 return [], False, 0
1737
1738 ## AnalyzePcdData
1739 #
1740 # Analyze the pcd Value, Datum type and TokenNumber.
1741 # Used to avoid split issue while the value string contain "|" character
1742 #
1743 # @param[in] Setting: A String contain value/datum type/token number information;
1744 #
1745 # @retval ValueList: A List contain value, datum type and toke number.
1746 #
1747 def AnalyzePcdData(Setting):
1748 ValueList = ['', '', '']
1749
1750 ValueRe = re.compile(r'^\s*L?\".*\|.*\"')
1751 PtrValue = ValueRe.findall(Setting)
1752
1753 ValueUpdateFlag = False
1754
1755 if len(PtrValue) >= 1:
1756 Setting = re.sub(ValueRe, '', Setting)
1757 ValueUpdateFlag = True
1758
1759 TokenList = Setting.split(TAB_VALUE_SPLIT)
1760 ValueList[0:len(TokenList)] = TokenList
1761
1762 if ValueUpdateFlag:
1763 ValueList[0] = PtrValue[0]
1764
1765 return ValueList
1766
1767 ## AnalyzeHiiPcdData
1768 #
1769 # Analyze the pcd Value, variable name, variable Guid and variable offset.
1770 # Used to avoid split issue while the value string contain "|" character
1771 #
1772 # @param[in] Setting: A String contain VariableName, VariableGuid, VariableOffset, DefaultValue information;
1773 #
1774 # @retval ValueList: A List contaian VariableName, VariableGuid, VariableOffset, DefaultValue.
1775 #
1776 def AnalyzeHiiPcdData(Setting):
1777 ValueList = ['', '', '', '']
1778
1779 TokenList = GetSplitValueList(Setting)
1780 ValueList[0:len(TokenList)] = TokenList
1781
1782 return ValueList
1783
1784 ## AnalyzeVpdPcdData
1785 #
1786 # Analyze the vpd pcd VpdOffset, MaxDatumSize and InitialValue.
1787 # Used to avoid split issue while the value string contain "|" character
1788 #
1789 # @param[in] Setting: A String contain VpdOffset/MaxDatumSize/InitialValue information;
1790 #
1791 # @retval ValueList: A List contain VpdOffset, MaxDatumSize and InitialValue.
1792 #
1793 def AnalyzeVpdPcdData(Setting):
1794 ValueList = ['', '', '']
1795
1796 ValueRe = re.compile(r'\s*L?\".*\|.*\"\s*$')
1797 PtrValue = ValueRe.findall(Setting)
1798
1799 ValueUpdateFlag = False
1800
1801 if len(PtrValue) >= 1:
1802 Setting = re.sub(ValueRe, '', Setting)
1803 ValueUpdateFlag = True
1804
1805 TokenList = Setting.split(TAB_VALUE_SPLIT)
1806 ValueList[0:len(TokenList)] = TokenList
1807
1808 if ValueUpdateFlag:
1809 ValueList[2] = PtrValue[0]
1810
1811 return ValueList
1812
1813 ## check format of PCD value against its the datum type
1814 #
1815 # For PCD value setting
1816 #
1817 def CheckPcdDatum(Type, Value):
1818 if Type == "VOID*":
1819 ValueRe = re.compile(r'\s*L?\".*\"\s*$')
1820 if not (((Value.startswith('L"') or Value.startswith('"')) and Value.endswith('"'))
1821 or (Value.startswith('{') and Value.endswith('}'))
1822 ):
1823 return False, "Invalid value [%s] of type [%s]; must be in the form of {...} for array"\
1824 ", or \"...\" for string, or L\"...\" for unicode string" % (Value, Type)
1825 elif ValueRe.match(Value):
1826 # Check the chars in UnicodeString or CString is printable
1827 if Value.startswith("L"):
1828 Value = Value[2:-1]
1829 else:
1830 Value = Value[1:-1]
1831 Printset = set(string.printable)
1832 Printset.remove(TAB_PRINTCHAR_VT)
1833 Printset.add(TAB_PRINTCHAR_BS)
1834 Printset.add(TAB_PRINTCHAR_NUL)
1835 if not set(Value).issubset(Printset):
1836 PrintList = list(Printset)
1837 PrintList.sort()
1838 return False, "Invalid PCD string value of type [%s]; must be printable chars %s." % (Type, PrintList)
1839 elif Type == 'BOOLEAN':
1840 if Value not in ['TRUE', 'True', 'true', '0x1', '0x01', '1', 'FALSE', 'False', 'false', '0x0', '0x00', '0']:
1841 return False, "Invalid value [%s] of type [%s]; must be one of TRUE, True, true, 0x1, 0x01, 1"\
1842 ", FALSE, False, false, 0x0, 0x00, 0" % (Value, Type)
1843 elif Type in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64]:
1844 try:
1845 Value = long(Value, 0)
1846 except:
1847 return False, "Invalid value [%s] of type [%s];"\
1848 " must be a hexadecimal, decimal or octal in C language format." % (Value, Type)
1849 else:
1850 return True, "StructurePcd"
1851
1852 return True, ""
1853
1854 ## Split command line option string to list
1855 #
1856 # subprocess.Popen needs the args to be a sequence. Otherwise there's problem
1857 # in non-windows platform to launch command
1858 #
1859 def SplitOption(OptionString):
1860 OptionList = []
1861 LastChar = " "
1862 OptionStart = 0
1863 QuotationMark = ""
1864 for Index in range(0, len(OptionString)):
1865 CurrentChar = OptionString[Index]
1866 if CurrentChar in ['"', "'"]:
1867 if QuotationMark == CurrentChar:
1868 QuotationMark = ""
1869 elif QuotationMark == "":
1870 QuotationMark = CurrentChar
1871 continue
1872 elif QuotationMark:
1873 continue
1874
1875 if CurrentChar in ["/", "-"] and LastChar in [" ", "\t", "\r", "\n"]:
1876 if Index > OptionStart:
1877 OptionList.append(OptionString[OptionStart:Index - 1])
1878 OptionStart = Index
1879 LastChar = CurrentChar
1880 OptionList.append(OptionString[OptionStart:])
1881 return OptionList
1882
1883 def CommonPath(PathList):
1884 P1 = min(PathList).split(os.path.sep)
1885 P2 = max(PathList).split(os.path.sep)
1886 for Index in xrange(min(len(P1), len(P2))):
1887 if P1[Index] != P2[Index]:
1888 return os.path.sep.join(P1[:Index])
1889 return os.path.sep.join(P1)
1890
1891 #
1892 # Convert string to C format array
1893 #
1894 def ConvertStringToByteArray(Value):
1895 Value = Value.strip()
1896 if not Value:
1897 return None
1898 if Value[0] == '{':
1899 if not Value.endswith('}'):
1900 return None
1901 Value = Value.replace(' ', '').replace('{', '').replace('}', '')
1902 ValFields = Value.split(',')
1903 try:
1904 for Index in range(len(ValFields)):
1905 ValFields[Index] = str(int(ValFields[Index], 0))
1906 except ValueError:
1907 return None
1908 Value = '{' + ','.join(ValFields) + '}'
1909 return Value
1910
1911 Unicode = False
1912 if Value.startswith('L"'):
1913 if not Value.endswith('"'):
1914 return None
1915 Value = Value[1:]
1916 Unicode = True
1917 elif not Value.startswith('"') or not Value.endswith('"'):
1918 return None
1919
1920 Value = eval(Value) # translate escape character
1921 NewValue = '{'
1922 for Index in range(0,len(Value)):
1923 if Unicode:
1924 NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ','
1925 else:
1926 NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ','
1927 Value = NewValue + '0}'
1928 return Value
1929
1930 class PathClass(object):
1931 def __init__(self, File='', Root='', AlterRoot='', Type='', IsBinary=False,
1932 Arch='COMMON', ToolChainFamily='', Target='', TagName='', ToolCode=''):
1933 self.Arch = Arch
1934 self.File = str(File)
1935 if os.path.isabs(self.File):
1936 self.Root = ''
1937 self.AlterRoot = ''
1938 else:
1939 self.Root = str(Root)
1940 self.AlterRoot = str(AlterRoot)
1941
1942 # Remove any '.' and '..' in path
1943 if self.Root:
1944 self.Root = mws.getWs(self.Root, self.File)
1945 self.Path = os.path.normpath(os.path.join(self.Root, self.File))
1946 self.Root = os.path.normpath(CommonPath([self.Root, self.Path]))
1947 # eliminate the side-effect of 'C:'
1948 if self.Root[-1] == ':':
1949 self.Root += os.path.sep
1950 # file path should not start with path separator
1951 if self.Root[-1] == os.path.sep:
1952 self.File = self.Path[len(self.Root):]
1953 else:
1954 self.File = self.Path[len(self.Root) + 1:]
1955 else:
1956 self.Path = os.path.normpath(self.File)
1957
1958 self.SubDir, self.Name = os.path.split(self.File)
1959 self.BaseName, self.Ext = os.path.splitext(self.Name)
1960
1961 if self.Root:
1962 if self.SubDir:
1963 self.Dir = os.path.join(self.Root, self.SubDir)
1964 else:
1965 self.Dir = self.Root
1966 else:
1967 self.Dir = self.SubDir
1968
1969 if IsBinary:
1970 self.Type = Type
1971 else:
1972 self.Type = self.Ext.lower()
1973
1974 self.IsBinary = IsBinary
1975 self.Target = Target
1976 self.TagName = TagName
1977 self.ToolCode = ToolCode
1978 self.ToolChainFamily = ToolChainFamily
1979
1980 self._Key = None
1981
1982 ## Convert the object of this class to a string
1983 #
1984 # Convert member Path of the class to a string
1985 #
1986 # @retval string Formatted String
1987 #
1988 def __str__(self):
1989 return self.Path
1990
1991 ## Override __eq__ function
1992 #
1993 # Check whether PathClass are the same
1994 #
1995 # @retval False The two PathClass are different
1996 # @retval True The two PathClass are the same
1997 #
1998 def __eq__(self, Other):
1999 if type(Other) == type(self):
2000 return self.Path == Other.Path
2001 else:
2002 return self.Path == str(Other)
2003
2004 ## Override __cmp__ function
2005 #
2006 # Customize the comparsion operation of two PathClass
2007 #
2008 # @retval 0 The two PathClass are different
2009 # @retval -1 The first PathClass is less than the second PathClass
2010 # @retval 1 The first PathClass is Bigger than the second PathClass
2011 def __cmp__(self, Other):
2012 if type(Other) == type(self):
2013 OtherKey = Other.Path
2014 else:
2015 OtherKey = str(Other)
2016
2017 SelfKey = self.Path
2018 if SelfKey == OtherKey:
2019 return 0
2020 elif SelfKey > OtherKey:
2021 return 1
2022 else:
2023 return -1
2024
2025 ## Override __hash__ function
2026 #
2027 # Use Path as key in hash table
2028 #
2029 # @retval string Key for hash table
2030 #
2031 def __hash__(self):
2032 return hash(self.Path)
2033
2034 def _GetFileKey(self):
2035 if self._Key == None:
2036 self._Key = self.Path.upper() # + self.ToolChainFamily + self.TagName + self.ToolCode + self.Target
2037 return self._Key
2038
2039 def _GetTimeStamp(self):
2040 return os.stat(self.Path)[8]
2041
2042 def Validate(self, Type='', CaseSensitive=True):
2043 if GlobalData.gCaseInsensitive:
2044 CaseSensitive = False
2045 if Type and Type.lower() != self.Type:
2046 return FILE_TYPE_MISMATCH, '%s (expect %s but got %s)' % (self.File, Type, self.Type)
2047
2048 RealFile, RealRoot = RealPath2(self.File, self.Root, self.AlterRoot)
2049 if not RealRoot and not RealFile:
2050 RealFile = self.File
2051 if self.AlterRoot:
2052 RealFile = os.path.join(self.AlterRoot, self.File)
2053 elif self.Root:
2054 RealFile = os.path.join(self.Root, self.File)
2055 if len (mws.getPkgPath()) == 0:
2056 return FILE_NOT_FOUND, os.path.join(self.AlterRoot, RealFile)
2057 else:
2058 return FILE_NOT_FOUND, "%s is not found in packages path:\n\t%s" % (self.File, '\n\t'.join(mws.getPkgPath()))
2059
2060 ErrorCode = 0
2061 ErrorInfo = ''
2062 if RealRoot != self.Root or RealFile != self.File:
2063 if CaseSensitive and (RealFile != self.File or (RealRoot != self.Root and RealRoot != self.AlterRoot)):
2064 ErrorCode = FILE_CASE_MISMATCH
2065 ErrorInfo = self.File + '\n\t' + RealFile + " [in file system]"
2066
2067 self.SubDir, self.Name = os.path.split(RealFile)
2068 self.BaseName, self.Ext = os.path.splitext(self.Name)
2069 if self.SubDir:
2070 self.Dir = os.path.join(RealRoot, self.SubDir)
2071 else:
2072 self.Dir = RealRoot
2073 self.File = RealFile
2074 self.Root = RealRoot
2075 self.Path = os.path.join(RealRoot, RealFile)
2076 return ErrorCode, ErrorInfo
2077
2078 Key = property(_GetFileKey)
2079 TimeStamp = property(_GetTimeStamp)
2080
2081 ## Parse PE image to get the required PE informaion.
2082 #
2083 class PeImageClass():
2084 ## Constructor
2085 #
2086 # @param File FilePath of PeImage
2087 #
2088 def __init__(self, PeFile):
2089 self.FileName = PeFile
2090 self.IsValid = False
2091 self.Size = 0
2092 self.EntryPoint = 0
2093 self.SectionAlignment = 0
2094 self.SectionHeaderList = []
2095 self.ErrorInfo = ''
2096 try:
2097 PeObject = open(PeFile, 'rb')
2098 except:
2099 self.ErrorInfo = self.FileName + ' can not be found\n'
2100 return
2101 # Read DOS header
2102 ByteArray = array.array('B')
2103 ByteArray.fromfile(PeObject, 0x3E)
2104 ByteList = ByteArray.tolist()
2105 # DOS signature should be 'MZ'
2106 if self._ByteListToStr (ByteList[0x0:0x2]) != 'MZ':
2107 self.ErrorInfo = self.FileName + ' has no valid DOS signature MZ'
2108 return
2109
2110 # Read 4 byte PE Signature
2111 PeOffset = self._ByteListToInt(ByteList[0x3C:0x3E])
2112 PeObject.seek(PeOffset)
2113 ByteArray = array.array('B')
2114 ByteArray.fromfile(PeObject, 4)
2115 # PE signature should be 'PE\0\0'
2116 if ByteArray.tostring() != 'PE\0\0':
2117 self.ErrorInfo = self.FileName + ' has no valid PE signature PE00'
2118 return
2119
2120 # Read PE file header
2121 ByteArray = array.array('B')
2122 ByteArray.fromfile(PeObject, 0x14)
2123 ByteList = ByteArray.tolist()
2124 SecNumber = self._ByteListToInt(ByteList[0x2:0x4])
2125 if SecNumber == 0:
2126 self.ErrorInfo = self.FileName + ' has no section header'
2127 return
2128
2129 # Read PE optional header
2130 OptionalHeaderSize = self._ByteListToInt(ByteArray[0x10:0x12])
2131 ByteArray = array.array('B')
2132 ByteArray.fromfile(PeObject, OptionalHeaderSize)
2133 ByteList = ByteArray.tolist()
2134 self.EntryPoint = self._ByteListToInt(ByteList[0x10:0x14])
2135 self.SectionAlignment = self._ByteListToInt(ByteList[0x20:0x24])
2136 self.Size = self._ByteListToInt(ByteList[0x38:0x3C])
2137
2138 # Read each Section Header
2139 for Index in range(SecNumber):
2140 ByteArray = array.array('B')
2141 ByteArray.fromfile(PeObject, 0x28)
2142 ByteList = ByteArray.tolist()
2143 SecName = self._ByteListToStr(ByteList[0:8])
2144 SecVirtualSize = self._ByteListToInt(ByteList[8:12])
2145 SecRawAddress = self._ByteListToInt(ByteList[20:24])
2146 SecVirtualAddress = self._ByteListToInt(ByteList[12:16])
2147 self.SectionHeaderList.append((SecName, SecVirtualAddress, SecRawAddress, SecVirtualSize))
2148 self.IsValid = True
2149 PeObject.close()
2150
2151 def _ByteListToStr(self, ByteList):
2152 String = ''
2153 for index in range(len(ByteList)):
2154 if ByteList[index] == 0:
2155 break
2156 String += chr(ByteList[index])
2157 return String
2158
2159 def _ByteListToInt(self, ByteList):
2160 Value = 0
2161 for index in range(len(ByteList) - 1, -1, -1):
2162 Value = (Value << 8) | int(ByteList[index])
2163 return Value
2164
2165 class DefaultStore():
2166 def __init__(self,DefaultStores ):
2167
2168 self.DefaultStores = DefaultStores
2169 def DefaultStoreID(self,DefaultStoreName):
2170 for key,value in self.DefaultStores.items():
2171 if value == DefaultStoreName:
2172 return key
2173 return None
2174 def GetDefaultDefault(self):
2175 if not self.DefaultStores or "0" in self.DefaultStores:
2176 return "0",TAB_DEFAULT_STORES_DEFAULT
2177 else:
2178 minvalue = min([int(value_str) for value_str in self.DefaultStores.keys()])
2179 return (str(minvalue), self.DefaultStores[str(minvalue)])
2180 def GetMin(self,DefaultSIdList):
2181 if not DefaultSIdList:
2182 return "STANDARD"
2183 storeidset = {storeid for storeid, storename in self.DefaultStores.values() if storename in DefaultSIdList}
2184 if not storeidset:
2185 return ""
2186 minid = min(storeidset )
2187 for sid,name in self.DefaultStores.values():
2188 if sid == minid:
2189 return name
2190 class SkuClass():
2191
2192 DEFAULT = 0
2193 SINGLE = 1
2194 MULTIPLE =2
2195
2196 def __init__(self,SkuIdentifier='', SkuIds=None):
2197 if SkuIds is None:
2198 SkuIds = {}
2199
2200 for SkuName in SkuIds:
2201 SkuId = SkuIds[SkuName][0]
2202 skuid_num = int(SkuId,16) if SkuId.upper().startswith("0X") else int(SkuId)
2203 if skuid_num > 0xFFFFFFFFFFFFFFFF:
2204 EdkLogger.error("build", PARAMETER_INVALID,
2205 ExtraData = "SKU-ID [%s] value %s exceeds the max value of UINT64"
2206 % (SkuName, SkuId))
2207
2208 self.AvailableSkuIds = sdict()
2209 self.SkuIdSet = []
2210 self.SkuIdNumberSet = []
2211 self.SkuData = SkuIds
2212 self.__SkuInherit = {}
2213 self.__SkuIdentifier = SkuIdentifier
2214 if SkuIdentifier == '' or SkuIdentifier is None:
2215 self.SkuIdSet = ['DEFAULT']
2216 self.SkuIdNumberSet = ['0U']
2217 elif SkuIdentifier == 'ALL':
2218 self.SkuIdSet = SkuIds.keys()
2219 self.SkuIdNumberSet = [num[0].strip() + 'U' for num in SkuIds.values()]
2220 else:
2221 r = SkuIdentifier.split('|')
2222 self.SkuIdSet=[(r[k].strip()).upper() for k in range(len(r))]
2223 k = None
2224 try:
2225 self.SkuIdNumberSet = [SkuIds[k][0].strip() + 'U' for k in self.SkuIdSet]
2226 except Exception:
2227 EdkLogger.error("build", PARAMETER_INVALID,
2228 ExtraData = "SKU-ID [%s] is not supported by the platform. [Valid SKU-ID: %s]"
2229 % (k, " | ".join(SkuIds.keys())))
2230 for each in self.SkuIdSet:
2231 if each in SkuIds:
2232 self.AvailableSkuIds[each] = SkuIds[each][0]
2233 else:
2234 EdkLogger.error("build", PARAMETER_INVALID,
2235 ExtraData="SKU-ID [%s] is not supported by the platform. [Valid SKU-ID: %s]"
2236 % (each, " | ".join(SkuIds.keys())))
2237 if self.SkuUsageType != self.SINGLE:
2238 self.AvailableSkuIds.update({'DEFAULT':0, 'COMMON':0})
2239 if self.SkuIdSet:
2240 GlobalData.gSkuids = (self.SkuIdSet)
2241 if 'COMMON' in GlobalData.gSkuids:
2242 GlobalData.gSkuids.remove('COMMON')
2243 if GlobalData.gSkuids:
2244 GlobalData.gSkuids.sort()
2245
2246 def GetNextSkuId(self, skuname):
2247 if not self.__SkuInherit:
2248 self.__SkuInherit = {}
2249 for item in self.SkuData.values():
2250 self.__SkuInherit[item[1]]=item[2] if item[2] else "DEFAULT"
2251 return self.__SkuInherit.get(skuname,"DEFAULT")
2252
2253 def GetSkuChain(self,sku):
2254 skulist = [sku]
2255 nextsku = sku
2256 while 1:
2257 nextsku = self.GetNextSkuId(nextsku)
2258 skulist.append(nextsku)
2259 if nextsku == "DEFAULT":
2260 break
2261 skulist.reverse()
2262 return skulist
2263 def SkuOverrideOrder(self):
2264 skuorderset = []
2265 for skuname in self.SkuIdSet:
2266 skuorderset.append(self.GetSkuChain(skuname))
2267
2268 skuorder = []
2269 for index in range(max([len(item) for item in skuorderset])):
2270 for subset in skuorderset:
2271 if index > len(subset)-1:
2272 continue
2273 if subset[index] in skuorder:
2274 continue
2275 skuorder.append(subset[index])
2276
2277 return skuorder
2278
2279 def __SkuUsageType(self):
2280
2281 if self.__SkuIdentifier.upper() == "ALL":
2282 return SkuClass.MULTIPLE
2283
2284 if len(self.SkuIdSet) == 1:
2285 if self.SkuIdSet[0] == 'DEFAULT':
2286 return SkuClass.DEFAULT
2287 else:
2288 return SkuClass.SINGLE
2289 elif len(self.SkuIdSet) == 2:
2290 if 'DEFAULT' in self.SkuIdSet:
2291 return SkuClass.SINGLE
2292 else:
2293 return SkuClass.MULTIPLE
2294 else:
2295 return SkuClass.MULTIPLE
2296 def DumpSkuIdArrary(self):
2297
2298 ArrayStrList = []
2299 if self.SkuUsageType == SkuClass.SINGLE:
2300 ArrayStr = "{0x0}"
2301 else:
2302 for skuname in self.AvailableSkuIds:
2303 if skuname == "COMMON":
2304 continue
2305 while skuname != "DEFAULT":
2306 ArrayStrList.append(hex(int(self.AvailableSkuIds[skuname])))
2307 skuname = self.GetNextSkuId(skuname)
2308 ArrayStrList.append("0x0")
2309 ArrayStr = "{" + ",".join(ArrayStrList) + "}"
2310 return ArrayStr
2311 def __GetAvailableSkuIds(self):
2312 return self.AvailableSkuIds
2313
2314 def __GetSystemSkuID(self):
2315 if self.__SkuUsageType() == SkuClass.SINGLE:
2316 if len(self.SkuIdSet) == 1:
2317 return self.SkuIdSet[0]
2318 else:
2319 return self.SkuIdSet[0] if self.SkuIdSet[0] != 'DEFAULT' else self.SkuIdSet[1]
2320 else:
2321 return 'DEFAULT'
2322 def __GetAvailableSkuIdNumber(self):
2323 return self.SkuIdNumberSet
2324 SystemSkuId = property(__GetSystemSkuID)
2325 AvailableSkuIdSet = property(__GetAvailableSkuIds)
2326 SkuUsageType = property(__SkuUsageType)
2327 AvailableSkuIdNumSet = property(__GetAvailableSkuIdNumber)
2328
2329 #
2330 # Pack a registry format GUID
2331 #
2332 def PackRegistryFormatGuid(Guid):
2333 Guid = Guid.split('-')
2334 return pack('=LHHBBBBBBBB',
2335 int(Guid[0], 16),
2336 int(Guid[1], 16),
2337 int(Guid[2], 16),
2338 int(Guid[3][-4:-2], 16),
2339 int(Guid[3][-2:], 16),
2340 int(Guid[4][-12:-10], 16),
2341 int(Guid[4][-10:-8], 16),
2342 int(Guid[4][-8:-6], 16),
2343 int(Guid[4][-6:-4], 16),
2344 int(Guid[4][-4:-2], 16),
2345 int(Guid[4][-2:], 16)
2346 )
2347
2348 def BuildOptionPcdValueFormat(TokenSpaceGuidCName, TokenCName, PcdDatumType, Value):
2349 if PcdDatumType == 'VOID*':
2350 if Value.startswith('L'):
2351 if not Value[1]:
2352 EdkLogger.error("build", FORMAT_INVALID, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", H"{...}"')
2353 Value = Value[0] + '"' + Value[1:] + '"'
2354 elif Value.startswith('H'):
2355 if not Value[1]:
2356 EdkLogger.error("build", FORMAT_INVALID, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", H"{...}"')
2357 Value = Value[1:]
2358 else:
2359 if not Value[0]:
2360 EdkLogger.error("build", FORMAT_INVALID, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", H"{...}"')
2361 Value = '"' + Value + '"'
2362
2363 IsValid, Cause = CheckPcdDatum(PcdDatumType, Value)
2364 if not IsValid:
2365 EdkLogger.error("build", FORMAT_INVALID, Cause, ExtraData="%s.%s" % (TokenSpaceGuidCName, TokenCName))
2366 if PcdDatumType == 'BOOLEAN':
2367 Value = Value.upper()
2368 if Value == 'TRUE' or Value == '1':
2369 Value = '1'
2370 elif Value == 'FALSE' or Value == '0':
2371 Value = '0'
2372 return Value
2373 ## Get the integer value from string like "14U" or integer like 2
2374 #
2375 # @param Input The object that may be either a integer value or a string
2376 #
2377 # @retval Value The integer value that the input represents
2378 #
2379 def GetIntegerValue(Input):
2380 if type(Input) in (int, long):
2381 return Input
2382 String = Input
2383 if String.endswith("U"):
2384 String = String[:-1]
2385 if String.endswith("ULL"):
2386 String = String[:-3]
2387 if String.endswith("LL"):
2388 String = String[:-2]
2389
2390 if String.startswith("0x") or String.startswith("0X"):
2391 return int(String, 16)
2392 elif String == '':
2393 return 0
2394 else:
2395 return int(String)
2396
2397 ##
2398 #
2399 # This acts like the main() function for the script, unless it is 'import'ed into another
2400 # script.
2401 #
2402 if __name__ == '__main__':
2403 pass
2404