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