BaseTools: Fix a bug for VOID* type Fixatbuild Pcd in Library
[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 _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 = []
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.append(TokenCName)
840
841 TokenCNameList = []
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.append(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 FixPcdSizeTokenName = '_PCD_SIZE_' + TokenCName
920 FixedPcdSizeVariableName = '_gPcd_FixedAtBuild_Size_' + TokenCName
921
922 if Pcd.PcdValueFromComm:
923 Pcd.DefaultValue = Pcd.PcdValueFromComm
924
925 if Pcd.Type in gDynamicExPcd:
926 TokenNumber = int(Pcd.TokenValue, 0)
927 # Add TokenSpaceGuidValue value to PcdTokenName to discriminate the DynamicEx PCDs with
928 # different Guids but same TokenCName
929 PcdExTokenName = '_PCD_TOKEN_' + Pcd.TokenSpaceGuidCName + '_' + TokenCName
930 AutoGenH.Append('\n#define %s %dU\n' % (PcdExTokenName, TokenNumber))
931 else:
932 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
933 # If one of the Source built modules listed in the DSC is not listed in FDF modules,
934 # and the INF lists a PCD can only use the PcdsDynamic access method (it is only
935 # listed in the DEC file that declares the PCD as PcdsDynamic), then build tool will
936 # report warning message notify the PI that they are attempting to build a module
937 # that must be included in a flash image in order to be functional. These Dynamic PCD
938 # will not be added into the Database unless it is used by other modules that are
939 # included in the FDF file.
940 # In this case, just assign an invalid token number to make it pass build.
941 if Pcd.Type in PCD_DYNAMIC_TYPE_LIST:
942 TokenNumber = 0
943 else:
944 EdkLogger.error("build", AUTOGEN_ERROR,
945 "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, TokenCName),
946 ExtraData="[%s]" % str(Info))
947 else:
948 TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
949 AutoGenH.Append('\n#define %s %dU\n' % (PcdTokenName, TokenNumber))
950
951 EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for " + TokenCName + "." + Pcd.TokenSpaceGuidCName)
952 if Pcd.Type not in gItemTypeStringDatabase:
953 EdkLogger.error("build", AUTOGEN_ERROR,
954 "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, TokenCName),
955 ExtraData="[%s]" % str(Info))
956
957 DatumSize = gDatumSizeStringDatabase[Pcd.DatumType] if Pcd.DatumType in gDatumSizeStringDatabase else gDatumSizeStringDatabase['VOID*']
958 DatumSizeLib = gDatumSizeStringDatabaseLib[Pcd.DatumType] if Pcd.DatumType in gDatumSizeStringDatabaseLib else gDatumSizeStringDatabaseLib['VOID*']
959 GetModeName = '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + TokenCName if Pcd.DatumType in gDatumSizeStringDatabaseH else '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH['VOID*'] + '_' + TokenCName
960 SetModeName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + TokenCName if Pcd.DatumType in gDatumSizeStringDatabaseH else '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH['VOID*'] + '_' + TokenCName
961 SetModeStatusName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_S_' + TokenCName if Pcd.DatumType in gDatumSizeStringDatabaseH else '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH['VOID*'] + '_S_' + TokenCName
962 GetModeSizeName = '_PCD_GET_MODE_SIZE' + '_' + TokenCName
963
964 PcdExCNameList = []
965 if Pcd.Type in gDynamicExPcd:
966 if Info.IsLibrary:
967 PcdList = Info.LibraryPcdList
968 else:
969 PcdList = Info.ModulePcdList
970 for PcdModule in PcdList:
971 if PcdModule.Type in gDynamicExPcd:
972 PcdExCNameList.append(PcdModule.TokenCName)
973 # Be compatible with the current code which using PcdToken and PcdGet/Set for DynamicEx Pcd.
974 # If only PcdToken and PcdGet/Set used in all Pcds with different CName, it should succeed to build.
975 # If PcdToken and PcdGet/Set used in the Pcds with different Guids but same CName, it should failed to build.
976 if PcdExCNameList.count(Pcd.TokenCName) > 1:
977 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')
978 AutoGenH.Append('// #define %s %s\n' % (PcdTokenName, PcdExTokenName))
979 AutoGenH.Append('// #define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
980 AutoGenH.Append('// #define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
981 if Pcd.DatumType not in _NumericDataTypesList:
982 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
983 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
984 else:
985 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
986 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
987 else:
988 AutoGenH.Append('#define %s %s\n' % (PcdTokenName, PcdExTokenName))
989 AutoGenH.Append('#define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
990 AutoGenH.Append('#define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
991 if Pcd.DatumType not in _NumericDataTypesList:
992 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
993 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
994 else:
995 AutoGenH.Append('#define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
996 AutoGenH.Append('#define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
997 elif Pcd.Type in gDynamicPcd:
998 PcdList = []
999 PcdCNameList = []
1000 PcdList.extend(Info.LibraryPcdList)
1001 PcdList.extend(Info.ModulePcdList)
1002 for PcdModule in PcdList:
1003 if PcdModule.Type in gDynamicPcd:
1004 PcdCNameList.append(PcdModule.TokenCName)
1005 if PcdCNameList.count(Pcd.TokenCName) > 1:
1006 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))
1007 else:
1008 AutoGenH.Append('#define %s LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
1009 AutoGenH.Append('#define %s LibPcdGetSize(%s)\n' % (GetModeSizeName, PcdTokenName))
1010 if Pcd.DatumType not in _NumericDataTypesList:
1011 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
1012 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%sS(%s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
1013 else:
1014 AutoGenH.Append('#define %s(Value) LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
1015 AutoGenH.Append('#define %s(Value) LibPcdSet%sS(%s, (Value))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
1016 else:
1017 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + TokenCName
1018 Const = 'const'
1019 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1020 Const = ''
1021 Type = ''
1022 Array = ''
1023 Value = Pcd.DefaultValue
1024 Unicode = False
1025 ValueNumber = 0
1026
1027 if Pcd.DatumType == 'BOOLEAN':
1028 BoolValue = Value.upper()
1029 if BoolValue == 'TRUE' or BoolValue == '1':
1030 Value = '1U'
1031 elif BoolValue == 'FALSE' or BoolValue == '0':
1032 Value = '0U'
1033
1034 if Pcd.DatumType in ['UINT64', 'UINT32', 'UINT16', 'UINT8']:
1035 try:
1036 if Value.upper().endswith('L'):
1037 Value = Value[:-1]
1038 ValueNumber = int (Value, 0)
1039 except:
1040 EdkLogger.error("build", AUTOGEN_ERROR,
1041 "PCD value is not valid dec or hex number for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1042 ExtraData="[%s]" % str(Info))
1043 if Pcd.DatumType == 'UINT64':
1044 if ValueNumber < 0:
1045 EdkLogger.error("build", AUTOGEN_ERROR,
1046 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1047 ExtraData="[%s]" % str(Info))
1048 elif ValueNumber >= 0x10000000000000000:
1049 EdkLogger.error("build", AUTOGEN_ERROR,
1050 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1051 ExtraData="[%s]" % str(Info))
1052 if not Value.endswith('ULL'):
1053 Value += 'ULL'
1054 elif Pcd.DatumType == 'UINT32':
1055 if ValueNumber < 0:
1056 EdkLogger.error("build", AUTOGEN_ERROR,
1057 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1058 ExtraData="[%s]" % str(Info))
1059 elif ValueNumber >= 0x100000000:
1060 EdkLogger.error("build", AUTOGEN_ERROR,
1061 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1062 ExtraData="[%s]" % str(Info))
1063 if not Value.endswith('U'):
1064 Value += 'U'
1065 elif Pcd.DatumType == 'UINT16':
1066 if ValueNumber < 0:
1067 EdkLogger.error("build", AUTOGEN_ERROR,
1068 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1069 ExtraData="[%s]" % str(Info))
1070 elif ValueNumber >= 0x10000:
1071 EdkLogger.error("build", AUTOGEN_ERROR,
1072 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1073 ExtraData="[%s]" % str(Info))
1074 if not Value.endswith('U'):
1075 Value += 'U'
1076 elif Pcd.DatumType == 'UINT8':
1077 if ValueNumber < 0:
1078 EdkLogger.error("build", AUTOGEN_ERROR,
1079 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1080 ExtraData="[%s]" % str(Info))
1081 elif ValueNumber >= 0x100:
1082 EdkLogger.error("build", AUTOGEN_ERROR,
1083 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, TokenCName),
1084 ExtraData="[%s]" % str(Info))
1085 if not Value.endswith('U'):
1086 Value += 'U'
1087 if Pcd.DatumType not in _NumericDataTypesList:
1088 if Pcd.MaxDatumSize is None or Pcd.MaxDatumSize == '':
1089 EdkLogger.error("build", AUTOGEN_ERROR,
1090 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, TokenCName),
1091 ExtraData="[%s]" % str(Info))
1092
1093 ArraySize = int(Pcd.MaxDatumSize, 0)
1094 if Value[0] == '{':
1095 Type = '(VOID *)'
1096 else:
1097 if Value[0] == 'L':
1098 Unicode = True
1099 Value = Value.lstrip('L') #.strip('"')
1100 Value = eval(Value) # translate escape character
1101 NewValue = '{'
1102 for Index in range(0,len(Value)):
1103 if Unicode:
1104 NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ', '
1105 else:
1106 NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
1107 if Unicode:
1108 ArraySize = ArraySize / 2;
1109
1110 if ArraySize < (len(Value) + 1):
1111 EdkLogger.error("build", AUTOGEN_ERROR,
1112 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName),
1113 ExtraData="[%s]" % str(Info))
1114 Value = NewValue + '0 }'
1115 Array = '[%d]' % ArraySize
1116 #
1117 # skip casting for fixed at build since it breaks ARM assembly.
1118 # Long term we need PCD macros that work in assembly
1119 #
1120 elif Pcd.Type != TAB_PCDS_FIXED_AT_BUILD and Pcd.DatumType in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN', 'VOID*']:
1121 Value = "((%s)%s)" % (Pcd.DatumType, Value)
1122
1123 if Pcd.DatumType not in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN', 'VOID*']:
1124 # handle structure PCD
1125 if Pcd.MaxDatumSize is None or Pcd.MaxDatumSize == '':
1126 EdkLogger.error("build", AUTOGEN_ERROR,
1127 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, TokenCName),
1128 ExtraData="[%s]" % str(Info))
1129
1130 ArraySize = int(Pcd.MaxDatumSize, 0)
1131 Array = '[%d]' % ArraySize
1132
1133 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1134 PcdValueName = '_PCD_PATCHABLE_VALUE_' + TokenCName
1135 else:
1136 PcdValueName = '_PCD_VALUE_' + TokenCName
1137
1138 if Pcd.DatumType not in _NumericDataTypesList:
1139 #
1140 # For unicode, UINT16 array will be generated, so the alignment of unicode is guaranteed.
1141 #
1142 AutoGenH.Append('#define %s %s%s\n' %(PcdValueName, Type, PcdVariableName))
1143 if Unicode:
1144 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT16 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
1145 AutoGenH.Append('extern %s UINT16 %s%s;\n' %(Const, PcdVariableName, Array))
1146 else:
1147 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
1148 AutoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
1149 AutoGenH.Append('#define %s %s%s\n' %(GetModeName, Type, PcdVariableName))
1150
1151 PcdDataSize = GetPcdSize(Pcd)
1152 if Pcd.Type == TAB_PCDS_FIXED_AT_BUILD:
1153 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1154 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,FixPcdSizeTokenName))
1155 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED const UINTN %s = %s;\n' % (FixedPcdSizeVariableName,PcdDataSize))
1156 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1157 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, Pcd.MaxDatumSize))
1158 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,PatchPcdSizeVariableName))
1159 AutoGenH.Append('extern UINTN %s; \n' % PatchPcdSizeVariableName)
1160 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED UINTN %s = %s;\n' % (PatchPcdSizeVariableName,PcdDataSize))
1161 elif Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1162 AutoGenH.Append('#define %s %s\n' %(PcdValueName, Value))
1163 AutoGenC.Append('volatile %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
1164 AutoGenH.Append('extern volatile %s %s %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
1165 AutoGenH.Append('#define %s %s%s\n' % (GetModeName, Type, PcdVariableName))
1166
1167 PcdDataSize = GetPcdSize(Pcd)
1168 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, PcdDataSize))
1169
1170 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,PatchPcdSizeVariableName))
1171 AutoGenH.Append('extern UINTN %s; \n' % PatchPcdSizeVariableName)
1172 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED UINTN %s = %s;\n' % (PatchPcdSizeVariableName,PcdDataSize))
1173 else:
1174 PcdDataSize = GetPcdSize(Pcd)
1175 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1176 AutoGenH.Append('#define %s %s \n' % (GetModeSizeName,FixPcdSizeTokenName))
1177
1178 AutoGenH.Append('#define %s %s\n' %(PcdValueName, Value))
1179 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
1180 AutoGenH.Append('extern %s %s %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
1181 AutoGenH.Append('#define %s %s%s\n' % (GetModeName, Type, PcdVariableName))
1182
1183 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1184 if Pcd.DatumType not in _NumericDataTypesList:
1185 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))
1186 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))
1187 else:
1188 AutoGenH.Append('#define %s(Value) (%s = (Value))\n' % (SetModeName, PcdVariableName))
1189 AutoGenH.Append('#define %s(Value) ((%s = (Value)), RETURN_SUCCESS) \n' % (SetModeStatusName, PcdVariableName))
1190 else:
1191 AutoGenH.Append('//#define %s ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)
1192
1193 ## Create code for library module PCDs
1194 #
1195 # @param Info The ModuleAutoGen object
1196 # @param AutoGenC The TemplateString object for C code
1197 # @param AutoGenH The TemplateString object for header file
1198 # @param Pcd The PCD object
1199 #
1200 def CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd):
1201 PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
1202 TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1203 TokenCName = Pcd.TokenCName
1204 for PcdItem in GlobalData.MixedPcd:
1205 if (TokenCName, TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
1206 TokenCName = PcdItem[0]
1207 break
1208 PcdTokenName = '_PCD_TOKEN_' + TokenCName
1209 FixPcdSizeTokenName = '_PCD_SIZE_' + TokenCName
1210 PatchPcdSizeTokenName = '_PCD_PATCHABLE_' + TokenCName +'_SIZE'
1211 PatchPcdSizeVariableName = '_gPcd_BinaryPatch_Size_' + TokenCName
1212 FixedPcdSizeVariableName = '_gPcd_FixedAtBuild_Size_' + TokenCName
1213
1214 if Pcd.PcdValueFromComm:
1215 Pcd.DefaultValue = Pcd.PcdValueFromComm
1216 #
1217 # Write PCDs
1218 #
1219 if Pcd.Type in gDynamicExPcd:
1220 TokenNumber = int(Pcd.TokenValue, 0)
1221 else:
1222 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
1223 # If one of the Source built modules listed in the DSC is not listed in FDF modules,
1224 # and the INF lists a PCD can only use the PcdsDynamic access method (it is only
1225 # listed in the DEC file that declares the PCD as PcdsDynamic), then build tool will
1226 # report warning message notify the PI that they are attempting to build a module
1227 # that must be included in a flash image in order to be functional. These Dynamic PCD
1228 # will not be added into the Database unless it is used by other modules that are
1229 # included in the FDF file.
1230 # In this case, just assign an invalid token number to make it pass build.
1231 if Pcd.Type in PCD_DYNAMIC_TYPE_LIST:
1232 TokenNumber = 0
1233 else:
1234 EdkLogger.error("build", AUTOGEN_ERROR,
1235 "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, TokenCName),
1236 ExtraData="[%s]" % str(Info))
1237 else:
1238 TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
1239
1240 if Pcd.Type not in gItemTypeStringDatabase:
1241 EdkLogger.error("build", AUTOGEN_ERROR,
1242 "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, TokenCName),
1243 ExtraData="[%s]" % str(Info))
1244
1245 DatumType = Pcd.DatumType
1246 DatumSize = gDatumSizeStringDatabase[Pcd.DatumType] if Pcd.DatumType in gDatumSizeStringDatabase else gDatumSizeStringDatabase['VOID*']
1247 DatumSizeLib = gDatumSizeStringDatabaseLib[Pcd.DatumType] if Pcd.DatumType in gDatumSizeStringDatabaseLib else gDatumSizeStringDatabaseLib['VOID*']
1248 GetModeName = '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + TokenCName if Pcd.DatumType in gDatumSizeStringDatabaseH else '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH['VOID*'] + '_' + TokenCName
1249 SetModeName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + TokenCName if Pcd.DatumType in gDatumSizeStringDatabaseH else '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH['VOID*'] + '_' + TokenCName
1250 SetModeStatusName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_S_' + TokenCName if Pcd.DatumType in gDatumSizeStringDatabaseH else '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH['VOID*'] + '_S_' + TokenCName
1251 GetModeSizeName = '_PCD_GET_MODE_SIZE' + '_' + TokenCName
1252
1253 Type = ''
1254 Array = ''
1255 if Pcd.DatumType not in _NumericDataTypesList:
1256 if Pcd.DefaultValue[0]== '{':
1257 Type = '(VOID *)'
1258 Array = '[]'
1259 PcdItemType = Pcd.Type
1260 PcdExCNameList = []
1261 if PcdItemType in gDynamicExPcd:
1262 PcdExTokenName = '_PCD_TOKEN_' + TokenSpaceGuidCName + '_' + TokenCName
1263 AutoGenH.Append('\n#define %s %dU\n' % (PcdExTokenName, TokenNumber))
1264
1265 if Info.IsLibrary:
1266 PcdList = Info.LibraryPcdList
1267 else:
1268 PcdList = Info.ModulePcdList
1269 for PcdModule in PcdList:
1270 if PcdModule.Type in gDynamicExPcd:
1271 PcdExCNameList.append(PcdModule.TokenCName)
1272 # Be compatible with the current code which using PcdGet/Set for DynamicEx Pcd.
1273 # If only PcdGet/Set used in all Pcds with different CName, it should succeed to build.
1274 # If PcdGet/Set used in the Pcds with different Guids but same CName, it should failed to build.
1275 if PcdExCNameList.count(Pcd.TokenCName) > 1:
1276 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')
1277 AutoGenH.Append('// #define %s %s\n' % (PcdTokenName, PcdExTokenName))
1278 AutoGenH.Append('// #define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1279 AutoGenH.Append('// #define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
1280 if Pcd.DatumType not in _NumericDataTypesList:
1281 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1282 AutoGenH.Append('// #define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1283 else:
1284 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1285 AutoGenH.Append('// #define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1286 else:
1287 AutoGenH.Append('#define %s %s\n' % (PcdTokenName, PcdExTokenName))
1288 AutoGenH.Append('#define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1289 AutoGenH.Append('#define %s LibPcdGetExSize(&%s, %s)\n' % (GetModeSizeName,Pcd.TokenSpaceGuidCName, PcdTokenName))
1290 if Pcd.DatumType not in _NumericDataTypesList:
1291 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1292 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%sS(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1293 else:
1294 AutoGenH.Append('#define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1295 AutoGenH.Append('#define %s(Value) LibPcdSetEx%sS(&%s, %s, (Value))\n' % (SetModeStatusName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
1296 else:
1297 AutoGenH.Append('#define _PCD_TOKEN_%s %dU\n' % (TokenCName, TokenNumber))
1298 if PcdItemType in gDynamicPcd:
1299 PcdList = []
1300 PcdCNameList = []
1301 PcdList.extend(Info.LibraryPcdList)
1302 PcdList.extend(Info.ModulePcdList)
1303 for PcdModule in PcdList:
1304 if PcdModule.Type in gDynamicPcd:
1305 PcdCNameList.append(PcdModule.TokenCName)
1306 if PcdCNameList.count(Pcd.TokenCName) > 1:
1307 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))
1308 else:
1309 AutoGenH.Append('#define %s LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
1310 AutoGenH.Append('#define %s LibPcdGetSize(%s)\n' % (GetModeSizeName, PcdTokenName))
1311 if DatumType not in _NumericDataTypesList:
1312 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
1313 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%sS(%s, (SizeOfBuffer), (Buffer))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
1314 else:
1315 AutoGenH.Append('#define %s(Value) LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
1316 AutoGenH.Append('#define %s(Value) LibPcdSet%sS(%s, (Value))\n' % (SetModeStatusName, DatumSizeLib, PcdTokenName))
1317 if PcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
1318 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + TokenCName
1319 if DatumType not in _NumericDataTypesList:
1320 ArraySize = int(Pcd.MaxDatumSize, 0)
1321 if Pcd.DefaultValue[0] == 'L':
1322 ArraySize = ArraySize / 2
1323 Array = '[%d]' % ArraySize
1324 DatumType = ['UINT8', 'UINT16'][Pcd.DefaultValue[0] == 'L']
1325 AutoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(DatumType, TokenCName, Array))
1326 else:
1327 AutoGenH.Append('extern volatile %s %s%s;\n' % (DatumType, PcdVariableName, Array))
1328 AutoGenH.Append('#define %s %s_gPcd_BinaryPatch_%s\n' %(GetModeName, Type, TokenCName))
1329 PcdDataSize = GetPcdSize(Pcd)
1330 if Pcd.DatumType not in _NumericDataTypesList:
1331 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))
1332 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))
1333 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, Pcd.MaxDatumSize))
1334 else:
1335 AutoGenH.Append('#define %s(Value) (%s = (Value))\n' % (SetModeName, PcdVariableName))
1336 AutoGenH.Append('#define %s(Value) ((%s = (Value)), RETURN_SUCCESS)\n' % (SetModeStatusName, PcdVariableName))
1337 AutoGenH.Append('#define %s %s\n' % (PatchPcdSizeTokenName, PcdDataSize))
1338
1339 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,PatchPcdSizeVariableName))
1340 AutoGenH.Append('extern UINTN %s; \n' % PatchPcdSizeVariableName)
1341
1342 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD or PcdItemType == TAB_PCDS_FEATURE_FLAG:
1343 key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))
1344 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + TokenCName
1345 if DatumType == 'VOID*' and Array == '[]':
1346 DatumType = ['UINT8', 'UINT16'][Pcd.DefaultValue[0] == 'L']
1347 if DatumType not in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'BOOLEAN', 'VOID*']:
1348 DatumType = 'UINT8'
1349 AutoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(DatumType, TokenCName, Array))
1350 AutoGenH.Append('#define %s %s_gPcd_FixedAtBuild_%s\n' %(GetModeName, Type, TokenCName))
1351 AutoGenH.Append('//#define %s ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)
1352
1353 ConstFixedPcd = False
1354 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD and (key in Info.ConstPcd or (Info.IsLibrary and not Info._ReferenceModules)):
1355 ConstFixedPcd = True
1356 if Pcd.DatumType not in _NumericDataTypesList:
1357 AutoGenH.Append('#define _PCD_VALUE_%s %s%s\n' %(TokenCName, Type, PcdVariableName))
1358 else:
1359 AutoGenH.Append('#define _PCD_VALUE_%s %s\n' %(TokenCName, Pcd.DefaultValue))
1360 PcdDataSize = GetPcdSize(Pcd)
1361 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD:
1362 if Pcd.DatumType not in _NumericDataTypesList:
1363 if ConstFixedPcd:
1364 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1365 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixPcdSizeTokenName))
1366 else:
1367 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixedPcdSizeVariableName))
1368 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName,FixedPcdSizeVariableName))
1369 AutoGenH.Append('extern const UINTN %s; \n' % FixedPcdSizeVariableName)
1370 else:
1371 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1372 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixPcdSizeTokenName))
1373
1374 ## Create code for library constructor
1375 #
1376 # @param Info The ModuleAutoGen object
1377 # @param AutoGenC The TemplateString object for C code
1378 # @param AutoGenH The TemplateString object for header file
1379 #
1380 def CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH):
1381 #
1382 # Library Constructors
1383 #
1384 ConstructorPrototypeString = TemplateString()
1385 ConstructorCallingString = TemplateString()
1386 if Info.IsLibrary:
1387 DependentLibraryList = [Info.Module]
1388 else:
1389 DependentLibraryList = Info.DependentLibraryList
1390 for Lib in DependentLibraryList:
1391 if len(Lib.ConstructorList) <= 0:
1392 continue
1393 Dict = {'Function':Lib.ConstructorList}
1394 if Lib.ModuleType in ['BASE', 'SEC']:
1395 ConstructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1396 ConstructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1397 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1398 ConstructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1399 ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1400 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1401 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1402 ConstructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1403 ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1404 elif Lib.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1405 ConstructorPrototypeString.Append(gLibraryStructorPrototype['MM'].Replace(Dict))
1406 ConstructorCallingString.Append(gLibraryStructorCall['MM'].Replace(Dict))
1407
1408 if str(ConstructorPrototypeString) == '':
1409 ConstructorPrototypeList = []
1410 else:
1411 ConstructorPrototypeList = [str(ConstructorPrototypeString)]
1412 if str(ConstructorCallingString) == '':
1413 ConstructorCallingList = []
1414 else:
1415 ConstructorCallingList = [str(ConstructorCallingString)]
1416
1417 Dict = {
1418 'Type' : 'Constructor',
1419 'FunctionPrototype' : ConstructorPrototypeList,
1420 'FunctionCall' : ConstructorCallingList
1421 }
1422 if Info.IsLibrary:
1423 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1424 else:
1425 if Info.ModuleType in ['BASE', 'SEC']:
1426 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1427 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1428 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1429 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1430 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1431 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1432 elif Info.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1433 AutoGenC.Append(gLibraryString['MM'].Replace(Dict))
1434
1435 ## Create code for library destructor
1436 #
1437 # @param Info The ModuleAutoGen object
1438 # @param AutoGenC The TemplateString object for C code
1439 # @param AutoGenH The TemplateString object for header file
1440 #
1441 def CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH):
1442 #
1443 # Library Destructors
1444 #
1445 DestructorPrototypeString = TemplateString()
1446 DestructorCallingString = TemplateString()
1447 if Info.IsLibrary:
1448 DependentLibraryList = [Info.Module]
1449 else:
1450 DependentLibraryList = Info.DependentLibraryList
1451 for Index in range(len(DependentLibraryList)-1, -1, -1):
1452 Lib = DependentLibraryList[Index]
1453 if len(Lib.DestructorList) <= 0:
1454 continue
1455 Dict = {'Function':Lib.DestructorList}
1456 if Lib.ModuleType in ['BASE', 'SEC']:
1457 DestructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1458 DestructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1459 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1460 DestructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1461 DestructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1462 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1463 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION', 'SMM_CORE']:
1464 DestructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1465 DestructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1466 elif Lib.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1467 DestructorPrototypeString.Append(gLibraryStructorPrototype['MM'].Replace(Dict))
1468 DestructorCallingString.Append(gLibraryStructorCall['MM'].Replace(Dict))
1469
1470 if str(DestructorPrototypeString) == '':
1471 DestructorPrototypeList = []
1472 else:
1473 DestructorPrototypeList = [str(DestructorPrototypeString)]
1474 if str(DestructorCallingString) == '':
1475 DestructorCallingList = []
1476 else:
1477 DestructorCallingList = [str(DestructorCallingString)]
1478
1479 Dict = {
1480 'Type' : 'Destructor',
1481 'FunctionPrototype' : DestructorPrototypeList,
1482 'FunctionCall' : DestructorCallingList
1483 }
1484 if Info.IsLibrary:
1485 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1486 else:
1487 if Info.ModuleType in ['BASE', 'SEC']:
1488 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1489 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1490 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1491 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1492 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1493 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1494 elif Info.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1495 AutoGenC.Append(gLibraryString['MM'].Replace(Dict))
1496
1497
1498 ## Create code for ModuleEntryPoint
1499 #
1500 # @param Info The ModuleAutoGen object
1501 # @param AutoGenC The TemplateString object for C code
1502 # @param AutoGenH The TemplateString object for header file
1503 #
1504 def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH):
1505 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1506 return
1507 #
1508 # Module Entry Points
1509 #
1510 NumEntryPoints = len(Info.Module.ModuleEntryPointList)
1511 if 'PI_SPECIFICATION_VERSION' in Info.Module.Specification:
1512 PiSpecVersion = Info.Module.Specification['PI_SPECIFICATION_VERSION']
1513 else:
1514 PiSpecVersion = '0x00000000'
1515 if 'UEFI_SPECIFICATION_VERSION' in Info.Module.Specification:
1516 UefiSpecVersion = Info.Module.Specification['UEFI_SPECIFICATION_VERSION']
1517 else:
1518 UefiSpecVersion = '0x00000000'
1519 Dict = {
1520 'Function' : Info.Module.ModuleEntryPointList,
1521 'PiSpecVersion' : PiSpecVersion + 'U',
1522 'UefiSpecVersion': UefiSpecVersion + 'U'
1523 }
1524
1525 if Info.ModuleType in ['PEI_CORE', 'DXE_CORE', 'SMM_CORE', 'MM_CORE_STANDALONE']:
1526 if Info.SourceFileList <> None and Info.SourceFileList <> []:
1527 if NumEntryPoints != 1:
1528 EdkLogger.error(
1529 "build",
1530 AUTOGEN_ERROR,
1531 '%s must have exactly one entry point' % Info.ModuleType,
1532 File=str(Info),
1533 ExtraData= ", ".join(Info.Module.ModuleEntryPointList)
1534 )
1535 if Info.ModuleType == 'PEI_CORE':
1536 AutoGenC.Append(gPeiCoreEntryPointString.Replace(Dict))
1537 AutoGenH.Append(gPeiCoreEntryPointPrototype.Replace(Dict))
1538 elif Info.ModuleType == 'DXE_CORE':
1539 AutoGenC.Append(gDxeCoreEntryPointString.Replace(Dict))
1540 AutoGenH.Append(gDxeCoreEntryPointPrototype.Replace(Dict))
1541 elif Info.ModuleType == 'SMM_CORE':
1542 AutoGenC.Append(gSmmCoreEntryPointString.Replace(Dict))
1543 AutoGenH.Append(gSmmCoreEntryPointPrototype.Replace(Dict))
1544 elif Info.ModuleType == 'MM_CORE_STANDALONE':
1545 AutoGenC.Append(gMmCoreStandaloneEntryPointString.Replace(Dict))
1546 AutoGenH.Append(gMmCoreStandaloneEntryPointPrototype.Replace(Dict))
1547 elif Info.ModuleType == 'PEIM':
1548 if NumEntryPoints < 2:
1549 AutoGenC.Append(gPeimEntryPointString[NumEntryPoints].Replace(Dict))
1550 else:
1551 AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict))
1552 AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict))
1553 elif Info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:
1554 if NumEntryPoints < 2:
1555 AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Replace(Dict))
1556 else:
1557 AutoGenC.Append(gUefiDriverEntryPointString[2].Replace(Dict))
1558 AutoGenH.Append(gUefiDriverEntryPointPrototype.Replace(Dict))
1559 elif Info.ModuleType == 'DXE_SMM_DRIVER':
1560 if NumEntryPoints == 0:
1561 AutoGenC.Append(gDxeSmmEntryPointString[0].Replace(Dict))
1562 else:
1563 AutoGenC.Append(gDxeSmmEntryPointString[1].Replace(Dict))
1564 AutoGenH.Append(gDxeSmmEntryPointPrototype.Replace(Dict))
1565 elif Info.ModuleType == 'MM_STANDALONE':
1566 if NumEntryPoints < 2:
1567 AutoGenC.Append(gMmStandaloneEntryPointString[NumEntryPoints].Replace(Dict))
1568 else:
1569 AutoGenC.Append(gMmStandaloneEntryPointString[2].Replace(Dict))
1570 AutoGenH.Append(gMmStandaloneEntryPointPrototype.Replace(Dict))
1571 elif Info.ModuleType == 'UEFI_APPLICATION':
1572 if NumEntryPoints < 2:
1573 AutoGenC.Append(gUefiApplicationEntryPointString[NumEntryPoints].Replace(Dict))
1574 else:
1575 AutoGenC.Append(gUefiApplicationEntryPointString[2].Replace(Dict))
1576 AutoGenH.Append(gUefiApplicationEntryPointPrototype.Replace(Dict))
1577
1578 ## Create code for ModuleUnloadImage
1579 #
1580 # @param Info The ModuleAutoGen object
1581 # @param AutoGenC The TemplateString object for C code
1582 # @param AutoGenH The TemplateString object for header file
1583 #
1584 def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH):
1585 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1586 return
1587 #
1588 # Unload Image Handlers
1589 #
1590 NumUnloadImage = len(Info.Module.ModuleUnloadImageList)
1591 Dict = {'Count':str(NumUnloadImage) + 'U', 'Function':Info.Module.ModuleUnloadImageList}
1592 if NumUnloadImage < 2:
1593 AutoGenC.Append(gUefiUnloadImageString[NumUnloadImage].Replace(Dict))
1594 else:
1595 AutoGenC.Append(gUefiUnloadImageString[2].Replace(Dict))
1596 AutoGenH.Append(gUefiUnloadImagePrototype.Replace(Dict))
1597
1598 ## Create code for GUID
1599 #
1600 # @param Info The ModuleAutoGen object
1601 # @param AutoGenC The TemplateString object for C code
1602 # @param AutoGenH The TemplateString object for header file
1603 #
1604 def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH):
1605 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1606 GuidType = "GUID"
1607 else:
1608 GuidType = "EFI_GUID"
1609
1610 if Info.GuidList:
1611 if not Info.IsLibrary:
1612 AutoGenC.Append("\n// Guids\n")
1613 AutoGenH.Append("\n// Guids\n")
1614 #
1615 # GUIDs
1616 #
1617 for Key in Info.GuidList:
1618 if not Info.IsLibrary:
1619 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.GuidList[Key]))
1620 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1621
1622 ## Create code for protocol
1623 #
1624 # @param Info The ModuleAutoGen object
1625 # @param AutoGenC The TemplateString object for C code
1626 # @param AutoGenH The TemplateString object for header file
1627 #
1628 def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH):
1629 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1630 GuidType = "GUID"
1631 else:
1632 GuidType = "EFI_GUID"
1633
1634 if Info.ProtocolList:
1635 if not Info.IsLibrary:
1636 AutoGenC.Append("\n// Protocols\n")
1637 AutoGenH.Append("\n// Protocols\n")
1638 #
1639 # Protocol GUIDs
1640 #
1641 for Key in Info.ProtocolList:
1642 if not Info.IsLibrary:
1643 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.ProtocolList[Key]))
1644 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1645
1646 ## Create code for PPI
1647 #
1648 # @param Info The ModuleAutoGen object
1649 # @param AutoGenC The TemplateString object for C code
1650 # @param AutoGenH The TemplateString object for header file
1651 #
1652 def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH):
1653 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1654 GuidType = "GUID"
1655 else:
1656 GuidType = "EFI_GUID"
1657
1658 if Info.PpiList:
1659 if not Info.IsLibrary:
1660 AutoGenC.Append("\n// PPIs\n")
1661 AutoGenH.Append("\n// PPIs\n")
1662 #
1663 # PPI GUIDs
1664 #
1665 for Key in Info.PpiList:
1666 if not Info.IsLibrary:
1667 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.PpiList[Key]))
1668 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1669
1670 ## Create code for PCD
1671 #
1672 # @param Info The ModuleAutoGen object
1673 # @param AutoGenC The TemplateString object for C code
1674 # @param AutoGenH The TemplateString object for header file
1675 #
1676 def CreatePcdCode(Info, AutoGenC, AutoGenH):
1677
1678 # Collect Token Space GUIDs used by DynamicEc PCDs
1679 TokenSpaceList = []
1680 for Pcd in Info.ModulePcdList:
1681 if Pcd.Type in gDynamicExPcd and Pcd.TokenSpaceGuidCName not in TokenSpaceList:
1682 TokenSpaceList += [Pcd.TokenSpaceGuidCName]
1683
1684 SkuMgr = Info.Workspace.Platform.SkuIdMgr
1685 AutoGenH.Append("\n// Definition of SkuId Array\n")
1686 AutoGenH.Append("extern UINT64 _gPcd_SkuId_Array[];\n")
1687 # Add extern declarations to AutoGen.h if one or more Token Space GUIDs were found
1688 if TokenSpaceList <> []:
1689 AutoGenH.Append("\n// Definition of PCD Token Space GUIDs used in this module\n\n")
1690 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1691 GuidType = "GUID"
1692 else:
1693 GuidType = "EFI_GUID"
1694 for Item in TokenSpaceList:
1695 AutoGenH.Append('extern %s %s;\n' % (GuidType, Item))
1696
1697 if Info.IsLibrary:
1698 if Info.ModulePcdList:
1699 AutoGenH.Append("\n// PCD definitions\n")
1700 for Pcd in Info.ModulePcdList:
1701 CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd)
1702 DynExPcdTokenNumberMapping (Info, AutoGenH)
1703 else:
1704 AutoGenC.Append("\n// Definition of SkuId Array\n")
1705 AutoGenC.Append("GLOBAL_REMOVE_IF_UNREFERENCED UINT64 _gPcd_SkuId_Array[] = %s;\n" % SkuMgr.DumpSkuIdArrary())
1706 if Info.ModulePcdList:
1707 AutoGenH.Append("\n// Definition of PCDs used in this module\n")
1708 AutoGenC.Append("\n// Definition of PCDs used in this module\n")
1709 for Pcd in Info.ModulePcdList:
1710 CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd)
1711 DynExPcdTokenNumberMapping (Info, AutoGenH)
1712 if Info.LibraryPcdList:
1713 AutoGenH.Append("\n// Definition of PCDs used in libraries is in AutoGen.c\n")
1714 AutoGenC.Append("\n// Definition of PCDs used in libraries\n")
1715 for Pcd in Info.LibraryPcdList:
1716 CreateModulePcdCode(Info, AutoGenC, AutoGenC, Pcd)
1717 CreatePcdDatabaseCode(Info, AutoGenC, AutoGenH)
1718
1719 ## Create code for unicode string definition
1720 #
1721 # @param Info The ModuleAutoGen object
1722 # @param AutoGenC The TemplateString object for C code
1723 # @param AutoGenH The TemplateString object for header file
1724 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
1725 # @param UniGenBinBuffer Buffer to store uni string package data
1726 #
1727 def CreateUnicodeStringCode(Info, AutoGenC, AutoGenH, UniGenCFlag, UniGenBinBuffer):
1728 WorkingDir = os.getcwd()
1729 os.chdir(Info.WorkspaceDir)
1730
1731 IncList = [Info.MetaFile.Dir]
1732 # Get all files under [Sources] section in inf file for EDK-II module
1733 EDK2Module = True
1734 SrcList = [F for F in Info.SourceFileList]
1735 if Info.AutoGenVersion < 0x00010005:
1736 EDK2Module = False
1737 # Get all files under the module directory for EDK-I module
1738 Cwd = os.getcwd()
1739 os.chdir(Info.MetaFile.Dir)
1740 for Root, Dirs, Files in os.walk("."):
1741 if 'CVS' in Dirs:
1742 Dirs.remove('CVS')
1743 if '.svn' in Dirs:
1744 Dirs.remove('.svn')
1745 for File in Files:
1746 File = PathClass(os.path.join(Root, File), Info.MetaFile.Dir)
1747 if File in SrcList:
1748 continue
1749 SrcList.append(File)
1750 os.chdir(Cwd)
1751
1752 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-c') > -1:
1753 CompatibleMode = True
1754 else:
1755 CompatibleMode = False
1756
1757 #
1758 # -s is a temporary option dedicated for building .UNI files with ISO 639-2 language codes of EDK Shell in EDK2
1759 #
1760 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-s') > -1:
1761 if CompatibleMode:
1762 EdkLogger.error("build", AUTOGEN_ERROR,
1763 "-c and -s build options should be used exclusively",
1764 ExtraData="[%s]" % str(Info))
1765 ShellMode = True
1766 else:
1767 ShellMode = False
1768
1769 #RFC4646 is only for EDKII modules and ISO639-2 for EDK modules
1770 if EDK2Module:
1771 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.RFCLanguages]
1772 else:
1773 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.ISOLanguages]
1774 Header, Code = GetStringFiles(Info.UnicodeFileList, SrcList, IncList, Info.IncludePathList, ['.uni', '.inf'], Info.Name, CompatibleMode, ShellMode, UniGenCFlag, UniGenBinBuffer, FilterInfo)
1775 if CompatibleMode or UniGenCFlag:
1776 AutoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
1777 AutoGenC.Append(Code)
1778 AutoGenC.Append("\n")
1779 AutoGenH.Append("\n//\n//Unicode String ID\n//\n")
1780 AutoGenH.Append(Header)
1781 if CompatibleMode or UniGenCFlag:
1782 AutoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % Info.Name)
1783 os.chdir(WorkingDir)
1784
1785 def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGenCFlag, IdfGenBinBuffer):
1786 if len(Info.IdfFileList) > 0:
1787 ImageFiles = IdfFileClassObject(sorted (Info.IdfFileList))
1788 if ImageFiles.ImageFilesDict:
1789 Index = 1
1790 PaletteIndex = 1
1791 IncList = [Info.MetaFile.Dir]
1792 SrcList = [F for F in Info.SourceFileList]
1793 SkipList = ['.jpg', '.png', '.bmp', '.inf', '.idf']
1794 FileList = GetFileList(SrcList, IncList, SkipList)
1795 ValueStartPtr = 60
1796 StringH.Append("\n//\n//Image ID\n//\n")
1797 ImageInfoOffset = 0
1798 PaletteInfoOffset = 0
1799 ImageBuffer = pack('x')
1800 PaletteBuffer = pack('x')
1801 BufferStr = ''
1802 PaletteStr = ''
1803 FileDict = {}
1804 for Idf in ImageFiles.ImageFilesDict:
1805 if ImageFiles.ImageFilesDict[Idf]:
1806 for FileObj in ImageFiles.ImageFilesDict[Idf]:
1807 for sourcefile in Info.SourceFileList:
1808 if FileObj.FileName == sourcefile.File:
1809 if not sourcefile.Ext.upper() in ['.PNG', '.BMP', '.JPG']:
1810 EdkLogger.error("build", AUTOGEN_ERROR, "The %s's postfix must be one of .bmp, .jpg, .png" % (FileObj.FileName), ExtraData="[%s]" % str(Info))
1811 FileObj.File = sourcefile
1812 break
1813 else:
1814 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))
1815
1816 for FileObj in ImageFiles.ImageFilesDict[Idf]:
1817 ID = FileObj.ImageID
1818 File = FileObj.File
1819 if not os.path.exists(File.Path) or not os.path.isfile(File.Path):
1820 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=File.Path)
1821 SearchImageID (FileObj, FileList)
1822 if FileObj.Referenced:
1823 if (ValueStartPtr - len(DEFINE_STR + ID)) <= 0:
1824 Line = DEFINE_STR + ' ' + ID + ' ' + DecToHexStr(Index, 4) + '\n'
1825 else:
1826 Line = DEFINE_STR + ' ' + ID + ' ' * (ValueStartPtr - len(DEFINE_STR + ID)) + DecToHexStr(Index, 4) + '\n'
1827
1828 if File not in FileDict:
1829 FileDict[File] = Index
1830 else:
1831 DuplicateBlock = pack('B', EFI_HII_IIBT_DUPLICATE)
1832 DuplicateBlock += pack('H', FileDict[File])
1833 ImageBuffer += DuplicateBlock
1834 BufferStr = WriteLine(BufferStr, '// %s: %s: %s' % (DecToHexStr(Index, 4), ID, DecToHexStr(Index, 4)))
1835 TempBufferList = AscToHexList(DuplicateBlock)
1836 BufferStr = WriteLine(BufferStr, CreateArrayItem(TempBufferList, 16) + '\n')
1837 StringH.Append(Line)
1838 Index += 1
1839 continue
1840
1841 TmpFile = open(File.Path, 'rb')
1842 Buffer = TmpFile.read()
1843 TmpFile.close()
1844 if File.Ext.upper() == '.PNG':
1845 TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_PNG)
1846 TempBuffer += pack('I', len(Buffer))
1847 TempBuffer += Buffer
1848 elif File.Ext.upper() == '.JPG':
1849 ImageType, = struct.unpack('4s', Buffer[6:10])
1850 if ImageType != 'JFIF':
1851 EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard JPG file." % File.Path)
1852 TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_JPEG)
1853 TempBuffer += pack('I', len(Buffer))
1854 TempBuffer += Buffer
1855 elif File.Ext.upper() == '.BMP':
1856 TempBuffer, TempPalette = BmpImageDecoder(File, Buffer, PaletteIndex, FileObj.TransParent)
1857 if len(TempPalette) > 1:
1858 PaletteIndex += 1
1859 NewPalette = pack('H', len(TempPalette))
1860 NewPalette += TempPalette
1861 PaletteBuffer += NewPalette
1862 PaletteStr = WriteLine(PaletteStr, '// %s: %s: %s' % (DecToHexStr(PaletteIndex - 1, 4), ID, DecToHexStr(PaletteIndex - 1, 4)))
1863 TempPaletteList = AscToHexList(NewPalette)
1864 PaletteStr = WriteLine(PaletteStr, CreateArrayItem(TempPaletteList, 16) + '\n')
1865 ImageBuffer += TempBuffer
1866 BufferStr = WriteLine(BufferStr, '// %s: %s: %s' % (DecToHexStr(Index, 4), ID, DecToHexStr(Index, 4)))
1867 TempBufferList = AscToHexList(TempBuffer)
1868 BufferStr = WriteLine(BufferStr, CreateArrayItem(TempBufferList, 16) + '\n')
1869
1870 StringH.Append(Line)
1871 Index += 1
1872
1873 BufferStr = WriteLine(BufferStr, '// End of the Image Info')
1874 BufferStr = WriteLine(BufferStr, CreateArrayItem(DecToHexList(EFI_HII_IIBT_END, 2)) + '\n')
1875 ImageEnd = pack('B', EFI_HII_IIBT_END)
1876 ImageBuffer += ImageEnd
1877
1878 if len(ImageBuffer) > 1:
1879 ImageInfoOffset = 12
1880 if len(PaletteBuffer) > 1:
1881 PaletteInfoOffset = 12 + len(ImageBuffer) - 1 # -1 is for the first empty pad byte of ImageBuffer
1882
1883 IMAGE_PACKAGE_HDR = pack('=II', ImageInfoOffset, PaletteInfoOffset)
1884 # PACKAGE_HEADER_Length = PACKAGE_HEADER + ImageInfoOffset + PaletteInfoOffset + ImageBuffer Length + PaletteCount + PaletteBuffer Length
1885 if len(PaletteBuffer) > 1:
1886 PACKAGE_HEADER_Length = 4 + 4 + 4 + len(ImageBuffer) - 1 + 2 + len(PaletteBuffer) - 1
1887 else:
1888 PACKAGE_HEADER_Length = 4 + 4 + 4 + len(ImageBuffer) - 1
1889 if PaletteIndex > 1:
1890 PALETTE_INFO_HEADER = pack('H', PaletteIndex - 1)
1891 # EFI_HII_PACKAGE_HEADER length max value is 0xFFFFFF
1892 Hex_Length = '%06X' % PACKAGE_HEADER_Length
1893 if PACKAGE_HEADER_Length > 0xFFFFFF:
1894 EdkLogger.error("build", AUTOGEN_ERROR, "The Length of EFI_HII_PACKAGE_HEADER exceed its maximum value", ExtraData="[%s]" % str(Info))
1895 PACKAGE_HEADER = pack('=HBB', int('0x' + Hex_Length[2:], 16), int('0x' + Hex_Length[0:2], 16), EFI_HII_PACKAGE_IMAGES)
1896
1897 IdfGenBinBuffer.write(PACKAGE_HEADER)
1898 IdfGenBinBuffer.write(IMAGE_PACKAGE_HDR)
1899 if len(ImageBuffer) > 1 :
1900 IdfGenBinBuffer.write(ImageBuffer[1:])
1901 if PaletteIndex > 1:
1902 IdfGenBinBuffer.write(PALETTE_INFO_HEADER)
1903 if len(PaletteBuffer) > 1:
1904 IdfGenBinBuffer.write(PaletteBuffer[1:])
1905
1906 if IdfGenCFlag:
1907 TotalLength = EFI_HII_ARRAY_SIZE_LENGTH + PACKAGE_HEADER_Length
1908 AutoGenC.Append("\n//\n//Image Pack Definition\n//\n")
1909 AllStr = WriteLine('', CHAR_ARRAY_DEFIN + ' ' + Info.Module.BaseName + 'Images' + '[] = {\n')
1910 AllStr = WriteLine(AllStr, '// STRGATHER_OUTPUT_HEADER')
1911 AllStr = WriteLine(AllStr, CreateArrayItem(DecToHexList(TotalLength)) + '\n')
1912 AllStr = WriteLine(AllStr, '// Image PACKAGE HEADER\n')
1913 IMAGE_PACKAGE_HDR_List = AscToHexList(PACKAGE_HEADER)
1914 IMAGE_PACKAGE_HDR_List += AscToHexList(IMAGE_PACKAGE_HDR)
1915 AllStr = WriteLine(AllStr, CreateArrayItem(IMAGE_PACKAGE_HDR_List, 16) + '\n')
1916 AllStr = WriteLine(AllStr, '// Image DATA\n')
1917 if BufferStr:
1918 AllStr = WriteLine(AllStr, BufferStr)
1919 if PaletteStr:
1920 AllStr = WriteLine(AllStr, '// Palette Header\n')
1921 PALETTE_INFO_HEADER_List = AscToHexList(PALETTE_INFO_HEADER)
1922 AllStr = WriteLine(AllStr, CreateArrayItem(PALETTE_INFO_HEADER_List, 16) + '\n')
1923 AllStr = WriteLine(AllStr, '// Palette Data\n')
1924 AllStr = WriteLine(AllStr, PaletteStr)
1925 AllStr = WriteLine(AllStr, '};')
1926 AutoGenC.Append(AllStr)
1927 AutoGenC.Append("\n")
1928 StringH.Append('\nextern unsigned char ' + Info.Module.BaseName + 'Images[];\n')
1929 StringH.Append("\n#define IMAGE_ARRAY_NAME %sImages\n" % Info.Module.BaseName)
1930
1931 # typedef struct _EFI_HII_IMAGE_PACKAGE_HDR {
1932 # EFI_HII_PACKAGE_HEADER Header; # Standard package header, where Header.Type = EFI_HII_PACKAGE_IMAGES
1933 # UINT32 ImageInfoOffset;
1934 # UINT32 PaletteInfoOffset;
1935 # } EFI_HII_IMAGE_PACKAGE_HDR;
1936
1937 # typedef struct {
1938 # UINT32 Length:24;
1939 # UINT32 Type:8;
1940 # UINT8 Data[];
1941 # } EFI_HII_PACKAGE_HEADER;
1942
1943 # typedef struct _EFI_HII_IMAGE_BLOCK {
1944 # UINT8 BlockType;
1945 # UINT8 BlockBody[];
1946 # } EFI_HII_IMAGE_BLOCK;
1947
1948 def BmpImageDecoder(File, Buffer, PaletteIndex, TransParent):
1949 ImageType, = struct.unpack('2s', Buffer[0:2])
1950 if ImageType!= 'BM': # BMP file type is 'BM'
1951 EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard BMP file." % File.Path)
1952 BMP_IMAGE_HEADER = collections.namedtuple('BMP_IMAGE_HEADER', ['bfSize','bfReserved1','bfReserved2','bfOffBits','biSize','biWidth','biHeight','biPlanes','biBitCount', 'biCompression', 'biSizeImage','biXPelsPerMeter','biYPelsPerMeter','biClrUsed','biClrImportant'])
1953 BMP_IMAGE_HEADER_STRUCT = struct.Struct('IHHIIIIHHIIIIII')
1954 BmpHeader = BMP_IMAGE_HEADER._make(BMP_IMAGE_HEADER_STRUCT.unpack_from(Buffer[2:]))
1955 #
1956 # Doesn't support compress.
1957 #
1958 if BmpHeader.biCompression != 0:
1959 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The compress BMP file %s is not support." % File.Path)
1960
1961 # The Width and Height is UINT16 type in Image Package
1962 if BmpHeader.biWidth > 0xFFFF:
1963 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The BMP file %s Width is exceed 0xFFFF." % File.Path)
1964 if BmpHeader.biHeight > 0xFFFF:
1965 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The BMP file %s Height is exceed 0xFFFF." % File.Path)
1966
1967 PaletteBuffer = pack('x')
1968 if BmpHeader.biBitCount == 1:
1969 if TransParent:
1970 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_1BIT_TRANS)
1971 else:
1972 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_1BIT)
1973 ImageBuffer += pack('B', PaletteIndex)
1974 Width = (BmpHeader.biWidth + 7)/8
1975 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1976 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1977 elif BmpHeader.biBitCount == 4:
1978 if TransParent:
1979 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_4BIT_TRANS)
1980 else:
1981 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_4BIT)
1982 ImageBuffer += pack('B', PaletteIndex)
1983 Width = (BmpHeader.biWidth + 1)/2
1984 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1985 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1986 elif BmpHeader.biBitCount == 8:
1987 if TransParent:
1988 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_8BIT_TRANS)
1989 else:
1990 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_8BIT)
1991 ImageBuffer += pack('B', PaletteIndex)
1992 Width = BmpHeader.biWidth
1993 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1994 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1995 elif BmpHeader.biBitCount == 24:
1996 if TransParent:
1997 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_24BIT_TRANS)
1998 else:
1999 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_24BIT)
2000 Width = BmpHeader.biWidth * 3
2001 else:
2002 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "Only support the 1 bit, 4 bit, 8bit, 24 bit BMP files.", ExtraData="[%s]" % str(File.Path))
2003
2004 ImageBuffer += pack('H', BmpHeader.biWidth)
2005 ImageBuffer += pack('H', BmpHeader.biHeight)
2006 Start = BmpHeader.bfOffBits
2007 End = BmpHeader.bfSize - 1
2008 for Height in range(0, BmpHeader.biHeight):
2009 if Width % 4 != 0:
2010 Start = End + (Width % 4) - 4 - Width
2011 else:
2012 Start = End - Width
2013 ImageBuffer += Buffer[Start + 1 : Start + Width + 1]
2014 End = Start
2015
2016 # 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
2017 if PaletteBuffer and len(PaletteBuffer) > 1:
2018 PaletteTemp = pack('x')
2019 for Index in range(0, len(PaletteBuffer)):
2020 if Index % 4 == 3:
2021 continue
2022 PaletteTemp += PaletteBuffer[Index]
2023 PaletteBuffer = PaletteTemp[1:]
2024 return ImageBuffer, PaletteBuffer
2025
2026 ## Create common code
2027 #
2028 # @param Info The ModuleAutoGen object
2029 # @param AutoGenC The TemplateString object for C code
2030 # @param AutoGenH The TemplateString object for header file
2031 #
2032 def CreateHeaderCode(Info, AutoGenC, AutoGenH):
2033 # file header
2034 AutoGenH.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.h'}))
2035 # header file Prologue
2036 AutoGenH.Append(gAutoGenHPrologueString.Replace({'File':'AUTOGENH','Guid':Info.Guid.replace('-','_')}))
2037 AutoGenH.Append(gAutoGenHCppPrologueString)
2038 if Info.AutoGenVersion >= 0x00010005:
2039 # header files includes
2040 AutoGenH.Append("#include <%s>\n" % gBasicHeaderFile)
2041 if Info.ModuleType in gModuleTypeHeaderFile \
2042 and gModuleTypeHeaderFile[Info.ModuleType][0] != gBasicHeaderFile:
2043 AutoGenH.Append("#include <%s>\n" % gModuleTypeHeaderFile[Info.ModuleType][0])
2044 #
2045 # if either PcdLib in [LibraryClasses] sections or there exist Pcd section, add PcdLib.h
2046 # As if modules only uses FixedPcd, then PcdLib is not needed in [LibraryClasses] section.
2047 #
2048 if 'PcdLib' in Info.Module.LibraryClasses or Info.Module.Pcds:
2049 AutoGenH.Append("#include <Library/PcdLib.h>\n")
2050
2051 AutoGenH.Append('\nextern GUID gEfiCallerIdGuid;')
2052 AutoGenH.Append('\nextern CHAR8 *gEfiCallerBaseName;\n\n')
2053
2054 if Info.IsLibrary:
2055 return
2056
2057 AutoGenH.Append("#define EFI_CALLER_ID_GUID \\\n %s\n" % GuidStringToGuidStructureString(Info.Guid))
2058
2059 if Info.IsLibrary:
2060 return
2061 # C file header
2062 AutoGenC.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.c'}))
2063 if Info.AutoGenVersion >= 0x00010005:
2064 # C file header files includes
2065 if Info.ModuleType in gModuleTypeHeaderFile:
2066 for Inc in gModuleTypeHeaderFile[Info.ModuleType]:
2067 AutoGenC.Append("#include <%s>\n" % Inc)
2068 else:
2069 AutoGenC.Append("#include <%s>\n" % gBasicHeaderFile)
2070
2071 #
2072 # Publish the CallerId Guid
2073 #
2074 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(Info.Guid))
2075 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *gEfiCallerBaseName = "%s";\n' % Info.Name)
2076
2077 ## Create common code for header file
2078 #
2079 # @param Info The ModuleAutoGen object
2080 # @param AutoGenC The TemplateString object for C code
2081 # @param AutoGenH The TemplateString object for header file
2082 #
2083 def CreateFooterCode(Info, AutoGenC, AutoGenH):
2084 AutoGenH.Append(gAutoGenHEpilogueString)
2085
2086 ## Create code for a module
2087 #
2088 # @param Info The ModuleAutoGen object
2089 # @param AutoGenC The TemplateString object for C code
2090 # @param AutoGenH The TemplateString object for header file
2091 # @param StringH The TemplateString object for header file
2092 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
2093 # @param UniGenBinBuffer Buffer to store uni string package data
2094 # @param StringIdf The TemplateString object for header file
2095 # @param IdfGenCFlag IdfString is generated into AutoGen C file when it is set to True
2096 # @param IdfGenBinBuffer Buffer to store Idf string package data
2097 #
2098 def CreateCode(Info, AutoGenC, AutoGenH, StringH, UniGenCFlag, UniGenBinBuffer, StringIdf, IdfGenCFlag, IdfGenBinBuffer):
2099 CreateHeaderCode(Info, AutoGenC, AutoGenH)
2100
2101 if Info.AutoGenVersion >= 0x00010005:
2102 CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH)
2103 CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH)
2104 CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH)
2105 CreatePcdCode(Info, AutoGenC, AutoGenH)
2106 CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH)
2107 CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH)
2108 CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH)
2109 CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH)
2110
2111 if Info.UnicodeFileList:
2112 FileName = "%sStrDefs.h" % Info.Name
2113 StringH.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
2114 StringH.Append(gAutoGenHPrologueString.Replace({'File':'STRDEFS', 'Guid':Info.Guid.replace('-','_')}))
2115 CreateUnicodeStringCode(Info, AutoGenC, StringH, UniGenCFlag, UniGenBinBuffer)
2116
2117 GuidMacros = []
2118 for Guid in Info.Module.Guids:
2119 if Guid in Info.Module.GetGuidsUsedByPcd():
2120 continue
2121 GuidMacros.append('#define %s %s' % (Guid, Info.Module.Guids[Guid]))
2122 for Guid, Value in Info.Module.Protocols.items() + Info.Module.Ppis.items():
2123 GuidMacros.append('#define %s %s' % (Guid, Value))
2124 # supports FixedAtBuild usage in VFR file
2125 if Info.VfrFileList and Info.ModulePcdList:
2126 GuidMacros.append('#define %s %s' % ('FixedPcdGetBool(TokenName)', '_PCD_VALUE_##TokenName'))
2127 GuidMacros.append('#define %s %s' % ('FixedPcdGet8(TokenName)', '_PCD_VALUE_##TokenName'))
2128 GuidMacros.append('#define %s %s' % ('FixedPcdGet16(TokenName)', '_PCD_VALUE_##TokenName'))
2129 GuidMacros.append('#define %s %s' % ('FixedPcdGet32(TokenName)', '_PCD_VALUE_##TokenName'))
2130 GuidMacros.append('#define %s %s' % ('FixedPcdGet64(TokenName)', '_PCD_VALUE_##TokenName'))
2131 for Pcd in Info.ModulePcdList:
2132 if Pcd.Type == TAB_PCDS_FIXED_AT_BUILD:
2133 TokenCName = Pcd.TokenCName
2134 Value = Pcd.DefaultValue
2135 if Pcd.DatumType == 'BOOLEAN':
2136 BoolValue = Value.upper()
2137 if BoolValue == 'TRUE':
2138 Value = '1'
2139 elif BoolValue == 'FALSE':
2140 Value = '0'
2141 for PcdItem in GlobalData.MixedPcd:
2142 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
2143 TokenCName = PcdItem[0]
2144 break
2145 GuidMacros.append('#define %s %s' % ('_PCD_VALUE_'+TokenCName, Value))
2146
2147 if Info.IdfFileList:
2148 GuidMacros.append('#include "%sImgDefs.h"' % Info.Name)
2149
2150 if GuidMacros:
2151 StringH.Append('\n#ifdef VFRCOMPILE\n%s\n#endif\n' % '\n'.join(GuidMacros))
2152
2153 StringH.Append("\n#endif\n")
2154 AutoGenH.Append('#include "%s"\n' % FileName)
2155
2156 if Info.IdfFileList:
2157 FileName = "%sImgDefs.h" % Info.Name
2158 StringIdf.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
2159 StringIdf.Append(gAutoGenHPrologueString.Replace({'File':'IMAGEDEFS', 'Guid':Info.Guid.replace('-','_')}))
2160 CreateIdfFileCode(Info, AutoGenC, StringIdf, IdfGenCFlag, IdfGenBinBuffer)
2161
2162 StringIdf.Append("\n#endif\n")
2163 AutoGenH.Append('#include "%s"\n' % FileName)
2164
2165 CreateFooterCode(Info, AutoGenC, AutoGenH)
2166
2167 # no generation of AutoGen.c for Edk modules without unicode file
2168 if Info.AutoGenVersion < 0x00010005 and len(Info.UnicodeFileList) == 0:
2169 AutoGenC.String = ''
2170
2171 ## Create the code file
2172 #
2173 # @param FilePath The path of code file
2174 # @param Content The content of code file
2175 # @param IsBinaryFile The flag indicating if the file is binary file or not
2176 #
2177 # @retval True If file content is changed or file doesn't exist
2178 # @retval False If the file exists and the content is not changed
2179 #
2180 def Generate(FilePath, Content, IsBinaryFile):
2181 return SaveFileOnChange(FilePath, Content, IsBinaryFile)
2182