1 # Copyright (c) 2007, Intel Corporation
2 # All rights reserved. This program and the accompanying materials
3 # are licensed and made available under the terms and conditions of the BSD License
4 # which accompanies this distribution. The full text of the license may be found at
5 # http://opensource.org/licenses/bsd-license.php
7 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
8 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 #This file is used to parse a strings file and create or add to a string database file.
18 import Common
.EdkLogger
as EdkLogger
19 from Common
.BuildToolError
import *
20 from UniClassObject
import *
21 from StringIO
import StringIO
22 from struct
import pack
27 EFI_HII_SIBT_END
= '0x00'
28 EFI_HII_SIBT_STRING_SCSU
= '0x10'
29 EFI_HII_SIBT_STRING_SCSU_FONT
= '0x11'
30 EFI_HII_SIBT_STRINGS_SCSU
= '0x12'
31 EFI_HII_SIBT_STRINGS_SCSU_FONT
= '0x13'
32 EFI_HII_SIBT_STRING_UCS2
= '0x14'
33 EFI_HII_SIBT_STRING_UCS2_FONT
= '0x15'
34 EFI_HII_SIBT_STRINGS_UCS2
= '0x16'
35 EFI_HII_SIBT_STRINGS_UCS2_FONT
= '0x17'
36 EFI_HII_SIBT_DUPLICATE
= '0x20'
37 EFI_HII_SIBT_SKIP2
= '0x21'
38 EFI_HII_SIBT_SKIP1
= '0x22'
39 EFI_HII_SIBT_EXT1
= '0x30'
40 EFI_HII_SIBT_EXT2
= '0x31'
41 EFI_HII_SIBT_EXT4
= '0x32'
42 EFI_HII_SIBT_FONT
= '0x40'
44 EFI_HII_PACKAGE_STRINGS
= '0x04'
45 EFI_HII_PACKAGE_FORM
= '0x02'
47 StringPackageType
= EFI_HII_PACKAGE_STRINGS
48 StringPackageForm
= EFI_HII_PACKAGE_FORM
49 StringBlockType
= EFI_HII_SIBT_STRING_UCS2
50 StringSkipType
= EFI_HII_SIBT_SKIP2
55 DEFINE_STR
= '#define'
56 COMMENT_DEFINE_STR
= COMMENT
+ DEFINE_STR
57 NOT_REFERENCED
= 'not referenced'
58 COMMENT_NOT_REFERENCED
= ' ' + COMMENT
+ NOT_REFERENCED
59 CHAR_ARRAY_DEFIN
= 'unsigned char'
60 COMMON_FILE_NAME
= 'Strings'
64 STRING_TOKEN
= re
.compile('STRING_TOKEN *\(([A-Z0-9_]+) *\)', re
.MULTILINE | re
.UNICODE
)
65 COMPATIBLE_STRING_TOKEN
= re
.compile('STRING_TOKEN *\(([A-Za-z0-9_]+) *\)', re
.MULTILINE | re
.UNICODE
)
67 EFI_HII_ARRAY_SIZE_LENGTH
= 4
68 EFI_HII_PACKAGE_HEADER_LENGTH
= 4
69 EFI_HII_HDR_SIZE_LENGTH
= 4
70 EFI_HII_STRING_OFFSET_LENGTH
= 4
72 EFI_STRING_ID_LENGTH
= 2
73 EFI_HII_LANGUAGE_WINDOW
= 0
74 EFI_HII_LANGUAGE_WINDOW_LENGTH
= 2
75 EFI_HII_LANGUAGE_WINDOW_NUMBER
= 16
76 EFI_HII_STRING_PACKAGE_HDR_LENGTH
= EFI_HII_PACKAGE_HEADER_LENGTH
+ EFI_HII_HDR_SIZE_LENGTH
+ EFI_HII_STRING_OFFSET_LENGTH
+ EFI_HII_LANGUAGE_WINDOW_LENGTH
* EFI_HII_LANGUAGE_WINDOW_NUMBER
+ EFI_STRING_ID_LENGTH
78 H_C_FILE_HEADER
= ['//', \
79 '// DO NOT EDIT -- auto-generated file', \
81 '// This file is generated by the StrGather utility', \
83 LANGUAGE_NAME_STRING_NAME
= '$LANGUAGE_NAME'
84 PRINTABLE_LANGUAGE_NAME_STRING_NAME
= '$PRINTABLE_LANGUAGE_NAME'
86 ## Convert a dec number to a hex string
88 # Convert a dec number to a formatted hex string in length digit
89 # The digit is set to default 8
90 # The hex string starts with "0x"
91 # DecToHexStr(1000) is '0x000003E8'
92 # DecToHexStr(1000, 6) is '0x0003E8'
94 # @param Dec: The number in dec format
95 # @param Digit: The needed digit of hex string
97 # @retval: The formatted hex string
99 def DecToHexStr(Dec
, Digit
= 8):
100 return eval("'0x%0" + str(Digit
) + "X' % int(Dec)")
102 ## Convert a dec number to a hex list
104 # Convert a dec number to a formatted hex list in size digit
105 # The digit is set to default 8
106 # DecToHexList(1000) is ['0xE8', '0x03', '0x00', '0x00']
107 # DecToHexList(1000, 6) is ['0xE8', '0x03', '0x00']
109 # @param Dec: The number in dec format
110 # @param Digit: The needed digit of hex list
112 # @retval: A list for formatted hex string
114 def DecToHexList(Dec
, Digit
= 8):
115 Hex
= eval("'%0" + str(Digit
) + "X' % int(Dec)" )
117 for Bit
in range(Digit
- 2, -1, -2):
118 List
.append(HexHeader
+ Hex
[Bit
:Bit
+ 2])
121 ## Convert a acsii string to a hex list
123 # Convert a acsii string to a formatted hex list
124 # AscToHexList('en-US') is ['0x65', '0x6E', '0x2D', '0x55', '0x53']
126 # @param Ascii: The acsii string
128 # @retval: A list for formatted hex string
130 def AscToHexList(Ascii
):
133 List
.append('0x%2X' % ord(Item
))
137 ## Create header of .h file
139 # Create a header of .h file
141 # @param BaseName: The basename of strings
143 # @retval Str: A string for .h file header
145 def CreateHFileHeader(BaseName
):
147 for Item
in H_C_FILE_HEADER
:
148 Str
= WriteLine(Str
, Item
)
149 Str
= WriteLine(Str
, '#ifndef _' + BaseName
.upper() + '_STRINGS_DEFINE_H_')
150 Str
= WriteLine(Str
, '#define _' + BaseName
.upper() + '_STRINGS_DEFINE_H_')
153 ## Create content of .h file
155 # Create content of .h file
157 # @param BaseName: The basename of strings
158 # @param UniObjectClass A UniObjectClass instance
159 # @param IsCompatibleMode Compatible mode
160 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
162 # @retval Str: A string of .h file content
164 def CreateHFileContent(BaseName
, UniObjectClass
, IsCompatibleMode
, UniGenCFlag
):
167 Line
= COMMENT_DEFINE_STR
+ ' ' + LANGUAGE_NAME_STRING_NAME
+ ' ' * (ValueStartPtr
- len(DEFINE_STR
+ LANGUAGE_NAME_STRING_NAME
)) + DecToHexStr(0, 4) + COMMENT_NOT_REFERENCED
168 Str
= WriteLine(Str
, Line
)
169 Line
= COMMENT_DEFINE_STR
+ ' ' + PRINTABLE_LANGUAGE_NAME_STRING_NAME
+ ' ' * (ValueStartPtr
- len(DEFINE_STR
+ PRINTABLE_LANGUAGE_NAME_STRING_NAME
)) + DecToHexStr(1, 4) + COMMENT_NOT_REFERENCED
170 Str
= WriteLine(Str
, Line
)
171 for Index
in range(2, len(UniObjectClass
.OrderedStringList
[UniObjectClass
.LanguageDef
[0][0]])):
172 StringItem
= UniObjectClass
.OrderedStringList
[UniObjectClass
.LanguageDef
[0][0]][Index
]
173 Name
= StringItem
.StringName
174 Token
= StringItem
.Token
175 Referenced
= StringItem
.Referenced
178 if Referenced
== True:
179 if (ValueStartPtr
- len(DEFINE_STR
+ Name
)) <= 0:
180 Line
= DEFINE_STR
+ ' ' + Name
+ ' ' + DecToHexStr(Token
, 4)
182 Line
= DEFINE_STR
+ ' ' + Name
+ ' ' * (ValueStartPtr
- len(DEFINE_STR
+ Name
)) + DecToHexStr(Token
, 4)
184 if (ValueStartPtr
- len(DEFINE_STR
+ Name
)) <= 0:
185 Line
= COMMENT_DEFINE_STR
+ ' ' + Name
+ ' ' + DecToHexStr(Token
, 4) + COMMENT_NOT_REFERENCED
187 Line
= COMMENT_DEFINE_STR
+ ' ' + Name
+ ' ' * (ValueStartPtr
- len(DEFINE_STR
+ Name
)) + DecToHexStr(Token
, 4) + COMMENT_NOT_REFERENCED
188 Str
= WriteLine(Str
, Line
)
190 Str
= WriteLine(Str
, '')
191 if IsCompatibleMode
or UniGenCFlag
:
192 Str
= WriteLine(Str
, 'extern unsigned char ' + BaseName
+ 'Strings[];')
195 ## Create a complete .h file
197 # Create a complet .h file with file header and file content
199 # @param BaseName: The basename of strings
200 # @param UniObjectClass A UniObjectClass instance
201 # @param IsCompatibleMode Compatible mode
202 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
204 # @retval Str: A string of complete .h file
206 def CreateHFile(BaseName
, UniObjectClass
, IsCompatibleMode
, UniGenCFlag
):
207 HFile
= WriteLine('', CreateHFileContent(BaseName
, UniObjectClass
, IsCompatibleMode
, UniGenCFlag
))
211 ## Create header of .c file
213 # Create a header of .c file
215 # @retval Str: A string for .c file header
217 def CreateCFileHeader():
219 for Item
in H_C_FILE_HEADER
:
220 Str
= WriteLine(Str
, Item
)
224 ## Create a buffer to store all items in an array
226 # @param BinBuffer Buffer to contain Binary data.
227 # @param Array: The array need to be formatted
229 def CreateBinBuffer(BinBuffer
, Array
):
231 BinBuffer
.write(pack("B", int(Item
,16)))
233 ## Create a formatted string all items in an array
235 # Use ',' to join each item in an array, and break an new line when reaching the width (default is 16)
237 # @param Array: The array need to be formatted
238 # @param Width: The line length, the default value is set to 16
240 # @retval ArrayItem: A string for all formatted array items
242 def CreateArrayItem(Array
, Width
= 16):
249 if Index
< MaxLength
:
250 Line
= Line
+ Item
+ ', '
253 ArrayItem
= WriteLine(ArrayItem
, Line
)
254 Line
= ' ' + Item
+ ', '
256 ArrayItem
= Write(ArrayItem
, Line
.rstrip())
260 ## CreateCFileStringValue
262 # Create a line with string value
264 # @param Value: Value of the string
266 # @retval Str: A formatted string with string value
269 def CreateCFileStringValue(Value
):
270 Value
= [StringBlockType
] + Value
271 Str
= WriteLine('', CreateArrayItem(Value
))
276 ## Create content of .c file
278 # Create content of .c file
280 # @param BaseName: The basename of strings
281 # @param UniObjectClass A UniObjectClass instance
282 # @param IsCompatibleMode Compatible mode
283 # @param UniBinBuffer UniBinBuffer to contain UniBinary data.
285 # @retval Str: A string of .c file content
287 def CreateCFileContent(BaseName
, UniObjectClass
, IsCompatibleMode
, UniBinBuffer
=None):
291 TotalLength
= EFI_HII_ARRAY_SIZE_LENGTH
296 # Create lines for each language's strings
298 for IndexI
in range(len(UniObjectClass
.LanguageDef
)):
299 Language
= UniObjectClass
.LanguageDef
[IndexI
][0]
300 LangPrintName
= UniObjectClass
.LanguageDef
[IndexI
][1]
302 StringBuffer
= StringIO()
305 NumberOfUseOtherLangDef
= 0
307 for IndexJ
in range(1, len(UniObjectClass
.OrderedStringList
[UniObjectClass
.LanguageDef
[IndexI
][0]])):
308 Item
= UniObjectClass
.FindByToken(IndexJ
, Language
)
309 Name
= Item
.StringName
310 Value
= Item
.StringValueByteList
311 Referenced
= Item
.Referenced
314 UseOtherLangDef
= Item
.UseOtherLangDef
316 if UseOtherLangDef
!= '' and Referenced
:
317 NumberOfUseOtherLangDef
= NumberOfUseOtherLangDef
+ 1
320 if NumberOfUseOtherLangDef
> 0:
321 StrStringValue
= WriteLine(StrStringValue
, CreateArrayItem([StringSkipType
] + DecToHexList(NumberOfUseOtherLangDef
, 4)))
322 CreateBinBuffer (StringBuffer
, ([StringSkipType
] + DecToHexList(NumberOfUseOtherLangDef
, 4)))
323 NumberOfUseOtherLangDef
= 0
324 ArrayLength
= ArrayLength
+ 3
325 if Referenced
and Item
.Token
> 0:
327 StrStringValue
= WriteLine(StrStringValue
, "// %s: %s:%s" % (DecToHexStr(Index
, 4), Name
, DecToHexStr(Token
, 4)))
328 StrStringValue
= Write(StrStringValue
, CreateCFileStringValue(Value
))
329 CreateBinBuffer (StringBuffer
, [StringBlockType
] + Value
)
330 ArrayLength
= ArrayLength
+ Item
.Length
+ 1 # 1 is for the length of string type
333 # EFI_HII_PACKAGE_HEADER
335 Offset
= EFI_HII_STRING_PACKAGE_HDR_LENGTH
+ len(Language
) + 1
336 ArrayLength
= Offset
+ ArrayLength
+ 1
339 # Create PACKAGE HEADER
341 Str
= WriteLine(Str
, '// PACKAGE HEADER\n')
342 TotalLength
= TotalLength
+ ArrayLength
344 List
= DecToHexList(ArrayLength
, 6) + \
345 [StringPackageType
] + \
346 DecToHexList(Offset
) + \
347 DecToHexList(Offset
) + \
348 DecToHexList(EFI_HII_LANGUAGE_WINDOW
, EFI_HII_LANGUAGE_WINDOW_LENGTH
* 2) * EFI_HII_LANGUAGE_WINDOW_NUMBER
+ \
349 DecToHexList(EFI_STRING_ID
, 4) + \
350 AscToHexList(Language
) + \
352 Str
= WriteLine(Str
, CreateArrayItem(List
, 16) + '\n')
355 # Create PACKAGE DATA
357 Str
= WriteLine(Str
, '// PACKAGE DATA\n')
358 Str
= Write(Str
, StrStringValue
)
361 # Add an EFI_HII_SIBT_END at last
363 Str
= WriteLine(Str
, ' ' + EFI_HII_SIBT_END
+ ",")
366 # Create binary UNI string
369 CreateBinBuffer (UniBinBuffer
, List
)
370 UniBinBuffer
.write (StringBuffer
.getvalue())
371 UniBinBuffer
.write (pack("B", int(EFI_HII_SIBT_END
,16)))
375 # Create line for string variable name
376 # "unsigned char $(BaseName)Strings[] = {"
378 AllStr
= WriteLine('', CHAR_ARRAY_DEFIN
+ ' ' + BaseName
+ COMMON_FILE_NAME
+ '[] = {\n' )
382 # Create FRAMEWORK_EFI_HII_PACK_HEADER in compatible mode
384 AllStr
= WriteLine(AllStr
, '// FRAMEWORK PACKAGE HEADER Length')
385 AllStr
= WriteLine(AllStr
, CreateArrayItem(DecToHexList(TotalLength
+ 2)) + '\n')
386 AllStr
= WriteLine(AllStr
, '// FRAMEWORK PACKAGE HEADER Type')
387 AllStr
= WriteLine(AllStr
, CreateArrayItem(DecToHexList(2, 4)) + '\n')
390 # Create whole array length in UEFI mode
392 AllStr
= WriteLine(AllStr
, '// STRGATHER_OUTPUT_HEADER')
393 AllStr
= WriteLine(AllStr
, CreateArrayItem(DecToHexList(TotalLength
)) + '\n')
398 AllStr
= Write(AllStr
, Str
)
402 ## Create end of .c file
404 # Create end of .c file
406 # @retval Str: A string of .h file end
408 def CreateCFileEnd():
409 Str
= Write('', '};')
414 # Create a complete .c file
416 # @param BaseName: The basename of strings
417 # @param UniObjectClass A UniObjectClass instance
418 # @param IsCompatibleMode Compatible Mode
420 # @retval CFile: A string of complete .c file
422 def CreateCFile(BaseName
, UniObjectClass
, IsCompatibleMode
):
424 #CFile = WriteLine(CFile, CreateCFileHeader())
425 CFile
= WriteLine(CFile
, CreateCFileContent(BaseName
, UniObjectClass
, IsCompatibleMode
))
426 CFile
= WriteLine(CFile
, CreateCFileEnd())
431 # Get a list for all files
433 # @param IncludeList: A list of all path to be searched
434 # @param SkipList: A list of all types of file could be skipped
436 # @retval FileList: A list of all files found
438 def GetFileList(SourceFileList
, IncludeList
, SkipList
):
439 if IncludeList
== None:
440 EdkLogger
.error("UnicodeStringGather", AUTOGEN_ERROR
, "Include path for unicode file is not defined")
446 for File
in SourceFileList
:
447 for Dir
in IncludeList
:
448 if not os
.path
.exists(Dir
):
450 File
= os
.path
.join(Dir
, File
.Path
)
454 if os
.path
.isfile(File
) != True:
457 # Ignore file listed in skip list
460 for Skip
in SkipList
:
461 if os
.path
.splitext(File
)[1].upper() == Skip
.upper():
462 EdkLogger
.verbose("Skipped %s for string token uses search" % File
)
467 FileList
.append(File
)
475 # Search whether all string defined in UniObjectClass are referenced
476 # All string used should be set to Referenced
478 # @param UniObjectClass: Input UniObjectClass
479 # @param FileList: Search path list
480 # @param IsCompatibleMode Compatible Mode
482 # @retval UniObjectClass: UniObjectClass after searched
484 def SearchString(UniObjectClass
, FileList
, IsCompatibleMode
):
486 return UniObjectClass
488 for File
in FileList
:
489 if os
.path
.isfile(File
):
490 Lines
= open(File
, 'r')
492 if not IsCompatibleMode
:
493 StringTokenList
= STRING_TOKEN
.findall(Line
)
495 StringTokenList
= COMPATIBLE_STRING_TOKEN
.findall(Line
)
496 for StrName
in StringTokenList
:
497 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "Found string identifier: " + StrName
)
498 UniObjectClass
.SetStringReferenced(StrName
)
500 UniObjectClass
.ReToken()
502 return UniObjectClass
506 # This function is used for UEFI2.1 spec
509 def GetStringFiles(UniFilList
, SourceFileList
, IncludeList
, SkipList
, BaseName
, IsCompatibleMode
= False, ShellMode
= False, UniGenCFlag
= True, UniGenBinBuffer
= None):
513 if len(UniFilList
) > 0:
516 # support ISO 639-2 codes in .UNI files of EDK Shell
518 Uni
= UniFileClassObject(UniFilList
, True)
520 Uni
= UniFileClassObject(UniFilList
, IsCompatibleMode
)
522 EdkLogger
.error("UnicodeStringGather", AUTOGEN_ERROR
, 'No unicode files given')
524 FileList
= GetFileList(SourceFileList
, IncludeList
, SkipList
)
526 Uni
= SearchString(Uni
, FileList
, IsCompatibleMode
)
528 HFile
= CreateHFile(BaseName
, Uni
, IsCompatibleMode
, UniGenCFlag
)
530 if IsCompatibleMode
or UniGenCFlag
:
531 CFile
= CreateCFile(BaseName
, Uni
, IsCompatibleMode
)
533 CreateCFileContent(BaseName
, Uni
, IsCompatibleMode
, UniGenBinBuffer
)
540 def Write(Target
, Item
):
544 # Write an item with a break line
546 def WriteLine(Target
, Item
):
547 return Target
+ Item
+ '\n'
549 # This acts like the main() function for the script, unless it is 'import'ed into another
551 if __name__
== '__main__':
552 EdkLogger
.info('start')
555 r
'C:\\Edk\\Strings2.uni',
556 r
'C:\\Edk\\Strings.uni'
560 for Root
, Dirs
, Files
in os
.walk('C:\\Edk'):
562 SrcFileList
.append(File
)
568 SkipList
= ['.inf', '.uni']
569 BaseName
= 'DriverSample'
570 (h
, c
) = GetStringFiles(UniFileList
, SrcFileList
, IncludeList
, SkipList
, BaseName
, True)
571 hfile
= open('unistring.h', 'w')
572 cfile
= open('unistring.c', 'w')
576 EdkLogger
.info('end')