]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/AutoGen/GenC.py
BaseTools: Fix the bug that FixedPcdGetPtr failure for CArray Pcd
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / GenC.py
1 ## @file
2 # Routines for generating AutoGen.h and AutoGen.c
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 ## Import Modules
15 #
16 import string
17 import collections
18 import struct
19 from Common import EdkLogger
20
21 from Common.BuildToolError import *
22 from Common.DataType import *
23 from Common.Misc import *
24 from Common.String import StringToArray
25 from StrGather import *
26 from GenPcdDb import CreatePcdDatabaseCode
27 from IdfClassObject import *
28
29 ## PCD type string
30 gItemTypeStringDatabase = {
31 TAB_PCDS_FEATURE_FLAG : 'FixedAtBuild',
32 TAB_PCDS_FIXED_AT_BUILD : 'FixedAtBuild',
33 TAB_PCDS_PATCHABLE_IN_MODULE: 'BinaryPatch',
34 TAB_PCDS_DYNAMIC : '',
35 TAB_PCDS_DYNAMIC_DEFAULT : '',
36 TAB_PCDS_DYNAMIC_VPD : '',
37 TAB_PCDS_DYNAMIC_HII : '',
38 TAB_PCDS_DYNAMIC_EX : '',
39 TAB_PCDS_DYNAMIC_EX_DEFAULT : '',
40 TAB_PCDS_DYNAMIC_EX_VPD : '',
41 TAB_PCDS_DYNAMIC_EX_HII : '',
42 }
43
44 ## Dynamic PCD types
45 gDynamicPcd = [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC_DEFAULT, TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_HII]
46
47 ## Dynamic-ex PCD types
48 gDynamicExPcd = [TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX_DEFAULT, TAB_PCDS_DYNAMIC_EX_VPD, TAB_PCDS_DYNAMIC_EX_HII]
49
50 ## Datum size
51 gDatumSizeStringDatabase = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOLEAN','VOID*':'8'}
52 gDatumSizeStringDatabaseH = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOL','VOID*':'PTR'}
53 gDatumSizeStringDatabaseLib = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'Bool','VOID*':'Ptr'}
54
55 ## AutoGen File Header Templates
56 gAutoGenHeaderString = TemplateString("""\
57 /**
58 DO NOT EDIT
59 FILE auto-generated
60 Module name:
61 ${FileName}
62 Abstract: Auto-generated ${FileName} for building module or library.
63 **/
64 """)
65
66 gAutoGenHPrologueString = TemplateString("""
67 #ifndef _${File}_${Guid}
68 #define _${File}_${Guid}
69
70 """)
71
72 gAutoGenHCppPrologueString = """\
73 #ifdef __cplusplus
74 extern "C" {
75 #endif
76
77 """
78
79 gAutoGenHEpilogueString = """
80
81 #ifdef __cplusplus
82 }
83 #endif
84
85 #endif
86 """
87
88 ## PEI Core Entry Point Templates
89 gPeiCoreEntryPointPrototype = TemplateString("""
90 ${BEGIN}
91 VOID
92 EFIAPI
93 ${Function} (
94 IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData,
95 IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList,
96 IN VOID *Context
97 );
98 ${END}
99 """)
100
101 gPeiCoreEntryPointString = TemplateString("""
102 ${BEGIN}
103 VOID
104 EFIAPI
105 ProcessModuleEntryPointList (
106 IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData,
107 IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList,
108 IN VOID *Context
109 )
110
111 {
112 ${Function} (SecCoreData, PpiList, Context);
113 }
114 ${END}
115 """)
116
117
118 ## DXE Core Entry Point Templates
119 gDxeCoreEntryPointPrototype = TemplateString("""
120 ${BEGIN}
121 VOID
122 EFIAPI
123 ${Function} (
124 IN VOID *HobStart
125 );
126 ${END}
127 """)
128
129 gDxeCoreEntryPointString = TemplateString("""
130 ${BEGIN}
131 VOID
132 EFIAPI
133 ProcessModuleEntryPointList (
134 IN VOID *HobStart
135 )
136
137 {
138 ${Function} (HobStart);
139 }
140 ${END}
141 """)
142
143 ## PEIM Entry Point Templates
144 gPeimEntryPointPrototype = TemplateString("""
145 ${BEGIN}
146 EFI_STATUS
147 EFIAPI
148 ${Function} (
149 IN EFI_PEI_FILE_HANDLE FileHandle,
150 IN CONST EFI_PEI_SERVICES **PeiServices
151 );
152 ${END}
153 """)
154
155 gPeimEntryPointString = [
156 TemplateString("""
157 GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
158
159 EFI_STATUS
160 EFIAPI
161 ProcessModuleEntryPointList (
162 IN EFI_PEI_FILE_HANDLE FileHandle,
163 IN CONST EFI_PEI_SERVICES **PeiServices
164 )
165
166 {
167 return EFI_SUCCESS;
168 }
169 """),
170 TemplateString("""
171 GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
172 ${BEGIN}
173 EFI_STATUS
174 EFIAPI
175 ProcessModuleEntryPointList (
176 IN EFI_PEI_FILE_HANDLE FileHandle,
177 IN CONST EFI_PEI_SERVICES **PeiServices
178 )
179
180 {
181 return ${Function} (FileHandle, PeiServices);
182 }
183 ${END}
184 """),
185 TemplateString("""
186 GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
187
188 EFI_STATUS
189 EFIAPI
190 ProcessModuleEntryPointList (
191 IN EFI_PEI_FILE_HANDLE FileHandle,
192 IN CONST EFI_PEI_SERVICES **PeiServices
193 )
194
195 {
196 EFI_STATUS Status;
197 EFI_STATUS CombinedStatus;
198
199 CombinedStatus = EFI_LOAD_ERROR;
200 ${BEGIN}
201 Status = ${Function} (FileHandle, PeiServices);
202 if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {
203 CombinedStatus = Status;
204 }
205 ${END}
206 return CombinedStatus;
207 }
208 """)
209 ]
210
211 ## SMM_CORE Entry Point Templates
212 gSmmCoreEntryPointPrototype = TemplateString("""
213 ${BEGIN}
214 EFI_STATUS
215 EFIAPI
216 ${Function} (
217 IN EFI_HANDLE ImageHandle,
218 IN EFI_SYSTEM_TABLE *SystemTable
219 );
220 ${END}
221 """)
222
223 gSmmCoreEntryPointString = TemplateString("""
224 ${BEGIN}
225 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
226 const UINT32 _gDxeRevision = ${PiSpecVersion};
227
228 EFI_STATUS
229 EFIAPI
230 ProcessModuleEntryPointList (
231 IN EFI_HANDLE ImageHandle,
232 IN EFI_SYSTEM_TABLE *SystemTable
233 )
234 {
235 return ${Function} (ImageHandle, SystemTable);
236 }
237 ${END}
238 """)
239
240 ## DXE SMM Entry Point Templates
241 gDxeSmmEntryPointPrototype = TemplateString("""
242 ${BEGIN}
243 EFI_STATUS
244 EFIAPI
245 ${Function} (
246 IN EFI_HANDLE ImageHandle,
247 IN EFI_SYSTEM_TABLE *SystemTable
248 );
249 ${END}
250 """)
251
252 gDxeSmmEntryPointString = [
253 TemplateString("""
254 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
255 const UINT32 _gDxeRevision = ${PiSpecVersion};
256
257 EFI_STATUS
258 EFIAPI
259 ProcessModuleEntryPointList (
260 IN EFI_HANDLE ImageHandle,
261 IN EFI_SYSTEM_TABLE *SystemTable
262 )
263
264 {
265 return EFI_SUCCESS;
266 }
267 """),
268 TemplateString("""
269 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
270 const UINT32 _gDxeRevision = ${PiSpecVersion};
271
272 static BASE_LIBRARY_JUMP_BUFFER mJumpContext;
273 static EFI_STATUS mDriverEntryPointStatus;
274
275 VOID
276 EFIAPI
277 ExitDriver (
278 IN EFI_STATUS Status
279 )
280 {
281 if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
282 mDriverEntryPointStatus = Status;
283 }
284 LongJump (&mJumpContext, (UINTN)-1);
285 ASSERT (FALSE);
286 }
287
288 EFI_STATUS
289 EFIAPI
290 ProcessModuleEntryPointList (
291 IN EFI_HANDLE ImageHandle,
292 IN EFI_SYSTEM_TABLE *SystemTable
293 )
294 {
295 mDriverEntryPointStatus = EFI_LOAD_ERROR;
296
297 ${BEGIN}
298 if (SetJump (&mJumpContext) == 0) {
299 ExitDriver (${Function} (ImageHandle, SystemTable));
300 ASSERT (FALSE);
301 }
302 ${END}
303
304 return mDriverEntryPointStatus;
305 }
306 """)
307 ]
308
309 ## UEFI Driver Entry Point Templates
310 gUefiDriverEntryPointPrototype = TemplateString("""
311 ${BEGIN}
312 EFI_STATUS
313 EFIAPI
314 ${Function} (
315 IN EFI_HANDLE ImageHandle,
316 IN EFI_SYSTEM_TABLE *SystemTable
317 );
318 ${END}
319 """)
320
321 gUefiDriverEntryPointString = [
322 TemplateString("""
323 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
324 const UINT32 _gDxeRevision = ${PiSpecVersion};
325
326 EFI_STATUS
327 EFIAPI
328 ProcessModuleEntryPointList (
329 IN EFI_HANDLE ImageHandle,
330 IN EFI_SYSTEM_TABLE *SystemTable
331 )
332 {
333 return EFI_SUCCESS;
334 }
335 """),
336 TemplateString("""
337 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
338 const UINT32 _gDxeRevision = ${PiSpecVersion};
339
340 ${BEGIN}
341 EFI_STATUS
342 EFIAPI
343 ProcessModuleEntryPointList (
344 IN EFI_HANDLE ImageHandle,
345 IN EFI_SYSTEM_TABLE *SystemTable
346 )
347
348 {
349 return ${Function} (ImageHandle, SystemTable);
350 }
351 ${END}
352 VOID
353 EFIAPI
354 ExitDriver (
355 IN EFI_STATUS Status
356 )
357 {
358 if (EFI_ERROR (Status)) {
359 ProcessLibraryDestructorList (gImageHandle, gST);
360 }
361 gBS->Exit (gImageHandle, Status, 0, NULL);
362 }
363 """),
364 TemplateString("""
365 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
366 const UINT32 _gDxeRevision = ${PiSpecVersion};
367
368 static BASE_LIBRARY_JUMP_BUFFER mJumpContext;
369 static EFI_STATUS mDriverEntryPointStatus;
370
371 EFI_STATUS
372 EFIAPI
373 ProcessModuleEntryPointList (
374 IN EFI_HANDLE ImageHandle,
375 IN EFI_SYSTEM_TABLE *SystemTable
376 )
377 {
378 mDriverEntryPointStatus = EFI_LOAD_ERROR;
379 ${BEGIN}
380 if (SetJump (&mJumpContext) == 0) {
381 ExitDriver (${Function} (ImageHandle, SystemTable));
382 ASSERT (FALSE);
383 }
384 ${END}
385 return mDriverEntryPointStatus;
386 }
387
388 VOID
389 EFIAPI
390 ExitDriver (
391 IN EFI_STATUS Status
392 )
393 {
394 if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
395 mDriverEntryPointStatus = Status;
396 }
397 LongJump (&mJumpContext, (UINTN)-1);
398 ASSERT (FALSE);
399 }
400 """)
401 ]
402
403
404 ## UEFI Application Entry Point Templates
405 gUefiApplicationEntryPointPrototype = TemplateString("""
406 ${BEGIN}
407 EFI_STATUS
408 EFIAPI
409 ${Function} (
410 IN EFI_HANDLE ImageHandle,
411 IN EFI_SYSTEM_TABLE *SystemTable
412 );
413 ${END}
414 """)
415
416 gUefiApplicationEntryPointString = [
417 TemplateString("""
418 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
419
420 EFI_STATUS
421 EFIAPI
422 ProcessModuleEntryPointList (
423 IN EFI_HANDLE ImageHandle,
424 IN EFI_SYSTEM_TABLE *SystemTable
425 )
426 {
427 return EFI_SUCCESS;
428 }
429 """),
430 TemplateString("""
431 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
432
433 ${BEGIN}
434 EFI_STATUS
435 EFIAPI
436 ProcessModuleEntryPointList (
437 IN EFI_HANDLE ImageHandle,
438 IN EFI_SYSTEM_TABLE *SystemTable
439 )
440
441 {
442 return ${Function} (ImageHandle, SystemTable);
443 }
444 ${END}
445 VOID
446 EFIAPI
447 ExitDriver (
448 IN EFI_STATUS Status
449 )
450 {
451 if (EFI_ERROR (Status)) {
452 ProcessLibraryDestructorList (gImageHandle, gST);
453 }
454 gBS->Exit (gImageHandle, Status, 0, NULL);
455 }
456 """),
457 TemplateString("""
458 const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
459
460 EFI_STATUS
461 EFIAPI
462 ProcessModuleEntryPointList (
463 IN EFI_HANDLE ImageHandle,
464 IN EFI_SYSTEM_TABLE *SystemTable
465 )
466
467 {
468 ${BEGIN}
469 if (SetJump (&mJumpContext) == 0) {
470 ExitDriver (${Function} (ImageHandle, SystemTable));
471 ASSERT (FALSE);
472 }
473 ${END}
474 return mDriverEntryPointStatus;
475 }
476
477 static BASE_LIBRARY_JUMP_BUFFER mJumpContext;
478 static EFI_STATUS mDriverEntryPointStatus = EFI_LOAD_ERROR;
479
480 VOID
481 EFIAPI
482 ExitDriver (
483 IN EFI_STATUS Status
484 )
485 {
486 if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
487 mDriverEntryPointStatus = Status;
488 }
489 LongJump (&mJumpContext, (UINTN)-1);
490 ASSERT (FALSE);
491 }
492 """)
493 ]
494
495 ## UEFI Unload Image Templates
496 gUefiUnloadImagePrototype = TemplateString("""
497 ${BEGIN}
498 EFI_STATUS
499 EFIAPI
500 ${Function} (
501 IN EFI_HANDLE ImageHandle
502 );
503 ${END}
504 """)
505
506 gUefiUnloadImageString = [
507 TemplateString("""
508 GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
509
510 EFI_STATUS
511 EFIAPI
512 ProcessModuleUnloadList (
513 IN EFI_HANDLE ImageHandle
514 )
515 {
516 return EFI_SUCCESS;
517 }
518 """),
519 TemplateString("""
520 GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
521
522 ${BEGIN}
523 EFI_STATUS
524 EFIAPI
525 ProcessModuleUnloadList (
526 IN EFI_HANDLE ImageHandle
527 )
528 {
529 return ${Function} (ImageHandle);
530 }
531 ${END}
532 """),
533 TemplateString("""
534 GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
535
536 EFI_STATUS
537 EFIAPI
538 ProcessModuleUnloadList (
539 IN EFI_HANDLE ImageHandle
540 )
541 {
542 EFI_STATUS Status;
543
544 Status = EFI_SUCCESS;
545 ${BEGIN}
546 if (EFI_ERROR (Status)) {
547 ${Function} (ImageHandle);
548 } else {
549 Status = ${Function} (ImageHandle);
550 }
551 ${END}
552 return Status;
553 }
554 """)
555 ]
556
557 gLibraryStructorPrototype = {
558 'BASE' : TemplateString("""${BEGIN}
559 RETURN_STATUS
560 EFIAPI
561 ${Function} (
562 VOID
563 );${END}
564 """),
565
566 'PEI' : TemplateString("""${BEGIN}
567 EFI_STATUS
568 EFIAPI
569 ${Function} (
570 IN EFI_PEI_FILE_HANDLE FileHandle,
571 IN CONST EFI_PEI_SERVICES **PeiServices
572 );${END}
573 """),
574
575 'DXE' : TemplateString("""${BEGIN}
576 EFI_STATUS
577 EFIAPI
578 ${Function} (
579 IN EFI_HANDLE ImageHandle,
580 IN EFI_SYSTEM_TABLE *SystemTable
581 );${END}
582 """),
583 }
584
585 gLibraryStructorCall = {
586 'BASE' : TemplateString("""${BEGIN}
587 Status = ${Function} ();
588 ASSERT_EFI_ERROR (Status);${END}
589 """),
590
591 'PEI' : TemplateString("""${BEGIN}
592 Status = ${Function} (FileHandle, PeiServices);
593 ASSERT_EFI_ERROR (Status);${END}
594 """),
595
596 'DXE' : TemplateString("""${BEGIN}
597 Status = ${Function} (ImageHandle, SystemTable);
598 ASSERT_EFI_ERROR (Status);${END}
599 """),
600 }
601
602 ## Library Constructor and Destructor Templates
603 gLibraryString = {
604 'BASE' : TemplateString("""
605 ${BEGIN}${FunctionPrototype}${END}
606
607 VOID
608 EFIAPI
609 ProcessLibrary${Type}List (
610 VOID
611 )
612 {
613 ${BEGIN} EFI_STATUS Status;
614 ${FunctionCall}${END}
615 }
616 """),
617
618 'PEI' : TemplateString("""
619 ${BEGIN}${FunctionPrototype}${END}
620
621 VOID
622 EFIAPI
623 ProcessLibrary${Type}List (
624 IN EFI_PEI_FILE_HANDLE FileHandle,
625 IN CONST EFI_PEI_SERVICES **PeiServices
626 )
627 {
628 ${BEGIN} EFI_STATUS Status;
629 ${FunctionCall}${END}
630 }
631 """),
632
633 'DXE' : TemplateString("""
634 ${BEGIN}${FunctionPrototype}${END}
635
636 VOID
637 EFIAPI
638 ProcessLibrary${Type}List (
639 IN EFI_HANDLE ImageHandle,
640 IN EFI_SYSTEM_TABLE *SystemTable
641 )
642 {
643 ${BEGIN} EFI_STATUS Status;
644 ${FunctionCall}${END}
645 }
646 """),
647 }
648
649 gBasicHeaderFile = "Base.h"
650
651 gModuleTypeHeaderFile = {
652 "BASE" : [gBasicHeaderFile],
653 "SEC" : ["PiPei.h", "Library/DebugLib.h"],
654 "PEI_CORE" : ["PiPei.h", "Library/DebugLib.h", "Library/PeiCoreEntryPoint.h"],
655 "PEIM" : ["PiPei.h", "Library/DebugLib.h", "Library/PeimEntryPoint.h"],
656 "DXE_CORE" : ["PiDxe.h", "Library/DebugLib.h", "Library/DxeCoreEntryPoint.h"],
657 "DXE_DRIVER" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
658 "DXE_SMM_DRIVER" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
659 "DXE_RUNTIME_DRIVER": ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
660 "DXE_SAL_DRIVER" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
661 "UEFI_DRIVER" : ["Uefi.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
662 "UEFI_APPLICATION" : ["Uefi.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiApplicationEntryPoint.h"],
663 "SMM_CORE" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiDriverEntryPoint.h"],
664 "USER_DEFINED" : [gBasicHeaderFile]
665 }
666
667 ## Autogen internal worker macro to define DynamicEx PCD name includes both the TokenSpaceGuidName
668 # the TokenName and Guid comparison to avoid define name collisions.
669 #
670 # @param Info The ModuleAutoGen object
671 # @param AutoGenH The TemplateString object for header file
672 #
673 #
674 def DynExPcdTokenNumberMapping(Info, AutoGenH):
675 ExTokenCNameList = []
676 PcdExList = []
677 # Even it is the Library, the PCD is saved in the ModulePcdList
678 PcdList = Info.ModulePcdList
679 for Pcd in PcdList:
680 if Pcd.Type in gDynamicExPcd:
681 ExTokenCNameList.append(Pcd.TokenCName)
682 PcdExList.append(Pcd)
683 if len(ExTokenCNameList) == 0:
684 return
685 AutoGenH.Append('\n#define COMPAREGUID(Guid1, Guid2) (BOOLEAN)(*(CONST UINT64*)Guid1 == *(CONST UINT64*)Guid2 && *((CONST UINT64*)Guid1 + 1) == *((CONST UINT64*)Guid2 + 1))\n')
686 # AutoGen for each PCD listed in a [PcdEx] section of a Module/Lib INF file.
687 # Auto generate a macro for each TokenName that takes a Guid pointer as a parameter.
688 # Use the Guid pointer to see if it matches any of the token space GUIDs.
689 TokenCNameList = []
690 for TokenCName in ExTokenCNameList:
691 if TokenCName in TokenCNameList:
692 continue
693 Index = 0
694 Count = ExTokenCNameList.count(TokenCName)
695 for Pcd in PcdExList:
696 RealTokenCName = Pcd.TokenCName
697 for PcdItem in GlobalData.MixedPcd:
698 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
699 RealTokenCName = PcdItem[0]
700 break
701 if Pcd.TokenCName == TokenCName:
702 Index = Index + 1
703 if Index == 1:
704 AutoGenH.Append('\n#define __PCD_%s_ADDR_CMP(GuidPtr) (' % (RealTokenCName))
705 AutoGenH.Append('\\\n (GuidPtr == &%s) ? _PCD_TOKEN_%s_%s:'
706 % (Pcd.TokenSpaceGuidCName, Pcd.TokenSpaceGuidCName, RealTokenCName))
707 else:
708 AutoGenH.Append('\\\n (GuidPtr == &%s) ? _PCD_TOKEN_%s_%s:'
709 % (Pcd.TokenSpaceGuidCName, Pcd.TokenSpaceGuidCName, RealTokenCName))
710 if Index == Count:
711 AutoGenH.Append('0 \\\n )\n')
712 TokenCNameList.append(TokenCName)
713
714 TokenCNameList = []
715 for TokenCName in ExTokenCNameList:
716 if TokenCName in TokenCNameList:
717 continue
718 Index = 0
719 Count = ExTokenCNameList.count(TokenCName)
720 for Pcd in PcdExList:
721 RealTokenCName = Pcd.TokenCName
722 for PcdItem in GlobalData.MixedPcd:
723 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
724 RealTokenCName = PcdItem[0]
725 break
726 if Pcd.Type in gDynamicExPcd and Pcd.TokenCName == TokenCName:
727 Index = Index + 1
728 if Index == 1:
729 AutoGenH.Append('\n#define __PCD_%s_VAL_CMP(GuidPtr) (' % (RealTokenCName))
730 AutoGenH.Append('\\\n (GuidPtr == NULL) ? 0:')
731 AutoGenH.Append('\\\n COMPAREGUID (GuidPtr, &%s) ? _PCD_TOKEN_%s_%s:'
732 % (Pcd.TokenSpaceGuidCName, Pcd.TokenSpaceGuidCName, RealTokenCName))
733 else:
734 AutoGenH.Append('\\\n COMPAREGUID (GuidPtr, &%s) ? _PCD_TOKEN_%s_%s:'
735 % (Pcd.TokenSpaceGuidCName, Pcd.TokenSpaceGuidCName, RealTokenCName))
736 if Index == Count:
737 AutoGenH.Append('0 \\\n )\n')
738 # Autogen internal worker macro to compare GUIDs. Guid1 is a pointer to a GUID.
739 # Guid2 is a C name for a GUID. Compare pointers first because optimizing compiler
740 # can do this at build time on CONST GUID pointers and optimize away call to COMPAREGUID().
741 # COMPAREGUID() will only be used if the Guid passed in is local to the module.
742 AutoGenH.Append('#define _PCD_TOKEN_EX_%s(GuidPtr) __PCD_%s_ADDR_CMP(GuidPtr) ? __PCD_%s_ADDR_CMP(GuidPtr) : __PCD_%s_VAL_CMP(GuidPtr) \n'
743 % (RealTokenCName, RealTokenCName, RealTokenCName, RealTokenCName))
744 TokenCNameList.append(TokenCName)
745
746 def GetPcdSize(Pcd):
747 if Pcd.DatumType == 'VOID*':
748 Value = Pcd.DefaultValue
749 if Value in [None, '']:
750 return 1
751 elif Value[0] == 'L':
752 return (len(Value) - 2) * 2
753 elif Value[0] == '{':
754 return len(Value.split(','))
755 else:
756 return len(Value) - 1
757 if Pcd.DatumType == 'UINT64':
758 return 8
759 if Pcd.DatumType == 'UINT32':
760 return 4
761 if Pcd.DatumType == 'UINT16':
762 return 2
763 if Pcd.DatumType == 'UINT8':
764 return 1
765 if Pcd.DatumType == 'BOOLEAN':
766 return 1
767
768
769 ## Create code for module PCDs
770 #
771 # @param Info The ModuleAutoGen object
772 # @param AutoGenC The TemplateString object for C code
773 # @param AutoGenH The TemplateString object for header file
774 # @param Pcd The PCD object
775 #
776 def CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd):
777 TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue #Info.GuidList[Pcd.TokenSpaceGuidCName]
778 PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
779 #
780 # Write PCDs
781 #
782 TokenCName = Pcd.TokenCName
783 for PcdItem in GlobalData.MixedPcd:
784 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
785 TokenCName = PcdItem[0]
786 break
787 PcdTokenName = '_PCD_TOKEN_' + TokenCName
788 PatchPcdSizeTokenName = '_PCD_PATCHABLE_' + TokenCName +'_SIZE'
789 PatchPcdSizeVariableName = '_gPcd_BinaryPatch_Size_' + TokenCName
790 FixPcdSizeTokenName = '_PCD_SIZE_' + TokenCName
791
792 if GlobalData.BuildOptionPcd:
793 for PcdItem in GlobalData.BuildOptionPcd:
794 if (Pcd.TokenSpaceGuidCName, TokenCName) == (PcdItem[0], PcdItem[1]):
795 Pcd.DefaultValue = PcdItem[2]
796 break
797
798 if Pcd.Type in gDynamicExPcd:
799 TokenNumber = int(Pcd.TokenValue, 0)
800 # Add TokenSpaceGuidValue value to PcdTokenName to discriminate the DynamicEx PCDs with
801 # different Guids but same TokenCName
802 PcdExTokenName = '_PCD_TOKEN_' + Pcd.TokenSpaceGuidCName + '_' + TokenCName
803 AutoGenH.Append('\n#define %s %dU\n' % (PcdExTokenName, TokenNumber))
804 else:
805 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
806 # If one of the Source built modules listed in the DSC is not listed in FDF modules,
807 # and the INF lists a PCD can only use the PcdsDynamic access method (it is only
808 # listed in the DEC file that declares the PCD as PcdsDynamic), then build tool will
809 # report warning message notify the PI that they are attempting to build a module
810 # that must be included in a flash image in order to be functional. These Dynamic PCD
811 # will not be added into the Database unless it is used by other modules that are
812 # included in the FDF file.
813 # In this case, just assign an invalid token number to make it pass build.
814 if Pcd.Type in PCD_DYNAMIC_TYPE_LIST:
815 TokenNumber = 0
816 else:
817 EdkLogger.error("build", AUTOGEN_ERROR,
818 "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, TokenCName),
819 ExtraData="[%s]" % str(Info))
820 else:
821 TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
822 AutoGenH.Append('\n#define %s %dU\n' % (PcdTokenName, TokenNumber))
823
824 EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for " + TokenCName + "." + Pcd.TokenSpaceGuidCName)
825 if Pcd.Type not in gItemTypeStringDatabase:
826 EdkLogger.error("build", AUTOGEN_ERROR,
827 "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, TokenCName),
828 ExtraData="[%s]" % str(Info))
829 if Pcd.DatumType not in gDatumSizeStringDatabase:
830 EdkLogger.error("build", AUTOGEN_ERROR,
831 "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
832 ExtraData="[%s]" % str(Info))
833
834 DatumSize = gDatumSizeStringDatabase[Pcd.DatumType]
835 DatumSizeLib = gDatumSizeStringDatabaseLib[Pcd.DatumType]
836 GetModeName = '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + TokenCName
837 SetModeName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + TokenCName
838 SetModeStatusName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_S_' + TokenCName
839 GetModeSizeName = '_PCD_GET_MODE_SIZE' + '_' + TokenCName
840
841 PcdExCNameList = []
842 if Pcd.Type in gDynamicExPcd:
843 if Info.IsLibrary:
844 PcdList = Info.LibraryPcdList
845 else:
846 PcdList = Info.ModulePcdList
847 for PcdModule in PcdList:
848 if PcdModule.Type in gDynamicExPcd:
849 PcdExCNameList.append(PcdModule.TokenCName)
850 # Be compatible with the current code which using PcdToken and PcdGet/Set for DynamicEx Pcd.
851 # If only PcdToken and PcdGet/Set used in all Pcds with different CName, it should succeed to build.
852 # If PcdToken and PcdGet/Set used in the Pcds with different Guids but same CName, it should failed to build.
853 if PcdExCNameList.count(Pcd.TokenCName) > 1:
854 AutoGenH.Append('// Disabled the macros, as PcdToken and PcdGet/Set are not allowed in the case that more than one DynamicEx Pcds are different Guids but same CName.\n')
855 AutoGenH.Append('// #define %s %s\n' % (PcdTokenName, PcdExTokenName))
856 AutoGenH.Append('// #define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
857 AutoGenH.Append('// #define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
858 if Pcd.DatumType == 'VOID*':
859 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
860 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
861 else:
862 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
863 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
864 else:
865 AutoGenH.Append('#define %s %s\n' % (PcdTokenName, PcdExTokenName))
866 AutoGenH.Append('#define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
867 AutoGenH.Append('#define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
868 if Pcd.DatumType == 'VOID*':
869 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
870 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
871 else:
872 AutoGenH.Append('#define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
873 AutoGenH.Append('#define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
874 elif Pcd.Type in gDynamicPcd:
875 PcdList = []
876 PcdCNameList = []
877 PcdList.extend(Info.LibraryPcdList)
878 PcdList.extend(Info.ModulePcdList)
879 for PcdModule in PcdList:
880 if PcdModule.Type in gDynamicPcd:
881 PcdCNameList.append(PcdModule.TokenCName)
882 if PcdCNameList.count(Pcd.TokenCName) > 1:
883 EdkLogger.error("build", AUTOGEN_ERROR, "More than one Dynamic Pcds [%s] are different Guids but same CName. They need to be changed to DynamicEx type to avoid the confliction.\n" % (TokenCName), ExtraData="[%s]" % str(Info.MetaFile.Path))
884 else:
885 AutoGenH.Append('#define %s LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
886 AutoGenH.Append('#define %s LibPcdGetSize(%s)\n' % (GetModeSizeName, PcdTokenName))
887 if Pcd.DatumType == 'VOID*':
888 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
889 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%sS(%s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
890 else:
891 AutoGenH.Append('#define %s(Value) LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
892 AutoGenH.Append('#define %s(Value) LibPcdSet%sS(%s, (Value))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
893 else:
894 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + TokenCName
895 Const = 'const'
896 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
897 Const = ''
898 Type = ''
899 Array = ''
900 Value = Pcd.DefaultValue
901 Unicode = False
902 ValueNumber = 0
903
904 if Pcd.DatumType == 'BOOLEAN':
905 BoolValue = Value.upper()
906 if BoolValue == 'TRUE' or BoolValue == '1':
907 Value = '1U'
908 elif BoolValue == 'FALSE' or BoolValue == '0':
909 Value = '0U'
910
911 if Pcd.DatumType in ['UINT64', 'UINT32', 'UINT16', 'UINT8']:
912 try:
913 if Value.upper().startswith('0X'):
914 ValueNumber = int (Value, 16)
915 else:
916 ValueNumber = int (Value)
917 except:
918 EdkLogger.error("build", AUTOGEN_ERROR,
919 "PCD value is not valid dec or hex number for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
920 ExtraData="[%s]" % str(Info))
921 if Pcd.DatumType == 'UINT64':
922 if ValueNumber < 0:
923 EdkLogger.error("build", AUTOGEN_ERROR,
924 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
925 ExtraData="[%s]" % str(Info))
926 elif ValueNumber >= 0x10000000000000000:
927 EdkLogger.error("build", AUTOGEN_ERROR,
928 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
929 ExtraData="[%s]" % str(Info))
930 if not Value.endswith('ULL'):
931 Value += 'ULL'
932 elif Pcd.DatumType == 'UINT32':
933 if ValueNumber < 0:
934 EdkLogger.error("build", AUTOGEN_ERROR,
935 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
936 ExtraData="[%s]" % str(Info))
937 elif ValueNumber >= 0x100000000:
938 EdkLogger.error("build", AUTOGEN_ERROR,
939 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
940 ExtraData="[%s]" % str(Info))
941 if not Value.endswith('U'):
942 Value += 'U'
943 elif Pcd.DatumType == 'UINT16':
944 if ValueNumber < 0:
945 EdkLogger.error("build", AUTOGEN_ERROR,
946 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
947 ExtraData="[%s]" % str(Info))
948 elif ValueNumber >= 0x10000:
949 EdkLogger.error("build", AUTOGEN_ERROR,
950 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
951 ExtraData="[%s]" % str(Info))
952 if not Value.endswith('U'):
953 Value += 'U'
954 elif Pcd.DatumType == 'UINT8':
955 if ValueNumber < 0:
956 EdkLogger.error("build", AUTOGEN_ERROR,
957 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
958 ExtraData="[%s]" % str(Info))
959 elif ValueNumber >= 0x100:
960 EdkLogger.error("build", AUTOGEN_ERROR,
961 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
962 ExtraData="[%s]" % str(Info))
963 if not Value.endswith('U'):
964 Value += 'U'
965 if Pcd.DatumType == 'VOID*':
966 if Pcd.MaxDatumSize == None or Pcd.MaxDatumSize == '':
967 EdkLogger.error("build", AUTOGEN_ERROR,
968 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, TokenCName),
969 ExtraData="[%s]" % str(Info))
970
971 ArraySize = int(Pcd.MaxDatumSize, 0)
972 if Value[0] == '{':
973 Type = '(VOID *)'
974 else:
975 if Value[0] == 'L':
976 Unicode = True
977 Value = Value.lstrip('L') #.strip('"')
978 Value = eval(Value) # translate escape character
979 NewValue = '{'
980 for Index in range(0,len(Value)):
981 if Unicode:
982 NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ', '
983 else:
984 NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
985 if Unicode:
986 ArraySize = ArraySize / 2;
987
988 if ArraySize < (len(Value) + 1):
989 EdkLogger.error("build", AUTOGEN_ERROR,
990 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName),
991 ExtraData="[%s]" % str(Info))
992 Value = NewValue + '0 }'
993 Array = '[%d]' % ArraySize
994 #
995 # skip casting for fixed at build since it breaks ARM assembly.
996 # Long term we need PCD macros that work in assembly
997 #
998 elif Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:
999 Value = "((%s)%s)" % (Pcd.DatumType, Value)
1000
1001 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1002 PcdValueName = '_PCD_PATCHABLE_VALUE_' + TokenCName
1003 else:
1004 PcdValueName = '_PCD_VALUE_' + TokenCName
1005
1006 if Pcd.DatumType == 'VOID*':
1007 #
1008 # For unicode, UINT16 array will be generated, so the alignment of unicode is guaranteed.
1009 #
1010 if Unicode:
1011 AutoGenH.Append('#define %s %s%s\n' %(PcdValueName, Type, PcdVariableName))
1012 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT16 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
1013 AutoGenH.Append('extern %s UINT16 %s%s;\n' %(Const, PcdVariableName, Array))
1014 AutoGenH.Append('#define %s %s%s\n' %(GetModeName, Type, PcdVariableName))
1015 else:
1016 AutoGenH.Append('#define %s %s%s\n' %(PcdValueName, Type, PcdVariableName))
1017 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
1018 AutoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
1019 AutoGenH.Append('#define %s %s%s\n' %(GetModeName, Type, PcdVariableName))
1020
1021 PcdDataSize = GetPcdSize(Pcd)
1022 if Pcd.Type == TAB_PCDS_FIXED_AT_BUILD:
1023 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1024 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,FixPcdSizeTokenName))
1025
1026 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1027 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, Pcd.MaxDatumSize))
1028 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,PatchPcdSizeVariableName))
1029 AutoGenH.Append('extern UINTN %s; \n' % PatchPcdSizeVariableName)
1030 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED UINTN %s = %s;\n' % (PatchPcdSizeVariableName,PcdDataSize))
1031 elif Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1032 AutoGenH.Append('#define %s %s\n' %(PcdValueName, Value))
1033 AutoGenC.Append('volatile %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
1034 AutoGenH.Append('extern volatile %s %s %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
1035 AutoGenH.Append('#define %s %s%s\n' % (GetModeName, Type, PcdVariableName))
1036
1037 PcdDataSize = GetPcdSize(Pcd)
1038 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, PcdDataSize))
1039
1040 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,PatchPcdSizeVariableName))
1041 AutoGenH.Append('extern UINTN %s; \n' % PatchPcdSizeVariableName)
1042 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED UINTN %s = %s;\n' % (PatchPcdSizeVariableName,PcdDataSize))
1043 else:
1044 PcdDataSize = GetPcdSize(Pcd)
1045 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1046 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,FixPcdSizeTokenName))
1047
1048 AutoGenH.Append('#define %s %s\n' %(PcdValueName, Value))
1049 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
1050 AutoGenH.Append('extern %s %s %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
1051 AutoGenH.Append('#define %s %s%s\n' % (GetModeName, Type, PcdVariableName))
1052
1053 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1054 if Pcd.DatumType == 'VOID*':
1055 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPatchPcdSetPtrAndSize((VOID *)_gPcd_BinaryPatch_%s, &_gPcd_BinaryPatch_Size_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeName, Pcd.TokenCName, Pcd.TokenCName, Pcd.TokenCName))
1056 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPatchPcdSetPtrAndSizeS((VOID *)_gPcd_BinaryPatch_%s, &_gPcd_BinaryPatch_Size_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, Pcd.TokenCName, Pcd.TokenCName, Pcd.TokenCName))
1057 else:
1058 AutoGenH.Append('#define %s(Value) (%s = (Value))\n' % (SetModeName, PcdVariableName))
1059 AutoGenH.Append('#define %s(Value) ((%s = (Value)), RETURN_SUCCESS) \n' % (SetModeStatusName, PcdVariableName))
1060 else:
1061 AutoGenH.Append('//#define %s ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)
1062
1063 ## Create code for library module PCDs
1064 #
1065 # @param Info The ModuleAutoGen object
1066 # @param AutoGenC The TemplateString object for C code
1067 # @param AutoGenH The TemplateString object for header file
1068 # @param Pcd The PCD object
1069 #
1070 def CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd):
1071 PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
1072 TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1073 TokenCName = Pcd.TokenCName
1074 for PcdItem in GlobalData.MixedPcd:
1075 if (TokenCName, TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
1076 TokenCName = PcdItem[0]
1077 break
1078 PcdTokenName = '_PCD_TOKEN_' + TokenCName
1079 FixPcdSizeTokenName = '_PCD_SIZE_' + TokenCName
1080 PatchPcdSizeTokenName = '_PCD_PATCHABLE_' + TokenCName +'_SIZE'
1081 PatchPcdSizeVariableName = '_gPcd_BinaryPatch_Size_' + TokenCName
1082
1083 if GlobalData.BuildOptionPcd:
1084 for PcdItem in GlobalData.BuildOptionPcd:
1085 if (Pcd.TokenSpaceGuidCName, TokenCName) == (PcdItem[0], PcdItem[1]):
1086 Pcd.DefaultValue = PcdItem[2]
1087 break
1088
1089 #
1090 # Write PCDs
1091 #
1092 if Pcd.Type in gDynamicExPcd:
1093 TokenNumber = int(Pcd.TokenValue, 0)
1094 else:
1095 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
1096 # If one of the Source built modules listed in the DSC is not listed in FDF modules,
1097 # and the INF lists a PCD can only use the PcdsDynamic access method (it is only
1098 # listed in the DEC file that declares the PCD as PcdsDynamic), then build tool will
1099 # report warning message notify the PI that they are attempting to build a module
1100 # that must be included in a flash image in order to be functional. These Dynamic PCD
1101 # will not be added into the Database unless it is used by other modules that are
1102 # included in the FDF file.
1103 # In this case, just assign an invalid token number to make it pass build.
1104 if Pcd.Type in PCD_DYNAMIC_TYPE_LIST:
1105 TokenNumber = 0
1106 else:
1107 EdkLogger.error("build", AUTOGEN_ERROR,
1108 "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, TokenCName),
1109 ExtraData="[%s]" % str(Info))
1110 else:
1111 TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
1112
1113 if Pcd.Type not in gItemTypeStringDatabase:
1114 EdkLogger.error("build", AUTOGEN_ERROR,
1115 "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, TokenCName),
1116 ExtraData="[%s]" % str(Info))
1117 if Pcd.DatumType not in gDatumSizeStringDatabase:
1118 EdkLogger.error("build", AUTOGEN_ERROR,
1119 "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1120 ExtraData="[%s]" % str(Info))
1121
1122 DatumType = Pcd.DatumType
1123 DatumSize = gDatumSizeStringDatabaseH[DatumType]
1124 DatumSizeLib= gDatumSizeStringDatabaseLib[DatumType]
1125 GetModeName = '_PCD_GET_MODE_' + DatumSize + '_' + TokenCName
1126 SetModeName = '_PCD_SET_MODE_' + DatumSize + '_' + TokenCName
1127 SetModeStatusName = '_PCD_SET_MODE_' + DatumSize + '_S_' + TokenCName
1128 GetModeSizeName = '_PCD_GET_MODE_SIZE' + '_' + TokenCName
1129
1130 Type = ''
1131 Array = ''
1132 if Pcd.DatumType == 'VOID*':
1133 if Pcd.DefaultValue[0]== '{':
1134 Type = '(VOID *)'
1135 Array = '[]'
1136 PcdItemType = Pcd.Type
1137 PcdExCNameList = []
1138 if PcdItemType in gDynamicExPcd:
1139 PcdExTokenName = '_PCD_TOKEN_' + TokenSpaceGuidCName + '_' + TokenCName
1140 AutoGenH.Append('\n#define %s %dU\n' % (PcdExTokenName, TokenNumber))
1141
1142 if Info.IsLibrary:
1143 PcdList = Info.LibraryPcdList
1144 else:
1145 PcdList = Info.ModulePcdList
1146 for PcdModule in PcdList:
1147 if PcdModule.Type in gDynamicExPcd:
1148 PcdExCNameList.append(PcdModule.TokenCName)
1149 # Be compatible with the current code which using PcdGet/Set for DynamicEx Pcd.
1150 # If only PcdGet/Set used in all Pcds with different CName, it should succeed to build.
1151 # If PcdGet/Set used in the Pcds with different Guids but same CName, it should failed to build.
1152 if PcdExCNameList.count(Pcd.TokenCName) > 1:
1153 AutoGenH.Append('// Disabled the macros, as PcdToken and PcdGet/Set are not allowed in the case that more than one DynamicEx Pcds are different Guids but same CName.\n')
1154 AutoGenH.Append('// #define %s %s\n' % (PcdTokenName, PcdExTokenName))
1155 AutoGenH.Append('// #define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1156 AutoGenH.Append('// #define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
1157 if Pcd.DatumType == 'VOID*':
1158 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1159 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1160 else:
1161 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1162 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1163 else:
1164 AutoGenH.Append('#define %s %s\n' % (PcdTokenName, PcdExTokenName))
1165 AutoGenH.Append('#define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1166 AutoGenH.Append('#define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
1167 if Pcd.DatumType == 'VOID*':
1168 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1169 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1170 else:
1171 AutoGenH.Append('#define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1172 AutoGenH.Append('#define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1173 else:
1174 AutoGenH.Append('#define _PCD_TOKEN_%s %dU\n' % (TokenCName, TokenNumber))
1175 if PcdItemType in gDynamicPcd:
1176 PcdList = []
1177 PcdCNameList = []
1178 PcdList.extend(Info.LibraryPcdList)
1179 PcdList.extend(Info.ModulePcdList)
1180 for PcdModule in PcdList:
1181 if PcdModule.Type in gDynamicPcd:
1182 PcdCNameList.append(PcdModule.TokenCName)
1183 if PcdCNameList.count(Pcd.TokenCName) > 1:
1184 EdkLogger.error("build", AUTOGEN_ERROR, "More than one Dynamic Pcds [%s] are different Guids but same CName.They need to be changed to DynamicEx type to avoid the confliction.\n" % (TokenCName), ExtraData="[%s]" % str(Info.MetaFile.Path))
1185 else:
1186 AutoGenH.Append('#define %s LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
1187 AutoGenH.Append('#define %s LibPcdGetSize(%s)\n' % (GetModeSizeName, PcdTokenName))
1188 if DatumType == 'VOID*':
1189 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
1190 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%sS(%s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
1191 else:
1192 AutoGenH.Append('#define %s(Value) LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
1193 AutoGenH.Append('#define %s(Value) LibPcdSet%sS(%s, (Value))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
1194 if PcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
1195 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + TokenCName
1196 if DatumType == 'VOID*':
1197 ArraySize = int(Pcd.MaxDatumSize, 0)
1198 if Pcd.DefaultValue[0] == 'L':
1199 ArraySize = ArraySize / 2
1200 Array = '[%d]' % ArraySize
1201 DatumType = ['UINT8', 'UINT16'][Pcd.DefaultValue[0] == 'L']
1202 AutoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(DatumType, TokenCName, Array))
1203 else:
1204 AutoGenH.Append('extern volatile %s %s%s;\n' % (DatumType, PcdVariableName, Array))
1205 AutoGenH.Append('#define %s %s_gPcd_BinaryPatch_%s\n' %(GetModeName, Type, TokenCName))
1206 PcdDataSize = GetPcdSize(Pcd)
1207 if Pcd.DatumType == 'VOID*':
1208 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPatchPcdSetPtrAndSize((VOID *)_gPcd_BinaryPatch_%s, &_gPcd_BinaryPatch_Size_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeName, TokenCName, TokenCName, TokenCName))
1209 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPatchPcdSetPtrAndSizeS((VOID *)_gPcd_BinaryPatch_%s, &_gPcd_BinaryPatch_Size_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, TokenCName, TokenCName, TokenCName))
1210 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, Pcd.MaxDatumSize))
1211 else:
1212 AutoGenH.Append('#define %s(Value) (%s = (Value))\n' % (SetModeName, PcdVariableName))
1213 AutoGenH.Append('#define %s(Value) ((%s = (Value)), RETURN_SUCCESS)\n' % (SetModeStatusName, PcdVariableName))
1214 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, PcdDataSize))
1215
1216 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,PatchPcdSizeVariableName))
1217 AutoGenH.Append('extern UINTN %s; \n' % PatchPcdSizeVariableName)
1218
1219 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD or PcdItemType == TAB_PCDS_FEATURE_FLAG:
1220 key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))
1221 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + TokenCName
1222 if DatumType == 'VOID*' and Array == '[]':
1223 DatumType = ['UINT8', 'UINT16'][Pcd.DefaultValue[0] == 'L']
1224 AutoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(DatumType, TokenCName, Array))
1225 AutoGenH.Append('#define %s %s_gPcd_FixedAtBuild_%s\n' %(GetModeName, Type, TokenCName))
1226 AutoGenH.Append('//#define %s ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)
1227
1228 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD and (key in Info.ConstPcd or (Info.IsLibrary and not Info._ReferenceModules)):
1229 if DatumType == 'VOID*':
1230 AutoGenH.Append('#define _PCD_VALUE_%s %s%s\n' %(TokenCName, Type, PcdVariableName))
1231 else:
1232 AutoGenH.Append('#define _PCD_VALUE_%s %s\n' %(TokenCName, Pcd.DefaultValue))
1233
1234 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD:
1235 PcdDataSize = GetPcdSize(Pcd)
1236 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1237 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixPcdSizeTokenName))
1238
1239 ## Create code for library constructor
1240 #
1241 # @param Info The ModuleAutoGen object
1242 # @param AutoGenC The TemplateString object for C code
1243 # @param AutoGenH The TemplateString object for header file
1244 #
1245 def CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH):
1246 #
1247 # Library Constructors
1248 #
1249 ConstructorPrototypeString = TemplateString()
1250 ConstructorCallingString = TemplateString()
1251 if Info.IsLibrary:
1252 DependentLibraryList = [Info.Module]
1253 else:
1254 DependentLibraryList = Info.DependentLibraryList
1255 for Lib in DependentLibraryList:
1256 if len(Lib.ConstructorList) <= 0:
1257 continue
1258 Dict = {'Function':Lib.ConstructorList}
1259 if Lib.ModuleType in ['BASE', 'SEC']:
1260 ConstructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1261 ConstructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1262 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1263 ConstructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1264 ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1265 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1266 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1267 ConstructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1268 ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1269
1270 if str(ConstructorPrototypeString) == '':
1271 ConstructorPrototypeList = []
1272 else:
1273 ConstructorPrototypeList = [str(ConstructorPrototypeString)]
1274 if str(ConstructorCallingString) == '':
1275 ConstructorCallingList = []
1276 else:
1277 ConstructorCallingList = [str(ConstructorCallingString)]
1278
1279 Dict = {
1280 'Type' : 'Constructor',
1281 'FunctionPrototype' : ConstructorPrototypeList,
1282 'FunctionCall' : ConstructorCallingList
1283 }
1284 if Info.IsLibrary:
1285 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1286 else:
1287 if Info.ModuleType in ['BASE', 'SEC']:
1288 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1289 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1290 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1291 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1292 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1293 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1294
1295 ## Create code for library destructor
1296 #
1297 # @param Info The ModuleAutoGen object
1298 # @param AutoGenC The TemplateString object for C code
1299 # @param AutoGenH The TemplateString object for header file
1300 #
1301 def CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH):
1302 #
1303 # Library Destructors
1304 #
1305 DestructorPrototypeString = TemplateString()
1306 DestructorCallingString = TemplateString()
1307 if Info.IsLibrary:
1308 DependentLibraryList = [Info.Module]
1309 else:
1310 DependentLibraryList = Info.DependentLibraryList
1311 for Index in range(len(DependentLibraryList)-1, -1, -1):
1312 Lib = DependentLibraryList[Index]
1313 if len(Lib.DestructorList) <= 0:
1314 continue
1315 Dict = {'Function':Lib.DestructorList}
1316 if Lib.ModuleType in ['BASE', 'SEC']:
1317 DestructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1318 DestructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1319 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1320 DestructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1321 DestructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1322 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1323 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION', 'SMM_CORE']:
1324 DestructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1325 DestructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1326
1327 if str(DestructorPrototypeString) == '':
1328 DestructorPrototypeList = []
1329 else:
1330 DestructorPrototypeList = [str(DestructorPrototypeString)]
1331 if str(DestructorCallingString) == '':
1332 DestructorCallingList = []
1333 else:
1334 DestructorCallingList = [str(DestructorCallingString)]
1335
1336 Dict = {
1337 'Type' : 'Destructor',
1338 'FunctionPrototype' : DestructorPrototypeList,
1339 'FunctionCall' : DestructorCallingList
1340 }
1341 if Info.IsLibrary:
1342 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1343 else:
1344 if Info.ModuleType in ['BASE', 'SEC']:
1345 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1346 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1347 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1348 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1349 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1350 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1351
1352
1353 ## Create code for ModuleEntryPoint
1354 #
1355 # @param Info The ModuleAutoGen object
1356 # @param AutoGenC The TemplateString object for C code
1357 # @param AutoGenH The TemplateString object for header file
1358 #
1359 def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH):
1360 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1361 return
1362 #
1363 # Module Entry Points
1364 #
1365 NumEntryPoints = len(Info.Module.ModuleEntryPointList)
1366 if 'PI_SPECIFICATION_VERSION' in Info.Module.Specification:
1367 PiSpecVersion = Info.Module.Specification['PI_SPECIFICATION_VERSION']
1368 else:
1369 PiSpecVersion = '0x00000000'
1370 if 'UEFI_SPECIFICATION_VERSION' in Info.Module.Specification:
1371 UefiSpecVersion = Info.Module.Specification['UEFI_SPECIFICATION_VERSION']
1372 else:
1373 UefiSpecVersion = '0x00000000'
1374 Dict = {
1375 'Function' : Info.Module.ModuleEntryPointList,
1376 'PiSpecVersion' : PiSpecVersion + 'U',
1377 'UefiSpecVersion': UefiSpecVersion + 'U'
1378 }
1379
1380 if Info.ModuleType in ['PEI_CORE', 'DXE_CORE', 'SMM_CORE']:
1381 if Info.SourceFileList <> None and Info.SourceFileList <> []:
1382 if NumEntryPoints != 1:
1383 EdkLogger.error(
1384 "build",
1385 AUTOGEN_ERROR,
1386 '%s must have exactly one entry point' % Info.ModuleType,
1387 File=str(Info),
1388 ExtraData= ", ".join(Info.Module.ModuleEntryPointList)
1389 )
1390 if Info.ModuleType == 'PEI_CORE':
1391 AutoGenC.Append(gPeiCoreEntryPointString.Replace(Dict))
1392 AutoGenH.Append(gPeiCoreEntryPointPrototype.Replace(Dict))
1393 elif Info.ModuleType == 'DXE_CORE':
1394 AutoGenC.Append(gDxeCoreEntryPointString.Replace(Dict))
1395 AutoGenH.Append(gDxeCoreEntryPointPrototype.Replace(Dict))
1396 elif Info.ModuleType == 'SMM_CORE':
1397 AutoGenC.Append(gSmmCoreEntryPointString.Replace(Dict))
1398 AutoGenH.Append(gSmmCoreEntryPointPrototype.Replace(Dict))
1399 elif Info.ModuleType == 'PEIM':
1400 if NumEntryPoints < 2:
1401 AutoGenC.Append(gPeimEntryPointString[NumEntryPoints].Replace(Dict))
1402 else:
1403 AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict))
1404 AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict))
1405 elif Info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:
1406 if NumEntryPoints < 2:
1407 AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Replace(Dict))
1408 else:
1409 AutoGenC.Append(gUefiDriverEntryPointString[2].Replace(Dict))
1410 AutoGenH.Append(gUefiDriverEntryPointPrototype.Replace(Dict))
1411 elif Info.ModuleType == 'DXE_SMM_DRIVER':
1412 if NumEntryPoints == 0:
1413 AutoGenC.Append(gDxeSmmEntryPointString[0].Replace(Dict))
1414 else:
1415 AutoGenC.Append(gDxeSmmEntryPointString[1].Replace(Dict))
1416 AutoGenH.Append(gDxeSmmEntryPointPrototype.Replace(Dict))
1417 elif Info.ModuleType == 'UEFI_APPLICATION':
1418 if NumEntryPoints < 2:
1419 AutoGenC.Append(gUefiApplicationEntryPointString[NumEntryPoints].Replace(Dict))
1420 else:
1421 AutoGenC.Append(gUefiApplicationEntryPointString[2].Replace(Dict))
1422 AutoGenH.Append(gUefiApplicationEntryPointPrototype.Replace(Dict))
1423
1424 ## Create code for ModuleUnloadImage
1425 #
1426 # @param Info The ModuleAutoGen object
1427 # @param AutoGenC The TemplateString object for C code
1428 # @param AutoGenH The TemplateString object for header file
1429 #
1430 def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH):
1431 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1432 return
1433 #
1434 # Unload Image Handlers
1435 #
1436 NumUnloadImage = len(Info.Module.ModuleUnloadImageList)
1437 Dict = {'Count':str(NumUnloadImage) + 'U', 'Function':Info.Module.ModuleUnloadImageList}
1438 if NumUnloadImage < 2:
1439 AutoGenC.Append(gUefiUnloadImageString[NumUnloadImage].Replace(Dict))
1440 else:
1441 AutoGenC.Append(gUefiUnloadImageString[2].Replace(Dict))
1442 AutoGenH.Append(gUefiUnloadImagePrototype.Replace(Dict))
1443
1444 ## Create code for GUID
1445 #
1446 # @param Info The ModuleAutoGen object
1447 # @param AutoGenC The TemplateString object for C code
1448 # @param AutoGenH The TemplateString object for header file
1449 #
1450 def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH):
1451 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1452 GuidType = "GUID"
1453 else:
1454 GuidType = "EFI_GUID"
1455
1456 if Info.GuidList:
1457 if not Info.IsLibrary:
1458 AutoGenC.Append("\n// Guids\n")
1459 AutoGenH.Append("\n// Guids\n")
1460 #
1461 # GUIDs
1462 #
1463 for Key in Info.GuidList:
1464 if not Info.IsLibrary:
1465 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.GuidList[Key]))
1466 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1467
1468 ## Create code for protocol
1469 #
1470 # @param Info The ModuleAutoGen object
1471 # @param AutoGenC The TemplateString object for C code
1472 # @param AutoGenH The TemplateString object for header file
1473 #
1474 def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH):
1475 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1476 GuidType = "GUID"
1477 else:
1478 GuidType = "EFI_GUID"
1479
1480 if Info.ProtocolList:
1481 if not Info.IsLibrary:
1482 AutoGenC.Append("\n// Protocols\n")
1483 AutoGenH.Append("\n// Protocols\n")
1484 #
1485 # Protocol GUIDs
1486 #
1487 for Key in Info.ProtocolList:
1488 if not Info.IsLibrary:
1489 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.ProtocolList[Key]))
1490 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1491
1492 ## Create code for PPI
1493 #
1494 # @param Info The ModuleAutoGen object
1495 # @param AutoGenC The TemplateString object for C code
1496 # @param AutoGenH The TemplateString object for header file
1497 #
1498 def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH):
1499 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1500 GuidType = "GUID"
1501 else:
1502 GuidType = "EFI_GUID"
1503
1504 if Info.PpiList:
1505 if not Info.IsLibrary:
1506 AutoGenC.Append("\n// PPIs\n")
1507 AutoGenH.Append("\n// PPIs\n")
1508 #
1509 # PPI GUIDs
1510 #
1511 for Key in Info.PpiList:
1512 if not Info.IsLibrary:
1513 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.PpiList[Key]))
1514 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1515
1516 ## Create code for PCD
1517 #
1518 # @param Info The ModuleAutoGen object
1519 # @param AutoGenC The TemplateString object for C code
1520 # @param AutoGenH The TemplateString object for header file
1521 #
1522 def CreatePcdCode(Info, AutoGenC, AutoGenH):
1523
1524 # Collect Token Space GUIDs used by DynamicEc PCDs
1525 TokenSpaceList = []
1526 for Pcd in Info.ModulePcdList:
1527 if Pcd.Type in gDynamicExPcd and Pcd.TokenSpaceGuidCName not in TokenSpaceList:
1528 TokenSpaceList += [Pcd.TokenSpaceGuidCName]
1529
1530 # Add extern declarations to AutoGen.h if one or more Token Space GUIDs were found
1531 if TokenSpaceList <> []:
1532 AutoGenH.Append("\n// Definition of PCD Token Space GUIDs used in this module\n\n")
1533 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1534 GuidType = "GUID"
1535 else:
1536 GuidType = "EFI_GUID"
1537 for Item in TokenSpaceList:
1538 AutoGenH.Append('extern %s %s;\n' % (GuidType, Item))
1539
1540 if Info.IsLibrary:
1541 if Info.ModulePcdList:
1542 AutoGenH.Append("\n// PCD definitions\n")
1543 for Pcd in Info.ModulePcdList:
1544 CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd)
1545 DynExPcdTokenNumberMapping (Info, AutoGenH)
1546 else:
1547 if Info.ModulePcdList:
1548 AutoGenH.Append("\n// Definition of PCDs used in this module\n")
1549 AutoGenC.Append("\n// Definition of PCDs used in this module\n")
1550 for Pcd in Info.ModulePcdList:
1551 CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd)
1552 DynExPcdTokenNumberMapping (Info, AutoGenH)
1553 if Info.LibraryPcdList:
1554 AutoGenH.Append("\n// Definition of PCDs used in libraries is in AutoGen.c\n")
1555 AutoGenC.Append("\n// Definition of PCDs used in libraries\n")
1556 for Pcd in Info.LibraryPcdList:
1557 CreateModulePcdCode(Info, AutoGenC, AutoGenC, Pcd)
1558 CreatePcdDatabaseCode(Info, AutoGenC, AutoGenH)
1559
1560 ## Create code for unicode string definition
1561 #
1562 # @param Info The ModuleAutoGen object
1563 # @param AutoGenC The TemplateString object for C code
1564 # @param AutoGenH The TemplateString object for header file
1565 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
1566 # @param UniGenBinBuffer Buffer to store uni string package data
1567 #
1568 def CreateUnicodeStringCode(Info, AutoGenC, AutoGenH, UniGenCFlag, UniGenBinBuffer):
1569 WorkingDir = os.getcwd()
1570 os.chdir(Info.WorkspaceDir)
1571
1572 IncList = [Info.MetaFile.Dir]
1573 # Get all files under [Sources] section in inf file for EDK-II module
1574 EDK2Module = True
1575 SrcList = [F for F in Info.SourceFileList]
1576 if Info.AutoGenVersion < 0x00010005:
1577 EDK2Module = False
1578 # Get all files under the module directory for EDK-I module
1579 Cwd = os.getcwd()
1580 os.chdir(Info.MetaFile.Dir)
1581 for Root, Dirs, Files in os.walk("."):
1582 if 'CVS' in Dirs:
1583 Dirs.remove('CVS')
1584 if '.svn' in Dirs:
1585 Dirs.remove('.svn')
1586 for File in Files:
1587 File = PathClass(os.path.join(Root, File), Info.MetaFile.Dir)
1588 if File in SrcList:
1589 continue
1590 SrcList.append(File)
1591 os.chdir(Cwd)
1592
1593 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-c') > -1:
1594 CompatibleMode = True
1595 else:
1596 CompatibleMode = False
1597
1598 #
1599 # -s is a temporary option dedicated for building .UNI files with ISO 639-2 language codes of EDK Shell in EDK2
1600 #
1601 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-s') > -1:
1602 if CompatibleMode:
1603 EdkLogger.error("build", AUTOGEN_ERROR,
1604 "-c and -s build options should be used exclusively",
1605 ExtraData="[%s]" % str(Info))
1606 ShellMode = True
1607 else:
1608 ShellMode = False
1609
1610 #RFC4646 is only for EDKII modules and ISO639-2 for EDK modules
1611 if EDK2Module:
1612 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.RFCLanguages]
1613 else:
1614 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.ISOLanguages]
1615 Header, Code = GetStringFiles(Info.UnicodeFileList, SrcList, IncList, Info.IncludePathList, ['.uni', '.inf'], Info.Name, CompatibleMode, ShellMode, UniGenCFlag, UniGenBinBuffer, FilterInfo)
1616 if CompatibleMode or UniGenCFlag:
1617 AutoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
1618 AutoGenC.Append(Code)
1619 AutoGenC.Append("\n")
1620 AutoGenH.Append("\n//\n//Unicode String ID\n//\n")
1621 AutoGenH.Append(Header)
1622 if CompatibleMode or UniGenCFlag:
1623 AutoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % Info.Name)
1624 os.chdir(WorkingDir)
1625
1626 def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGenCFlag, IdfGenBinBuffer):
1627 if len(Info.IdfFileList) > 0:
1628 ImageFiles = IdfFileClassObject(sorted (Info.IdfFileList))
1629 if ImageFiles.ImageFilesDict:
1630 Index = 1
1631 PaletteIndex = 1
1632 IncList = [Info.MetaFile.Dir]
1633 SrcList = [F for F in Info.SourceFileList]
1634 SkipList = ['.jpg', '.png', '.bmp', '.inf', '.idf']
1635 FileList = GetFileList(SrcList, IncList, SkipList)
1636 ValueStartPtr = 60
1637 StringH.Append("\n//\n//Image ID\n//\n")
1638 ImageInfoOffset = 0
1639 PaletteInfoOffset = 0
1640 ImageBuffer = pack('x')
1641 PaletteBuffer = pack('x')
1642 BufferStr = ''
1643 PaletteStr = ''
1644 FileDict = {}
1645 for Idf in ImageFiles.ImageFilesDict:
1646 if ImageFiles.ImageFilesDict[Idf]:
1647 for FileObj in ImageFiles.ImageFilesDict[Idf]:
1648 for sourcefile in Info.SourceFileList:
1649 if FileObj.FileName == sourcefile.File:
1650 if not sourcefile.Ext.upper() in ['.PNG', '.BMP', '.JPG']:
1651 EdkLogger.error("build", AUTOGEN_ERROR, "The %s's postfix must be one of .bmp, .jpg, .png" % (FileObj.FileName), ExtraData="[%s]" % str(Info))
1652 FileObj.File = sourcefile
1653 break
1654 else:
1655 EdkLogger.error("build", AUTOGEN_ERROR, "The %s in %s is not defined in the driver's [Sources] section" % (FileObj.FileName, Idf), ExtraData="[%s]" % str(Info))
1656
1657 for FileObj in ImageFiles.ImageFilesDict[Idf]:
1658 ID = FileObj.ImageID
1659 File = FileObj.File
1660 if not os.path.exists(File.Path) or not os.path.isfile(File.Path):
1661 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=File.Path)
1662 SearchImageID (FileObj, FileList)
1663 if FileObj.Referenced:
1664 if (ValueStartPtr - len(DEFINE_STR + ID)) <= 0:
1665 Line = DEFINE_STR + ' ' + ID + ' ' + DecToHexStr(Index, 4) + '\n'
1666 else:
1667 Line = DEFINE_STR + ' ' + ID + ' ' * (ValueStartPtr - len(DEFINE_STR + ID)) + DecToHexStr(Index, 4) + '\n'
1668
1669 if File not in FileDict:
1670 FileDict[File] = Index
1671 else:
1672 DuplicateBlock = pack('B', EFI_HII_IIBT_DUPLICATE)
1673 DuplicateBlock += pack('H', FileDict[File])
1674 ImageBuffer += DuplicateBlock
1675 BufferStr = WriteLine(BufferStr, '// %s: %s: %s' % (DecToHexStr(Index, 4), ID, DecToHexStr(Index, 4)))
1676 TempBufferList = AscToHexList(DuplicateBlock)
1677 BufferStr = WriteLine(BufferStr, CreateArrayItem(TempBufferList, 16) + '\n')
1678 StringH.Append(Line)
1679 Index += 1
1680 continue
1681
1682 TmpFile = open(File.Path, 'rb')
1683 Buffer = TmpFile.read()
1684 TmpFile.close()
1685 if File.Ext.upper() == '.PNG':
1686 TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_PNG)
1687 TempBuffer += pack('I', len(Buffer))
1688 TempBuffer += Buffer
1689 elif File.Ext.upper() == '.JPG':
1690 ImageType, = struct.unpack('4s', Buffer[6:10])
1691 if ImageType != 'JFIF':
1692 EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard JPG file." % File.Path)
1693 TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_JPEG)
1694 TempBuffer += pack('I', len(Buffer))
1695 TempBuffer += Buffer
1696 elif File.Ext.upper() == '.BMP':
1697 TempBuffer, TempPalette = BmpImageDecoder(File, Buffer, PaletteIndex, FileObj.TransParent)
1698 if len(TempPalette) > 1:
1699 PaletteIndex += 1
1700 NewPalette = pack('H', len(TempPalette))
1701 NewPalette += TempPalette
1702 PaletteBuffer += NewPalette
1703 PaletteStr = WriteLine(PaletteStr, '// %s: %s: %s' % (DecToHexStr(PaletteIndex - 1, 4), ID, DecToHexStr(PaletteIndex - 1, 4)))
1704 TempPaletteList = AscToHexList(NewPalette)
1705 PaletteStr = WriteLine(PaletteStr, CreateArrayItem(TempPaletteList, 16) + '\n')
1706 ImageBuffer += TempBuffer
1707 BufferStr = WriteLine(BufferStr, '// %s: %s: %s' % (DecToHexStr(Index, 4), ID, DecToHexStr(Index, 4)))
1708 TempBufferList = AscToHexList(TempBuffer)
1709 BufferStr = WriteLine(BufferStr, CreateArrayItem(TempBufferList, 16) + '\n')
1710
1711 StringH.Append(Line)
1712 Index += 1
1713
1714 BufferStr = WriteLine(BufferStr, '// End of the Image Info')
1715 BufferStr = WriteLine(BufferStr, CreateArrayItem(DecToHexList(EFI_HII_IIBT_END, 2)) + '\n')
1716 ImageEnd = pack('B', EFI_HII_IIBT_END)
1717 ImageBuffer += ImageEnd
1718
1719 if len(ImageBuffer) > 1:
1720 ImageInfoOffset = 12
1721 if len(PaletteBuffer) > 1:
1722 PaletteInfoOffset = 12 + len(ImageBuffer) - 1 # -1 is for the first empty pad byte of ImageBuffer
1723
1724 IMAGE_PACKAGE_HDR = pack('=II', ImageInfoOffset, PaletteInfoOffset)
1725 # PACKAGE_HEADER_Length = PACKAGE_HEADER + ImageInfoOffset + PaletteInfoOffset + ImageBuffer Length + PaletteCount + PaletteBuffer Length
1726 if len(PaletteBuffer) > 1:
1727 PACKAGE_HEADER_Length = 4 + 4 + 4 + len(ImageBuffer) - 1 + 2 + len(PaletteBuffer) - 1
1728 else:
1729 PACKAGE_HEADER_Length = 4 + 4 + 4 + len(ImageBuffer) - 1
1730 if PaletteIndex > 1:
1731 PALETTE_INFO_HEADER = pack('H', PaletteIndex - 1)
1732 # EFI_HII_PACKAGE_HEADER length max value is 0xFFFFFF
1733 Hex_Length = '%06X' % PACKAGE_HEADER_Length
1734 if PACKAGE_HEADER_Length > 0xFFFFFF:
1735 EdkLogger.error("build", AUTOGEN_ERROR, "The Length of EFI_HII_PACKAGE_HEADER exceed its maximum value", ExtraData="[%s]" % str(Info))
1736 PACKAGE_HEADER = pack('=HBB', int('0x' + Hex_Length[2:], 16), int('0x' + Hex_Length[0:2], 16), EFI_HII_PACKAGE_IMAGES)
1737
1738 IdfGenBinBuffer.write(PACKAGE_HEADER)
1739 IdfGenBinBuffer.write(IMAGE_PACKAGE_HDR)
1740 if len(ImageBuffer) > 1 :
1741 IdfGenBinBuffer.write(ImageBuffer[1:])
1742 if PaletteIndex > 1:
1743 IdfGenBinBuffer.write(PALETTE_INFO_HEADER)
1744 if len(PaletteBuffer) > 1:
1745 IdfGenBinBuffer.write(PaletteBuffer[1:])
1746
1747 if IdfGenCFlag:
1748 TotalLength = EFI_HII_ARRAY_SIZE_LENGTH + PACKAGE_HEADER_Length
1749 AutoGenC.Append("\n//\n//Image Pack Definition\n//\n")
1750 AllStr = WriteLine('', CHAR_ARRAY_DEFIN + ' ' + Info.Module.BaseName + 'Images' + '[] = {\n')
1751 AllStr = WriteLine(AllStr, '// STRGATHER_OUTPUT_HEADER')
1752 AllStr = WriteLine(AllStr, CreateArrayItem(DecToHexList(TotalLength)) + '\n')
1753 AllStr = WriteLine(AllStr, '// Image PACKAGE HEADER\n')
1754 IMAGE_PACKAGE_HDR_List = AscToHexList(PACKAGE_HEADER)
1755 IMAGE_PACKAGE_HDR_List += AscToHexList(IMAGE_PACKAGE_HDR)
1756 AllStr = WriteLine(AllStr, CreateArrayItem(IMAGE_PACKAGE_HDR_List, 16) + '\n')
1757 AllStr = WriteLine(AllStr, '// Image DATA\n')
1758 if BufferStr:
1759 AllStr = WriteLine(AllStr, BufferStr)
1760 if PaletteStr:
1761 AllStr = WriteLine(AllStr, '// Palette Header\n')
1762 PALETTE_INFO_HEADER_List = AscToHexList(PALETTE_INFO_HEADER)
1763 AllStr = WriteLine(AllStr, CreateArrayItem(PALETTE_INFO_HEADER_List, 16) + '\n')
1764 AllStr = WriteLine(AllStr, '// Palette Data\n')
1765 AllStr = WriteLine(AllStr, PaletteStr)
1766 AllStr = WriteLine(AllStr, '};')
1767 AutoGenC.Append(AllStr)
1768 AutoGenC.Append("\n")
1769 StringH.Append('\nextern unsigned char ' + Info.Module.BaseName + 'Images[];\n')
1770 StringH.Append("\n#define IMAGE_ARRAY_NAME %sImages\n" % Info.Module.BaseName)
1771
1772 # typedef struct _EFI_HII_IMAGE_PACKAGE_HDR {
1773 # EFI_HII_PACKAGE_HEADER Header; # Standard package header, where Header.Type = EFI_HII_PACKAGE_IMAGES
1774 # UINT32 ImageInfoOffset;
1775 # UINT32 PaletteInfoOffset;
1776 # } EFI_HII_IMAGE_PACKAGE_HDR;
1777
1778 # typedef struct {
1779 # UINT32 Length:24;
1780 # UINT32 Type:8;
1781 # UINT8 Data[];
1782 # } EFI_HII_PACKAGE_HEADER;
1783
1784 # typedef struct _EFI_HII_IMAGE_BLOCK {
1785 # UINT8 BlockType;
1786 # UINT8 BlockBody[];
1787 # } EFI_HII_IMAGE_BLOCK;
1788
1789 def BmpImageDecoder(File, Buffer, PaletteIndex, TransParent):
1790 ImageType, = struct.unpack('2s', Buffer[0:2])
1791 if ImageType!= 'BM': # BMP file type is 'BM'
1792 EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard BMP file." % File.Path)
1793 BMP_IMAGE_HEADER = collections.namedtuple('BMP_IMAGE_HEADER', ['bfSize','bfReserved1','bfReserved2','bfOffBits','biSize','biWidth','biHeight','biPlanes','biBitCount', 'biCompression', 'biSizeImage','biXPelsPerMeter','biYPelsPerMeter','biClrUsed','biClrImportant'])
1794 BMP_IMAGE_HEADER_STRUCT = struct.Struct('IHHIIIIHHIIIIII')
1795 BmpHeader = BMP_IMAGE_HEADER._make(BMP_IMAGE_HEADER_STRUCT.unpack_from(Buffer[2:]))
1796 #
1797 # Doesn't support compress.
1798 #
1799 if BmpHeader.biCompression != 0:
1800 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The compress BMP file %s is not support." % File.Path)
1801
1802 # The Width and Height is UINT16 type in Image Package
1803 if BmpHeader.biWidth > 0xFFFF:
1804 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The BMP file %s Width is exceed 0xFFFF." % File.Path)
1805 if BmpHeader.biHeight > 0xFFFF:
1806 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The BMP file %s Height is exceed 0xFFFF." % File.Path)
1807
1808 PaletteBuffer = pack('x')
1809 if BmpHeader.biBitCount == 1:
1810 if TransParent:
1811 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_1BIT_TRANS)
1812 else:
1813 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_1BIT)
1814 ImageBuffer += pack('B', PaletteIndex)
1815 Width = (BmpHeader.biWidth + 7)/8
1816 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1817 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1818 elif BmpHeader.biBitCount == 4:
1819 if TransParent:
1820 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_4BIT_TRANS)
1821 else:
1822 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_4BIT)
1823 ImageBuffer += pack('B', PaletteIndex)
1824 Width = (BmpHeader.biWidth + 1)/2
1825 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1826 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1827 elif BmpHeader.biBitCount == 8:
1828 if TransParent:
1829 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_8BIT_TRANS)
1830 else:
1831 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_8BIT)
1832 ImageBuffer += pack('B', PaletteIndex)
1833 Width = BmpHeader.biWidth
1834 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1835 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1836 elif BmpHeader.biBitCount == 24:
1837 if TransParent:
1838 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_24BIT_TRANS)
1839 else:
1840 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_24BIT)
1841 Width = BmpHeader.biWidth * 3
1842 else:
1843 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "Only support the 1 bit, 4 bit, 8bit, 24 bit BMP files.", ExtraData="[%s]" % str(File.Path))
1844
1845 ImageBuffer += pack('H', BmpHeader.biWidth)
1846 ImageBuffer += pack('H', BmpHeader.biHeight)
1847 Start = BmpHeader.bfOffBits
1848 End = BmpHeader.bfSize - 1
1849 for Height in range(0, BmpHeader.biHeight):
1850 if Width % 4 != 0:
1851 Start = End + (Width % 4) - 4 - Width
1852 else:
1853 Start = End - Width
1854 ImageBuffer += Buffer[Start + 1 : Start + Width + 1]
1855 End = Start
1856
1857 # handle the Palette info, BMP use 4 bytes for R, G, B and Reserved info while EFI_HII_RGB_PIXEL only have the R, G, B info
1858 if PaletteBuffer and len(PaletteBuffer) > 1:
1859 PaletteTemp = pack('x')
1860 for Index in range(0, len(PaletteBuffer)):
1861 if Index % 4 == 3:
1862 continue
1863 PaletteTemp += PaletteBuffer[Index]
1864 PaletteBuffer = PaletteTemp[1:]
1865 return ImageBuffer, PaletteBuffer
1866
1867 ## Create common code
1868 #
1869 # @param Info The ModuleAutoGen object
1870 # @param AutoGenC The TemplateString object for C code
1871 # @param AutoGenH The TemplateString object for header file
1872 #
1873 def CreateHeaderCode(Info, AutoGenC, AutoGenH):
1874 # file header
1875 AutoGenH.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.h'}))
1876 # header file Prologue
1877 AutoGenH.Append(gAutoGenHPrologueString.Replace({'File':'AUTOGENH','Guid':Info.Guid.replace('-','_')}))
1878 AutoGenH.Append(gAutoGenHCppPrologueString)
1879 if Info.AutoGenVersion >= 0x00010005:
1880 # header files includes
1881 AutoGenH.Append("#include <%s>\n" % gBasicHeaderFile)
1882 if Info.ModuleType in gModuleTypeHeaderFile \
1883 and gModuleTypeHeaderFile[Info.ModuleType][0] != gBasicHeaderFile:
1884 AutoGenH.Append("#include <%s>\n" % gModuleTypeHeaderFile[Info.ModuleType][0])
1885 #
1886 # if either PcdLib in [LibraryClasses] sections or there exist Pcd section, add PcdLib.h
1887 # As if modules only uses FixedPcd, then PcdLib is not needed in [LibraryClasses] section.
1888 #
1889 if 'PcdLib' in Info.Module.LibraryClasses or Info.Module.Pcds:
1890 AutoGenH.Append("#include <Library/PcdLib.h>\n")
1891
1892 AutoGenH.Append('\nextern GUID gEfiCallerIdGuid;')
1893 AutoGenH.Append('\nextern CHAR8 *gEfiCallerBaseName;\n\n')
1894
1895 if Info.IsLibrary:
1896 return
1897
1898 AutoGenH.Append("#define EFI_CALLER_ID_GUID \\\n %s\n" % GuidStringToGuidStructureString(Info.Guid))
1899
1900 if Info.IsLibrary:
1901 return
1902 # C file header
1903 AutoGenC.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.c'}))
1904 if Info.AutoGenVersion >= 0x00010005:
1905 # C file header files includes
1906 if Info.ModuleType in gModuleTypeHeaderFile:
1907 for Inc in gModuleTypeHeaderFile[Info.ModuleType]:
1908 AutoGenC.Append("#include <%s>\n" % Inc)
1909 else:
1910 AutoGenC.Append("#include <%s>\n" % gBasicHeaderFile)
1911
1912 #
1913 # Publish the CallerId Guid
1914 #
1915 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(Info.Guid))
1916 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *gEfiCallerBaseName = "%s";\n' % Info.Name)
1917
1918 ## Create common code for header file
1919 #
1920 # @param Info The ModuleAutoGen object
1921 # @param AutoGenC The TemplateString object for C code
1922 # @param AutoGenH The TemplateString object for header file
1923 #
1924 def CreateFooterCode(Info, AutoGenC, AutoGenH):
1925 AutoGenH.Append(gAutoGenHEpilogueString)
1926
1927 ## Create code for a module
1928 #
1929 # @param Info The ModuleAutoGen object
1930 # @param AutoGenC The TemplateString object for C code
1931 # @param AutoGenH The TemplateString object for header file
1932 # @param StringH The TemplateString object for header file
1933 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
1934 # @param UniGenBinBuffer Buffer to store uni string package data
1935 # @param StringIdf The TemplateString object for header file
1936 # @param IdfGenCFlag IdfString is generated into AutoGen C file when it is set to True
1937 # @param IdfGenBinBuffer Buffer to store Idf string package data
1938 #
1939 def CreateCode(Info, AutoGenC, AutoGenH, StringH, UniGenCFlag, UniGenBinBuffer, StringIdf, IdfGenCFlag, IdfGenBinBuffer):
1940 CreateHeaderCode(Info, AutoGenC, AutoGenH)
1941
1942 if Info.AutoGenVersion >= 0x00010005:
1943 CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH)
1944 CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH)
1945 CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH)
1946 CreatePcdCode(Info, AutoGenC, AutoGenH)
1947 CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH)
1948 CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH)
1949 CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH)
1950 CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH)
1951
1952 if Info.UnicodeFileList:
1953 FileName = "%sStrDefs.h" % Info.Name
1954 StringH.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
1955 StringH.Append(gAutoGenHPrologueString.Replace({'File':'STRDEFS', 'Guid':Info.Guid.replace('-','_')}))
1956 CreateUnicodeStringCode(Info, AutoGenC, StringH, UniGenCFlag, UniGenBinBuffer)
1957
1958 GuidMacros = []
1959 for Guid in Info.Module.Guids:
1960 if Guid in Info.Module.GetGuidsUsedByPcd():
1961 continue
1962 GuidMacros.append('#define %s %s' % (Guid, Info.Module.Guids[Guid]))
1963 for Guid, Value in Info.Module.Protocols.items() + Info.Module.Ppis.items():
1964 GuidMacros.append('#define %s %s' % (Guid, Value))
1965 # supports FixedAtBuild usage in VFR file
1966 if Info.VfrFileList and Info.ModulePcdList:
1967 GuidMacros.append('#define %s %s' % ('FixedPcdGetBool(TokenName)', '_PCD_VALUE_##TokenName'))
1968 GuidMacros.append('#define %s %s' % ('FixedPcdGet8(TokenName)', '_PCD_VALUE_##TokenName'))
1969 GuidMacros.append('#define %s %s' % ('FixedPcdGet16(TokenName)', '_PCD_VALUE_##TokenName'))
1970 GuidMacros.append('#define %s %s' % ('FixedPcdGet32(TokenName)', '_PCD_VALUE_##TokenName'))
1971 GuidMacros.append('#define %s %s' % ('FixedPcdGet64(TokenName)', '_PCD_VALUE_##TokenName'))
1972 for Pcd in Info.ModulePcdList:
1973 if Pcd.Type == TAB_PCDS_FIXED_AT_BUILD:
1974 TokenCName = Pcd.TokenCName
1975 Value = Pcd.DefaultValue
1976 if Pcd.DatumType == 'BOOLEAN':
1977 BoolValue = Value.upper()
1978 if BoolValue == 'TRUE':
1979 Value = '1'
1980 elif BoolValue == 'FALSE':
1981 Value = '0'
1982 for PcdItem in GlobalData.MixedPcd:
1983 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
1984 TokenCName = PcdItem[0]
1985 break
1986 GuidMacros.append('#define %s %s' % ('_PCD_VALUE_'+TokenCName, Value))
1987
1988 if Info.IdfFileList:
1989 GuidMacros.append('#include "%sImgDefs.h"' % Info.Name)
1990
1991 if GuidMacros:
1992 StringH.Append('\n#ifdef VFRCOMPILE\n%s\n#endif\n' % '\n'.join(GuidMacros))
1993
1994 StringH.Append("\n#endif\n")
1995 AutoGenH.Append('#include "%s"\n' % FileName)
1996
1997 if Info.IdfFileList:
1998 FileName = "%sImgDefs.h" % Info.Name
1999 StringIdf.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
2000 StringIdf.Append(gAutoGenHPrologueString.Replace({'File':'IMAGEDEFS', 'Guid':Info.Guid.replace('-','_')}))
2001 CreateIdfFileCode(Info, AutoGenC, StringIdf, IdfGenCFlag, IdfGenBinBuffer)
2002
2003 StringIdf.Append("\n#endif\n")
2004 AutoGenH.Append('#include "%s"\n' % FileName)
2005
2006 CreateFooterCode(Info, AutoGenC, AutoGenH)
2007
2008 # no generation of AutoGen.c for Edk modules without unicode file
2009 if Info.AutoGenVersion < 0x00010005 and len(Info.UnicodeFileList) == 0:
2010 AutoGenC.String = ''
2011
2012 ## Create the code file
2013 #
2014 # @param FilePath The path of code file
2015 # @param Content The content of code file
2016 # @param IsBinaryFile The flag indicating if the file is binary file or not
2017 #
2018 # @retval True If file content is changed or file doesn't exist
2019 # @retval False If the file exists and the content is not changed
2020 #
2021 def Generate(FilePath, Content, IsBinaryFile):
2022 return SaveFileOnChange(FilePath, Content, IsBinaryFile)
2023