]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Common/String.py
2 # This file is used to define common string related functions used in parsing process
4 # Copyright (c) 2007 - 2015, 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
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.
19 import Common
.LongFilePathOs
as os
21 import EdkLogger
as EdkLogger
24 from BuildToolError
import *
25 from CommonDataClass
.Exceptions
import *
26 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
27 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
29 gHexVerPatt
= re
.compile('0x[a-f0-9]{4}[a-f0-9]{4}$', re
.IGNORECASE
)
30 gHumanReadableVerPatt
= re
.compile(r
'([1-9][0-9]*|0)\.[0-9]{1,2}$')
34 # Get a value list from a string with multiple values splited with SplitTag
35 # The default SplitTag is DataType.TAB_VALUE_SPLIT
36 # 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']
38 # @param String: The input string to be splitted
39 # @param SplitTag: The split key, default is DataType.TAB_VALUE_SPLIT
40 # @param MaxSplit: The max number of split values, default is -1
42 # @retval list() A list for splitted string
44 def GetSplitValueList(String
, SplitTag
=DataType
.TAB_VALUE_SPLIT
, MaxSplit
= -1):
50 for Index
in range(0, len(String
)):
54 # Found a splitter not in a string, split it
55 if not InString
and InParenthesis
== 0 and Char
== SplitTag
:
56 ValueList
.append(String
[Last
:Index
].strip())
58 if MaxSplit
> 0 and len(ValueList
) >= MaxSplit
:
61 if Char
== '\\' and InString
:
69 InParenthesis
= InParenthesis
+ 1
71 InParenthesis
= InParenthesis
- 1
75 if Last
< len(String
):
76 ValueList
.append(String
[Last
:].strip())
77 elif Last
== len(String
):
84 # Get a value list from a string with multiple values splited with SplitString
85 # The default SplitTag is DataType.TAB_VALUE_SPLIT
86 # 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']
88 # @param String: The input string to be splitted
89 # @param SplitStr: The split key, default is DataType.TAB_VALUE_SPLIT
90 # @param MaxSplit: The max number of split values, default is -1
92 # @retval list() A list for splitted string
94 def GetSplitList(String
, SplitStr
=DataType
.TAB_VALUE_SPLIT
, MaxSplit
= -1):
95 return map(lambda l
: l
.strip(), String
.split(SplitStr
, MaxSplit
))
99 # Find a key's all arches in dict, add the new arch to the list
100 # If not exist any arch, set the arch directly
102 # @param Dict: The input value for Dict
103 # @param Key: The input value for Key
104 # @param Arch: The Arch to be added or merged
106 def MergeArches(Dict
, Key
, Arch
):
107 if Key
in Dict
.keys():
108 Dict
[Key
].append(Arch
)
110 Dict
[Key
] = Arch
.split()
114 # Parse a string with format "DEFINE <VarName> = <PATH>"
115 # Generate a map Defines[VarName] = PATH
116 # Return False if invalid format
118 # @param String: String with DEFINE statement
119 # @param Arch: Supportted Arch
120 # @param Defines: DEFINE statement to be parsed
122 # @retval 0 DEFINE statement found, and valid
123 # @retval 1 DEFINE statement found, but not valid
124 # @retval -1 DEFINE statement not found
126 def GenDefines(String
, Arch
, Defines
):
127 if String
.find(DataType
.TAB_DEFINE
+ ' ') > -1:
128 List
= String
.replace(DataType
.TAB_DEFINE
+ ' ', '').split(DataType
.TAB_EQUAL_SPLIT
)
130 Defines
[(CleanString(List
[0]), Arch
)] = CleanString(List
[1])
139 # Parse a string with format "!include <Filename>"
140 # Return the file path
141 # Return False if invalid format or NOT FOUND
143 # @param String: String with INCLUDE statement
144 # @param IncludeFiles: INCLUDE statement to be parsed
145 # @param Arch: Supportted Arch
150 def GenInclude(String
, IncludeFiles
, Arch
):
151 if String
.upper().find(DataType
.TAB_INCLUDE
.upper() + ' ') > -1:
152 IncludeFile
= CleanString(String
[String
.upper().find(DataType
.TAB_INCLUDE
.upper() + ' ') + len(DataType
.TAB_INCLUDE
+ ' ') : ])
153 MergeArches(IncludeFiles
, IncludeFile
, Arch
)
158 ## GetLibraryClassesWithModuleType
160 # Get Library Class definition when no module type defined
162 # @param Lines: The content to be parsed
163 # @param Key: Reserved
164 # @param KeyValues: To store data after parsing
165 # @param CommentCharacter: Comment char, used to ignore comment content
167 # @retval True Get library classes successfully
169 def GetLibraryClassesWithModuleType(Lines
, Key
, KeyValues
, CommentCharacter
):
170 newKey
= SplitModuleType(Key
)
171 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
172 LineList
= Lines
.splitlines()
173 for Line
in LineList
:
174 Line
= CleanString(Line
, CommentCharacter
)
175 if Line
!= '' and Line
[0] != CommentCharacter
:
176 KeyValues
.append([CleanString(Line
, CommentCharacter
), newKey
[1]])
184 # @param Lines: The content to be parsed
185 # @param Key: Reserved
186 # @param KeyValues: To store data after parsing
187 # @param CommentCharacter: Comment char, used to ignore comment content
189 # @retval True Get Dynamic Pcds successfully
191 def GetDynamics(Lines
, Key
, KeyValues
, CommentCharacter
):
193 # Get SkuId Name List
195 SkuIdNameList
= SplitModuleType(Key
)
197 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
198 LineList
= Lines
.splitlines()
199 for Line
in LineList
:
200 Line
= CleanString(Line
, CommentCharacter
)
201 if Line
!= '' and Line
[0] != CommentCharacter
:
202 KeyValues
.append([CleanString(Line
, CommentCharacter
), SkuIdNameList
[1]])
208 # Split ModuleType out of section defien to get key
209 # [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [ 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]
211 # @param Key: String to be parsed
213 # @retval ReturnValue A list for module types
215 def SplitModuleType(Key
):
216 KeyList
= Key
.split(DataType
.TAB_SPLIT
)
222 # Fill in for moduletype
226 KeyValue
= KeyList
[0]
228 KeyValue
= KeyValue
+ DataType
.TAB_SPLIT
+ KeyList
[1]
229 ReturnValue
.append(KeyValue
)
230 ReturnValue
.append(GetSplitValueList(KeyList
[2]))
234 ## Replace macro in strings list
236 # This method replace macros used in a given string list. The macros are
237 # given in a dictionary.
239 # @param StringList StringList to be processed
240 # @param MacroDefinitions The macro definitions in the form of dictionary
241 # @param SelfReplacement To decide whether replace un-defined macro to ''
243 # @retval NewList A new string list whose macros are replaced
245 def ReplaceMacros(StringList
, MacroDefinitions
={}, SelfReplacement
=False):
247 for String
in StringList
:
248 if type(String
) == type(''):
249 NewList
.append(ReplaceMacro(String
, MacroDefinitions
, SelfReplacement
))
251 NewList
.append(String
)
255 ## Replace macro in string
257 # This method replace macros used in given string. The macros are given in a
260 # @param String String to be processed
261 # @param MacroDefinitions The macro definitions in the form of dictionary
262 # @param SelfReplacement To decide whether replace un-defined macro to ''
264 # @retval string The string whose macros are replaced
266 def ReplaceMacro(String
, MacroDefinitions
={}, SelfReplacement
=False, RaiseError
=False):
268 while String
and MacroDefinitions
:
269 MacroUsed
= GlobalData
.gMacroRefPattern
.findall(String
)
270 # no macro found in String, stop replacing
271 if len(MacroUsed
) == 0:
274 for Macro
in MacroUsed
:
275 if Macro
not in MacroDefinitions
:
277 raise SymbolNotFound("%s not defined" % Macro
)
279 String
= String
.replace("$(%s)" % Macro
, '')
281 if "$(%s)" % Macro
not in MacroDefinitions
[Macro
]:
282 String
= String
.replace("$(%s)" % Macro
, MacroDefinitions
[Macro
])
283 # in case there's macro not defined
284 if String
== LastString
:
292 # Create a normal path
293 # And replace DFEINE in the path
295 # @param Path: The input value for Path to be converted
296 # @param Defines: A set for DEFINE statement
298 # @retval Path Formatted path
300 def NormPath(Path
, Defines
={}):
301 IsRelativePath
= False
304 IsRelativePath
= True
306 # Replace with Define
309 Path
= ReplaceMacro(Path
, Defines
)
311 # To local path format
313 Path
= os
.path
.normpath(Path
)
314 if Path
.startswith(GlobalData
.gWorkspace
) and not Path
.startswith(GlobalData
.gBuildDirectory
) and not os
.path
.exists(Path
):
315 Path
= Path
[len (GlobalData
.gWorkspace
):]
316 if Path
[0] == os
.path
.sep
:
318 Path
= mws
.join(GlobalData
.gWorkspace
, Path
)
320 if IsRelativePath
and Path
[0] != '.':
321 Path
= os
.path
.join('.', Path
)
327 # Remove comments in a string
330 # @param Line: The string to be cleaned
331 # @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT
333 # @retval Path Formatted path
335 def CleanString(Line
, CommentCharacter
=DataType
.TAB_COMMENT_SPLIT
, AllowCppStyleComment
=False, BuildOption
=False):
341 # Replace Edk's comment character
343 if AllowCppStyleComment
:
344 Line
= Line
.replace(DataType
.TAB_COMMENT_EDK_SPLIT
, CommentCharacter
)
346 # remove comments, but we should escape comment character in string
349 CommentInString
= False
350 for Index
in range(0, len(Line
)):
351 if Line
[Index
] == '"':
352 InString
= not InString
353 elif Line
[Index
] == CommentCharacter
and InString
:
354 CommentInString
= True
355 elif Line
[Index
] == CommentCharacter
and not InString
:
356 Line
= Line
[0: Index
]
359 if CommentInString
and BuildOption
:
360 Line
= Line
.replace('"', '')
361 ChIndex
= Line
.find('#')
363 if GlobalData
.gIsWindows
:
364 if ChIndex
== 0 or Line
[ChIndex
- 1] != '^':
365 Line
= Line
[0:ChIndex
] + '^' + Line
[ChIndex
:]
366 ChIndex
= Line
.find('#', ChIndex
+ 2)
368 ChIndex
= Line
.find('#', ChIndex
+ 1)
370 if ChIndex
== 0 or Line
[ChIndex
- 1] != '\\':
371 Line
= Line
[0:ChIndex
] + '\\' + Line
[ChIndex
:]
372 ChIndex
= Line
.find('#', ChIndex
+ 2)
374 ChIndex
= Line
.find('#', ChIndex
+ 1)
376 # remove whitespace again
384 # Split statement with comments in a string
387 # @param Line: The string to be cleaned
388 # @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT
390 # @retval Path Formatted path
392 def CleanString2(Line
, CommentCharacter
=DataType
.TAB_COMMENT_SPLIT
, AllowCppStyleComment
=False):
398 # Replace Edk's comment character
400 if AllowCppStyleComment
:
401 Line
= Line
.replace(DataType
.TAB_COMMENT_EDK_SPLIT
, CommentCharacter
)
403 # separate comments and statements, but we should escape comment character in string
406 CommentInString
= False
408 for Index
in range(0, len(Line
)):
409 if Line
[Index
] == '"':
410 InString
= not InString
411 elif Line
[Index
] == CommentCharacter
and InString
:
412 CommentInString
= True
413 elif Line
[Index
] == CommentCharacter
and not InString
:
414 Comment
= Line
[Index
:].strip()
415 Line
= Line
[0:Index
].strip()
420 ## GetMultipleValuesOfKeyFromLines
422 # Parse multiple strings to clean comment and spaces
423 # The result is saved to KeyValues
425 # @param Lines: The content to be parsed
426 # @param Key: Reserved
427 # @param KeyValues: To store data after parsing
428 # @param CommentCharacter: Comment char, used to ignore comment content
430 # @retval True Successfully executed
432 def GetMultipleValuesOfKeyFromLines(Lines
, Key
, KeyValues
, CommentCharacter
):
433 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
434 LineList
= Lines
.split('\n')
435 for Line
in LineList
:
436 Line
= CleanString(Line
, CommentCharacter
)
437 if Line
!= '' and Line
[0] != CommentCharacter
:
444 # Parse a DEFINE statement to get defined value
447 # @param String: The content to be parsed
448 # @param Key: The key of DEFINE statement
449 # @param CommentCharacter: Comment char, used to ignore comment content
451 # @retval string The defined value
453 def GetDefineValue(String
, Key
, CommentCharacter
):
454 String
= CleanString(String
)
455 return String
[String
.find(Key
+ ' ') + len(Key
+ ' ') : ]
459 # Get a Hex Version Value
461 # @param VerString: The version string to be parsed
464 # @retval: If VerString is incorrectly formatted, return "None" which will break the build.
465 # If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)
466 # where mmmm is the major number and nnnn is the adjusted minor number.
468 def GetHexVerValue(VerString
):
469 VerString
= CleanString(VerString
)
471 if gHumanReadableVerPatt
.match(VerString
):
472 ValueList
= VerString
.split('.')
477 DeciValue
= (int(Major
) << 16) + int(Minor
);
478 return "0x%08x" % DeciValue
479 elif gHexVerPatt
.match(VerString
):
485 ## GetSingleValueOfKeyFromLines
487 # Parse multiple strings as below to get value of each definition line
490 # The result is saved to Dictionary
492 # @param Lines: The content to be parsed
493 # @param Dictionary: To store data after parsing
494 # @param CommentCharacter: Comment char, be used to ignore comment content
495 # @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
496 # @param ValueSplitFlag: Value split flag, be used to decide if has multiple values
497 # @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
499 # @retval True Successfully executed
501 def GetSingleValueOfKeyFromLines(Lines
, Dictionary
, CommentCharacter
, KeySplitCharacter
, ValueSplitFlag
, ValueSplitCharacter
):
502 Lines
= Lines
.split('\n')
510 # Handle DEFINE and SPEC
512 if Line
.find(DataType
.TAB_INF_DEFINES_DEFINE
+ ' ') > -1:
513 if '' in DefineValues
:
514 DefineValues
.remove('')
515 DefineValues
.append(GetDefineValue(Line
, DataType
.TAB_INF_DEFINES_DEFINE
, CommentCharacter
))
517 if Line
.find(DataType
.TAB_INF_DEFINES_SPEC
+ ' ') > -1:
519 SpecValues
.remove('')
520 SpecValues
.append(GetDefineValue(Line
, DataType
.TAB_INF_DEFINES_SPEC
, CommentCharacter
))
526 LineList
= Line
.split(KeySplitCharacter
, 1)
527 if len(LineList
) >= 2:
528 Key
= LineList
[0].split()
529 if len(Key
) == 1 and Key
[0][0] != CommentCharacter
:
531 # Remove comments and white spaces
533 LineList
[1] = CleanString(LineList
[1], CommentCharacter
)
535 Value
= map(string
.strip
, LineList
[1].split(ValueSplitCharacter
))
537 Value
= CleanString(LineList
[1], CommentCharacter
).splitlines()
539 if Key
[0] in Dictionary
:
540 if Key
[0] not in Keys
:
541 Dictionary
[Key
[0]] = Value
544 Dictionary
[Key
[0]].extend(Value
)
546 Dictionary
[DataType
.TAB_INF_DEFINES_MACRO
][Key
[0]] = Value
[0]
548 if DefineValues
== []:
552 Dictionary
[DataType
.TAB_INF_DEFINES_DEFINE
] = DefineValues
553 Dictionary
[DataType
.TAB_INF_DEFINES_SPEC
] = SpecValues
557 ## The content to be parsed
559 # Do pre-check for a file before it is parsed
563 # @param FileName: Used for error report
564 # @param FileContent: File content to be parsed
565 # @param SupSectionTag: Used for error report
567 def PreCheck(FileName
, FileContent
, SupSectionTag
):
571 for Line
in FileContent
.splitlines():
576 Line
= CleanString(Line
)
579 # Remove commented line
581 if Line
.find(DataType
.TAB_COMMA_SPLIT
) == 0:
586 if Line
.find('$') > -1:
587 if Line
.find('$(') < 0 or Line
.find(')') < 0:
588 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
593 if Line
.find('[') > -1 or Line
.find(']') > -1:
595 # Only get one '[' or one ']'
597 if not (Line
.find('[') > -1 and Line
.find(']') > -1):
598 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
601 # Regenerate FileContent
603 NewFileContent
= NewFileContent
+ Line
+ '\r\n'
606 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
608 return NewFileContent
612 # Check if the Filename is including ExtName
613 # Return True if it exists
614 # Raise a error message if it not exists
616 # @param CheckFilename: Name of the file to be checked
617 # @param ExtName: Ext name of the file to be checked
618 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
619 # @param SectionName: Used for error report
620 # @param Line: The line in container file which defines the file to be checked
622 # @retval True The file type is correct
624 def CheckFileType(CheckFilename
, ExtName
, ContainerFilename
, SectionName
, Line
, LineNo
= -1):
625 if CheckFilename
!= '' and CheckFilename
!= None:
626 (Root
, Ext
) = os
.path
.splitext(CheckFilename
)
627 if Ext
.upper() != ExtName
.upper():
628 ContainerFile
= open(ContainerFilename
, 'r').read()
630 LineNo
= GetLineNo(ContainerFile
, Line
)
631 ErrorMsg
= "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName
, CheckFilename
, ExtName
)
632 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
, Line
=LineNo
,
633 File
=ContainerFilename
, RaiseError
=EdkLogger
.IsRaiseError
)
639 # Check if the file exists
640 # Return True if it exists
641 # Raise a error message if it not exists
643 # @param CheckFilename: Name of the file to be checked
644 # @param WorkspaceDir: Current workspace dir
645 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
646 # @param SectionName: Used for error report
647 # @param Line: The line in container file which defines the file to be checked
649 # @retval The file full path if the file exists
651 def CheckFileExist(WorkspaceDir
, CheckFilename
, ContainerFilename
, SectionName
, Line
, LineNo
= -1):
653 if CheckFilename
!= '' and CheckFilename
!= None:
654 CheckFile
= WorkspaceFile(WorkspaceDir
, CheckFilename
)
655 if not os
.path
.isfile(CheckFile
):
656 ContainerFile
= open(ContainerFilename
, 'r').read()
658 LineNo
= GetLineNo(ContainerFile
, Line
)
659 ErrorMsg
= "Can't find file '%s' defined in section '%s'" % (CheckFile
, SectionName
)
660 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
,
661 File
=ContainerFilename
, Line
=LineNo
, RaiseError
=EdkLogger
.IsRaiseError
)
667 # Find the index of a line in a file
669 # @param FileContent: Search scope
670 # @param Line: Search key
672 # @retval int Index of the line
673 # @retval -1 The line is not found
675 def GetLineNo(FileContent
, Line
, IsIgnoreComment
=True):
676 LineList
= FileContent
.splitlines()
677 for Index
in range(len(LineList
)):
678 if LineList
[Index
].find(Line
) > -1:
680 # Ignore statement in comment
683 if LineList
[Index
].strip()[0] == DataType
.TAB_COMMENT_SPLIT
:
691 # Raise a parser error
693 # @param Line: String which has error
694 # @param Section: Used for error report
695 # @param File: File which has the string
696 # @param Format: Correct format
698 def RaiseParserError(Line
, Section
, File
, Format
='', LineNo
= -1):
700 LineNo
= GetLineNo(open(os
.path
.normpath(File
), 'r').read(), Line
)
701 ErrorMsg
= "Invalid statement '%s' is found in section '%s'" % (Line
, Section
)
703 Format
= "Correct format is " + Format
704 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
, File
=File
, Line
=LineNo
, ExtraData
=Format
, RaiseError
=EdkLogger
.IsRaiseError
)
708 # Return a full path with workspace dir
710 # @param WorkspaceDir: Workspace dir
711 # @param Filename: Relative file name
713 # @retval string A full path
715 def WorkspaceFile(WorkspaceDir
, Filename
):
716 return mws
.join(NormPath(WorkspaceDir
), NormPath(Filename
))
720 # Revmove '"' which startswith and endswith string
722 # @param String: The string need to be splited
724 # @retval String: The string after removed '""'
726 def SplitString(String
):
727 if String
.startswith('\"'):
729 if String
.endswith('\"'):
734 ## Convert To Sql String
736 # 1. Replace "'" with "''" in each item of StringList
738 # @param StringList: A list for strings to be converted
740 def ConvertToSqlString(StringList
):
741 return map(lambda s
: s
.replace("'", "''") , StringList
)
743 ## Convert To Sql String
745 # 1. Replace "'" with "''" in the String
747 # @param String: A String to be converted
749 def ConvertToSqlString2(String
):
750 return String
.replace("'", "''")
753 # Remove comment block
755 def RemoveBlockComment(Lines
):
756 IsFindBlockComment
= False
757 IsFindBlockCode
= False
764 # Remove comment block
766 if Line
.find(DataType
.TAB_COMMENT_EDK_START
) > -1:
767 ReservedLine
= GetSplitList(Line
, DataType
.TAB_COMMENT_EDK_START
, 1)[0]
768 IsFindBlockComment
= True
769 if Line
.find(DataType
.TAB_COMMENT_EDK_END
) > -1:
770 Line
= ReservedLine
+ GetSplitList(Line
, DataType
.TAB_COMMENT_EDK_END
, 1)[1]
772 IsFindBlockComment
= False
773 if IsFindBlockComment
:
777 NewLines
.append(Line
)
781 # Get String of a List
783 def GetStringOfList(List
, Split
=' '):
784 if type(List
) != type([]):
788 Str
= Str
+ Item
+ Split
793 # Get HelpTextList from HelpTextClassList
795 def GetHelpTextList(HelpTextClassList
):
797 if HelpTextClassList
:
798 for HelpText
in HelpTextClassList
:
799 if HelpText
.String
.endswith('\n'):
800 HelpText
.String
= HelpText
.String
[0: len(HelpText
.String
) - len('\n')]
801 List
.extend(HelpText
.String
.split('\n'))
805 def StringToArray(String
):
806 if isinstance(String
, unicode):
807 if len(unicode) == 0:
808 return "{0x00, 0x00}"
809 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C
) for C
in String
])
810 elif String
.startswith('L"'):
811 if String
== "L\"\"":
812 return "{0x00, 0x00}"
814 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C
) for C
in String
[2:-1]])
815 elif String
.startswith('"'):
819 StringLen
= len(String
[1:-1])
821 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C
) for C
in String
[1:-1]])
823 return "{%s, 0x00,0x00}" % ", ".join(["0x%02x" % ord(C
) for C
in String
[1:-1]])
824 elif String
.startswith('{'):
825 StringLen
= len(String
.split(","))
827 return "{%s, 0x00}" % ", ".join([ C
for C
in String
[1:-1].split(',')])
829 return "{%s}" % ", ".join([ C
for C
in String
[1:-1].split(',')])
832 if len(String
.split()) % 2:
833 return '{%s, 0}' % ', '.join(String
.split())
835 return '{%s, 0,0}' % ', '.join(String
.split())
837 def StringArrayLength(String
):
838 if isinstance(String
, unicode):
839 return (len(String
) + 1) * 2 + 1;
840 elif String
.startswith('L"'):
841 return (len(String
) - 3 + 1) * 2
842 elif String
.startswith('"'):
843 return (len(String
) - 2 + 1)
845 return len(String
.split()) + 1
847 def RemoveDupOption(OptionString
, Which
="/I", Against
=None):
848 OptionList
= OptionString
.split()
852 for Index
in range(len(OptionList
)):
853 Opt
= OptionList
[Index
]
854 if not Opt
.startswith(Which
):
856 if len(Opt
) > len(Which
):
857 Val
= Opt
[len(Which
):]
861 OptionList
[Index
] = ""
863 ValueList
.append(Val
)
864 return " ".join(OptionList
)
868 # This acts like the main() function for the script, unless it is 'import'ed into another
871 if __name__
== '__main__':