]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/AutoGen/GenC.py
BaseTools: Fix a bug for Size incorrect of Void* Fixatbuild Pcd
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / GenC.py
1 ## @file
2 # Routines for generating AutoGen.h and AutoGen.c
3 #
4 # Copyright (c) 2007 - 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 = []
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 key in Info.ConstPcd:
1357 Pcd.DefaultValue = Info.ConstPcd[key]
1358 if Pcd.DatumType not in _NumericDataTypesList:
1359 AutoGenH.Append('#define _PCD_VALUE_%s %s%s\n' %(TokenCName, Type, PcdVariableName))
1360 else:
1361 AutoGenH.Append('#define _PCD_VALUE_%s %s\n' %(TokenCName, Pcd.DefaultValue))
1362 PcdDataSize = GetPcdSize(Pcd)
1363 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD:
1364 if Pcd.DatumType not in _NumericDataTypesList:
1365 if ConstFixedPcd:
1366 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1367 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixPcdSizeTokenName))
1368 else:
1369 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixedPcdSizeVariableName))
1370 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName,FixedPcdSizeVariableName))
1371 AutoGenH.Append('extern const UINTN %s; \n' % FixedPcdSizeVariableName)
1372 else:
1373 AutoGenH.Append('#define %s %s\n' % (FixPcdSizeTokenName, PcdDataSize))
1374 AutoGenH.Append('#define %s %s\n' % (GetModeSizeName,FixPcdSizeTokenName))
1375
1376 ## Create code for library constructor
1377 #
1378 # @param Info The ModuleAutoGen object
1379 # @param AutoGenC The TemplateString object for C code
1380 # @param AutoGenH The TemplateString object for header file
1381 #
1382 def CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH):
1383 #
1384 # Library Constructors
1385 #
1386 ConstructorPrototypeString = TemplateString()
1387 ConstructorCallingString = TemplateString()
1388 if Info.IsLibrary:
1389 DependentLibraryList = [Info.Module]
1390 else:
1391 DependentLibraryList = Info.DependentLibraryList
1392 for Lib in DependentLibraryList:
1393 if len(Lib.ConstructorList) <= 0:
1394 continue
1395 Dict = {'Function':Lib.ConstructorList}
1396 if Lib.ModuleType in ['BASE', 'SEC']:
1397 ConstructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1398 ConstructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1399 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1400 ConstructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1401 ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1402 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1403 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1404 ConstructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1405 ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1406 elif Lib.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1407 ConstructorPrototypeString.Append(gLibraryStructorPrototype['MM'].Replace(Dict))
1408 ConstructorCallingString.Append(gLibraryStructorCall['MM'].Replace(Dict))
1409
1410 if str(ConstructorPrototypeString) == '':
1411 ConstructorPrototypeList = []
1412 else:
1413 ConstructorPrototypeList = [str(ConstructorPrototypeString)]
1414 if str(ConstructorCallingString) == '':
1415 ConstructorCallingList = []
1416 else:
1417 ConstructorCallingList = [str(ConstructorCallingString)]
1418
1419 Dict = {
1420 'Type' : 'Constructor',
1421 'FunctionPrototype' : ConstructorPrototypeList,
1422 'FunctionCall' : ConstructorCallingList
1423 }
1424 if Info.IsLibrary:
1425 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1426 else:
1427 if Info.ModuleType in ['BASE', 'SEC']:
1428 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1429 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1430 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1431 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1432 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1433 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1434 elif Info.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1435 AutoGenC.Append(gLibraryString['MM'].Replace(Dict))
1436
1437 ## Create code for library destructor
1438 #
1439 # @param Info The ModuleAutoGen object
1440 # @param AutoGenC The TemplateString object for C code
1441 # @param AutoGenH The TemplateString object for header file
1442 #
1443 def CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH):
1444 #
1445 # Library Destructors
1446 #
1447 DestructorPrototypeString = TemplateString()
1448 DestructorCallingString = TemplateString()
1449 if Info.IsLibrary:
1450 DependentLibraryList = [Info.Module]
1451 else:
1452 DependentLibraryList = Info.DependentLibraryList
1453 for Index in range(len(DependentLibraryList)-1, -1, -1):
1454 Lib = DependentLibraryList[Index]
1455 if len(Lib.DestructorList) <= 0:
1456 continue
1457 Dict = {'Function':Lib.DestructorList}
1458 if Lib.ModuleType in ['BASE', 'SEC']:
1459 DestructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1460 DestructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1461 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1462 DestructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1463 DestructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1464 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1465 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION', 'SMM_CORE']:
1466 DestructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1467 DestructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1468 elif Lib.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1469 DestructorPrototypeString.Append(gLibraryStructorPrototype['MM'].Replace(Dict))
1470 DestructorCallingString.Append(gLibraryStructorCall['MM'].Replace(Dict))
1471
1472 if str(DestructorPrototypeString) == '':
1473 DestructorPrototypeList = []
1474 else:
1475 DestructorPrototypeList = [str(DestructorPrototypeString)]
1476 if str(DestructorCallingString) == '':
1477 DestructorCallingList = []
1478 else:
1479 DestructorCallingList = [str(DestructorCallingString)]
1480
1481 Dict = {
1482 'Type' : 'Destructor',
1483 'FunctionPrototype' : DestructorPrototypeList,
1484 'FunctionCall' : DestructorCallingList
1485 }
1486 if Info.IsLibrary:
1487 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1488 else:
1489 if Info.ModuleType in ['BASE', 'SEC']:
1490 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1491 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1492 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1493 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
1494 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
1495 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1496 elif Info.ModuleType in ['MM_STANDALONE','MM_CORE_STANDALONE']:
1497 AutoGenC.Append(gLibraryString['MM'].Replace(Dict))
1498
1499
1500 ## Create code for ModuleEntryPoint
1501 #
1502 # @param Info The ModuleAutoGen object
1503 # @param AutoGenC The TemplateString object for C code
1504 # @param AutoGenH The TemplateString object for header file
1505 #
1506 def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH):
1507 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1508 return
1509 #
1510 # Module Entry Points
1511 #
1512 NumEntryPoints = len(Info.Module.ModuleEntryPointList)
1513 if 'PI_SPECIFICATION_VERSION' in Info.Module.Specification:
1514 PiSpecVersion = Info.Module.Specification['PI_SPECIFICATION_VERSION']
1515 else:
1516 PiSpecVersion = '0x00000000'
1517 if 'UEFI_SPECIFICATION_VERSION' in Info.Module.Specification:
1518 UefiSpecVersion = Info.Module.Specification['UEFI_SPECIFICATION_VERSION']
1519 else:
1520 UefiSpecVersion = '0x00000000'
1521 Dict = {
1522 'Function' : Info.Module.ModuleEntryPointList,
1523 'PiSpecVersion' : PiSpecVersion + 'U',
1524 'UefiSpecVersion': UefiSpecVersion + 'U'
1525 }
1526
1527 if Info.ModuleType in ['PEI_CORE', 'DXE_CORE', 'SMM_CORE', 'MM_CORE_STANDALONE']:
1528 if Info.SourceFileList <> None and Info.SourceFileList <> []:
1529 if NumEntryPoints != 1:
1530 EdkLogger.error(
1531 "build",
1532 AUTOGEN_ERROR,
1533 '%s must have exactly one entry point' % Info.ModuleType,
1534 File=str(Info),
1535 ExtraData= ", ".join(Info.Module.ModuleEntryPointList)
1536 )
1537 if Info.ModuleType == 'PEI_CORE':
1538 AutoGenC.Append(gPeiCoreEntryPointString.Replace(Dict))
1539 AutoGenH.Append(gPeiCoreEntryPointPrototype.Replace(Dict))
1540 elif Info.ModuleType == 'DXE_CORE':
1541 AutoGenC.Append(gDxeCoreEntryPointString.Replace(Dict))
1542 AutoGenH.Append(gDxeCoreEntryPointPrototype.Replace(Dict))
1543 elif Info.ModuleType == 'SMM_CORE':
1544 AutoGenC.Append(gSmmCoreEntryPointString.Replace(Dict))
1545 AutoGenH.Append(gSmmCoreEntryPointPrototype.Replace(Dict))
1546 elif Info.ModuleType == 'MM_CORE_STANDALONE':
1547 AutoGenC.Append(gMmCoreStandaloneEntryPointString.Replace(Dict))
1548 AutoGenH.Append(gMmCoreStandaloneEntryPointPrototype.Replace(Dict))
1549 elif Info.ModuleType == 'PEIM':
1550 if NumEntryPoints < 2:
1551 AutoGenC.Append(gPeimEntryPointString[NumEntryPoints].Replace(Dict))
1552 else:
1553 AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict))
1554 AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict))
1555 elif Info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:
1556 if NumEntryPoints < 2:
1557 AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Replace(Dict))
1558 else:
1559 AutoGenC.Append(gUefiDriverEntryPointString[2].Replace(Dict))
1560 AutoGenH.Append(gUefiDriverEntryPointPrototype.Replace(Dict))
1561 elif Info.ModuleType == 'DXE_SMM_DRIVER':
1562 if NumEntryPoints == 0:
1563 AutoGenC.Append(gDxeSmmEntryPointString[0].Replace(Dict))
1564 else:
1565 AutoGenC.Append(gDxeSmmEntryPointString[1].Replace(Dict))
1566 AutoGenH.Append(gDxeSmmEntryPointPrototype.Replace(Dict))
1567 elif Info.ModuleType == 'MM_STANDALONE':
1568 if NumEntryPoints < 2:
1569 AutoGenC.Append(gMmStandaloneEntryPointString[NumEntryPoints].Replace(Dict))
1570 else:
1571 AutoGenC.Append(gMmStandaloneEntryPointString[2].Replace(Dict))
1572 AutoGenH.Append(gMmStandaloneEntryPointPrototype.Replace(Dict))
1573 elif Info.ModuleType == 'UEFI_APPLICATION':
1574 if NumEntryPoints < 2:
1575 AutoGenC.Append(gUefiApplicationEntryPointString[NumEntryPoints].Replace(Dict))
1576 else:
1577 AutoGenC.Append(gUefiApplicationEntryPointString[2].Replace(Dict))
1578 AutoGenH.Append(gUefiApplicationEntryPointPrototype.Replace(Dict))
1579
1580 ## Create code for ModuleUnloadImage
1581 #
1582 # @param Info The ModuleAutoGen object
1583 # @param AutoGenC The TemplateString object for C code
1584 # @param AutoGenH The TemplateString object for header file
1585 #
1586 def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH):
1587 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1588 return
1589 #
1590 # Unload Image Handlers
1591 #
1592 NumUnloadImage = len(Info.Module.ModuleUnloadImageList)
1593 Dict = {'Count':str(NumUnloadImage) + 'U', 'Function':Info.Module.ModuleUnloadImageList}
1594 if NumUnloadImage < 2:
1595 AutoGenC.Append(gUefiUnloadImageString[NumUnloadImage].Replace(Dict))
1596 else:
1597 AutoGenC.Append(gUefiUnloadImageString[2].Replace(Dict))
1598 AutoGenH.Append(gUefiUnloadImagePrototype.Replace(Dict))
1599
1600 ## Create code for GUID
1601 #
1602 # @param Info The ModuleAutoGen object
1603 # @param AutoGenC The TemplateString object for C code
1604 # @param AutoGenH The TemplateString object for header file
1605 #
1606 def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH):
1607 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1608 GuidType = "GUID"
1609 else:
1610 GuidType = "EFI_GUID"
1611
1612 if Info.GuidList:
1613 if not Info.IsLibrary:
1614 AutoGenC.Append("\n// Guids\n")
1615 AutoGenH.Append("\n// Guids\n")
1616 #
1617 # GUIDs
1618 #
1619 for Key in Info.GuidList:
1620 if not Info.IsLibrary:
1621 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.GuidList[Key]))
1622 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1623
1624 ## Create code for protocol
1625 #
1626 # @param Info The ModuleAutoGen object
1627 # @param AutoGenC The TemplateString object for C code
1628 # @param AutoGenH The TemplateString object for header file
1629 #
1630 def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH):
1631 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1632 GuidType = "GUID"
1633 else:
1634 GuidType = "EFI_GUID"
1635
1636 if Info.ProtocolList:
1637 if not Info.IsLibrary:
1638 AutoGenC.Append("\n// Protocols\n")
1639 AutoGenH.Append("\n// Protocols\n")
1640 #
1641 # Protocol GUIDs
1642 #
1643 for Key in Info.ProtocolList:
1644 if not Info.IsLibrary:
1645 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.ProtocolList[Key]))
1646 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1647
1648 ## Create code for PPI
1649 #
1650 # @param Info The ModuleAutoGen object
1651 # @param AutoGenC The TemplateString object for C code
1652 # @param AutoGenH The TemplateString object for header file
1653 #
1654 def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH):
1655 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1656 GuidType = "GUID"
1657 else:
1658 GuidType = "EFI_GUID"
1659
1660 if Info.PpiList:
1661 if not Info.IsLibrary:
1662 AutoGenC.Append("\n// PPIs\n")
1663 AutoGenH.Append("\n// PPIs\n")
1664 #
1665 # PPI GUIDs
1666 #
1667 for Key in Info.PpiList:
1668 if not Info.IsLibrary:
1669 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.PpiList[Key]))
1670 AutoGenH.Append('extern %s %s;\n' % (GuidType, Key))
1671
1672 ## Create code for PCD
1673 #
1674 # @param Info The ModuleAutoGen object
1675 # @param AutoGenC The TemplateString object for C code
1676 # @param AutoGenH The TemplateString object for header file
1677 #
1678 def CreatePcdCode(Info, AutoGenC, AutoGenH):
1679
1680 # Collect Token Space GUIDs used by DynamicEc PCDs
1681 TokenSpaceList = []
1682 for Pcd in Info.ModulePcdList:
1683 if Pcd.Type in gDynamicExPcd and Pcd.TokenSpaceGuidCName not in TokenSpaceList:
1684 TokenSpaceList += [Pcd.TokenSpaceGuidCName]
1685
1686 SkuMgr = Info.Workspace.Platform.SkuIdMgr
1687 AutoGenH.Append("\n// Definition of SkuId Array\n")
1688 AutoGenH.Append("extern UINT64 _gPcd_SkuId_Array[];\n")
1689 # Add extern declarations to AutoGen.h if one or more Token Space GUIDs were found
1690 if TokenSpaceList <> []:
1691 AutoGenH.Append("\n// Definition of PCD Token Space GUIDs used in this module\n\n")
1692 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1693 GuidType = "GUID"
1694 else:
1695 GuidType = "EFI_GUID"
1696 for Item in TokenSpaceList:
1697 AutoGenH.Append('extern %s %s;\n' % (GuidType, Item))
1698
1699 if Info.IsLibrary:
1700 if Info.ModulePcdList:
1701 AutoGenH.Append("\n// PCD definitions\n")
1702 for Pcd in Info.ModulePcdList:
1703 CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd)
1704 DynExPcdTokenNumberMapping (Info, AutoGenH)
1705 else:
1706 AutoGenC.Append("\n// Definition of SkuId Array\n")
1707 AutoGenC.Append("GLOBAL_REMOVE_IF_UNREFERENCED UINT64 _gPcd_SkuId_Array[] = %s;\n" % SkuMgr.DumpSkuIdArrary())
1708 if Info.ModulePcdList:
1709 AutoGenH.Append("\n// Definition of PCDs used in this module\n")
1710 AutoGenC.Append("\n// Definition of PCDs used in this module\n")
1711 for Pcd in Info.ModulePcdList:
1712 CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd)
1713 DynExPcdTokenNumberMapping (Info, AutoGenH)
1714 if Info.LibraryPcdList:
1715 AutoGenH.Append("\n// Definition of PCDs used in libraries is in AutoGen.c\n")
1716 AutoGenC.Append("\n// Definition of PCDs used in libraries\n")
1717 for Pcd in Info.LibraryPcdList:
1718 CreateModulePcdCode(Info, AutoGenC, AutoGenC, Pcd)
1719 CreatePcdDatabaseCode(Info, AutoGenC, AutoGenH)
1720
1721 ## Create code for unicode string definition
1722 #
1723 # @param Info The ModuleAutoGen object
1724 # @param AutoGenC The TemplateString object for C code
1725 # @param AutoGenH The TemplateString object for header file
1726 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
1727 # @param UniGenBinBuffer Buffer to store uni string package data
1728 #
1729 def CreateUnicodeStringCode(Info, AutoGenC, AutoGenH, UniGenCFlag, UniGenBinBuffer):
1730 WorkingDir = os.getcwd()
1731 os.chdir(Info.WorkspaceDir)
1732
1733 IncList = [Info.MetaFile.Dir]
1734 # Get all files under [Sources] section in inf file for EDK-II module
1735 EDK2Module = True
1736 SrcList = [F for F in Info.SourceFileList]
1737 if Info.AutoGenVersion < 0x00010005:
1738 EDK2Module = False
1739 # Get all files under the module directory for EDK-I module
1740 Cwd = os.getcwd()
1741 os.chdir(Info.MetaFile.Dir)
1742 for Root, Dirs, Files in os.walk("."):
1743 if 'CVS' in Dirs:
1744 Dirs.remove('CVS')
1745 if '.svn' in Dirs:
1746 Dirs.remove('.svn')
1747 for File in Files:
1748 File = PathClass(os.path.join(Root, File), Info.MetaFile.Dir)
1749 if File in SrcList:
1750 continue
1751 SrcList.append(File)
1752 os.chdir(Cwd)
1753
1754 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-c') > -1:
1755 CompatibleMode = True
1756 else:
1757 CompatibleMode = False
1758
1759 #
1760 # -s is a temporary option dedicated for building .UNI files with ISO 639-2 language codes of EDK Shell in EDK2
1761 #
1762 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-s') > -1:
1763 if CompatibleMode:
1764 EdkLogger.error("build", AUTOGEN_ERROR,
1765 "-c and -s build options should be used exclusively",
1766 ExtraData="[%s]" % str(Info))
1767 ShellMode = True
1768 else:
1769 ShellMode = False
1770
1771 #RFC4646 is only for EDKII modules and ISO639-2 for EDK modules
1772 if EDK2Module:
1773 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.RFCLanguages]
1774 else:
1775 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.ISOLanguages]
1776 Header, Code = GetStringFiles(Info.UnicodeFileList, SrcList, IncList, Info.IncludePathList, ['.uni', '.inf'], Info.Name, CompatibleMode, ShellMode, UniGenCFlag, UniGenBinBuffer, FilterInfo)
1777 if CompatibleMode or UniGenCFlag:
1778 AutoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
1779 AutoGenC.Append(Code)
1780 AutoGenC.Append("\n")
1781 AutoGenH.Append("\n//\n//Unicode String ID\n//\n")
1782 AutoGenH.Append(Header)
1783 if CompatibleMode or UniGenCFlag:
1784 AutoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % Info.Name)
1785 os.chdir(WorkingDir)
1786
1787 def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGenCFlag, IdfGenBinBuffer):
1788 if len(Info.IdfFileList) > 0:
1789 ImageFiles = IdfFileClassObject(sorted (Info.IdfFileList))
1790 if ImageFiles.ImageFilesDict:
1791 Index = 1
1792 PaletteIndex = 1
1793 IncList = [Info.MetaFile.Dir]
1794 SrcList = [F for F in Info.SourceFileList]
1795 SkipList = ['.jpg', '.png', '.bmp', '.inf', '.idf']
1796 FileList = GetFileList(SrcList, IncList, SkipList)
1797 ValueStartPtr = 60
1798 StringH.Append("\n//\n//Image ID\n//\n")
1799 ImageInfoOffset = 0
1800 PaletteInfoOffset = 0
1801 ImageBuffer = pack('x')
1802 PaletteBuffer = pack('x')
1803 BufferStr = ''
1804 PaletteStr = ''
1805 FileDict = {}
1806 for Idf in ImageFiles.ImageFilesDict:
1807 if ImageFiles.ImageFilesDict[Idf]:
1808 for FileObj in ImageFiles.ImageFilesDict[Idf]:
1809 for sourcefile in Info.SourceFileList:
1810 if FileObj.FileName == sourcefile.File:
1811 if not sourcefile.Ext.upper() in ['.PNG', '.BMP', '.JPG']:
1812 EdkLogger.error("build", AUTOGEN_ERROR, "The %s's postfix must be one of .bmp, .jpg, .png" % (FileObj.FileName), ExtraData="[%s]" % str(Info))
1813 FileObj.File = sourcefile
1814 break
1815 else:
1816 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))
1817
1818 for FileObj in ImageFiles.ImageFilesDict[Idf]:
1819 ID = FileObj.ImageID
1820 File = FileObj.File
1821 if not os.path.exists(File.Path) or not os.path.isfile(File.Path):
1822 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=File.Path)
1823 SearchImageID (FileObj, FileList)
1824 if FileObj.Referenced:
1825 if (ValueStartPtr - len(DEFINE_STR + ID)) <= 0:
1826 Line = DEFINE_STR + ' ' + ID + ' ' + DecToHexStr(Index, 4) + '\n'
1827 else:
1828 Line = DEFINE_STR + ' ' + ID + ' ' * (ValueStartPtr - len(DEFINE_STR + ID)) + DecToHexStr(Index, 4) + '\n'
1829
1830 if File not in FileDict:
1831 FileDict[File] = Index
1832 else:
1833 DuplicateBlock = pack('B', EFI_HII_IIBT_DUPLICATE)
1834 DuplicateBlock += pack('H', FileDict[File])
1835 ImageBuffer += DuplicateBlock
1836 BufferStr = WriteLine(BufferStr, '// %s: %s: %s' % (DecToHexStr(Index, 4), ID, DecToHexStr(Index, 4)))
1837 TempBufferList = AscToHexList(DuplicateBlock)
1838 BufferStr = WriteLine(BufferStr, CreateArrayItem(TempBufferList, 16) + '\n')
1839 StringH.Append(Line)
1840 Index += 1
1841 continue
1842
1843 TmpFile = open(File.Path, 'rb')
1844 Buffer = TmpFile.read()
1845 TmpFile.close()
1846 if File.Ext.upper() == '.PNG':
1847 TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_PNG)
1848 TempBuffer += pack('I', len(Buffer))
1849 TempBuffer += Buffer
1850 elif File.Ext.upper() == '.JPG':
1851 ImageType, = struct.unpack('4s', Buffer[6:10])
1852 if ImageType != 'JFIF':
1853 EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard JPG file." % File.Path)
1854 TempBuffer = pack('B', EFI_HII_IIBT_IMAGE_JPEG)
1855 TempBuffer += pack('I', len(Buffer))
1856 TempBuffer += Buffer
1857 elif File.Ext.upper() == '.BMP':
1858 TempBuffer, TempPalette = BmpImageDecoder(File, Buffer, PaletteIndex, FileObj.TransParent)
1859 if len(TempPalette) > 1:
1860 PaletteIndex += 1
1861 NewPalette = pack('H', len(TempPalette))
1862 NewPalette += TempPalette
1863 PaletteBuffer += NewPalette
1864 PaletteStr = WriteLine(PaletteStr, '// %s: %s: %s' % (DecToHexStr(PaletteIndex - 1, 4), ID, DecToHexStr(PaletteIndex - 1, 4)))
1865 TempPaletteList = AscToHexList(NewPalette)
1866 PaletteStr = WriteLine(PaletteStr, CreateArrayItem(TempPaletteList, 16) + '\n')
1867 ImageBuffer += TempBuffer
1868 BufferStr = WriteLine(BufferStr, '// %s: %s: %s' % (DecToHexStr(Index, 4), ID, DecToHexStr(Index, 4)))
1869 TempBufferList = AscToHexList(TempBuffer)
1870 BufferStr = WriteLine(BufferStr, CreateArrayItem(TempBufferList, 16) + '\n')
1871
1872 StringH.Append(Line)
1873 Index += 1
1874
1875 BufferStr = WriteLine(BufferStr, '// End of the Image Info')
1876 BufferStr = WriteLine(BufferStr, CreateArrayItem(DecToHexList(EFI_HII_IIBT_END, 2)) + '\n')
1877 ImageEnd = pack('B', EFI_HII_IIBT_END)
1878 ImageBuffer += ImageEnd
1879
1880 if len(ImageBuffer) > 1:
1881 ImageInfoOffset = 12
1882 if len(PaletteBuffer) > 1:
1883 PaletteInfoOffset = 12 + len(ImageBuffer) - 1 # -1 is for the first empty pad byte of ImageBuffer
1884
1885 IMAGE_PACKAGE_HDR = pack('=II', ImageInfoOffset, PaletteInfoOffset)
1886 # PACKAGE_HEADER_Length = PACKAGE_HEADER + ImageInfoOffset + PaletteInfoOffset + ImageBuffer Length + PaletteCount + PaletteBuffer Length
1887 if len(PaletteBuffer) > 1:
1888 PACKAGE_HEADER_Length = 4 + 4 + 4 + len(ImageBuffer) - 1 + 2 + len(PaletteBuffer) - 1
1889 else:
1890 PACKAGE_HEADER_Length = 4 + 4 + 4 + len(ImageBuffer) - 1
1891 if PaletteIndex > 1:
1892 PALETTE_INFO_HEADER = pack('H', PaletteIndex - 1)
1893 # EFI_HII_PACKAGE_HEADER length max value is 0xFFFFFF
1894 Hex_Length = '%06X' % PACKAGE_HEADER_Length
1895 if PACKAGE_HEADER_Length > 0xFFFFFF:
1896 EdkLogger.error("build", AUTOGEN_ERROR, "The Length of EFI_HII_PACKAGE_HEADER exceed its maximum value", ExtraData="[%s]" % str(Info))
1897 PACKAGE_HEADER = pack('=HBB', int('0x' + Hex_Length[2:], 16), int('0x' + Hex_Length[0:2], 16), EFI_HII_PACKAGE_IMAGES)
1898
1899 IdfGenBinBuffer.write(PACKAGE_HEADER)
1900 IdfGenBinBuffer.write(IMAGE_PACKAGE_HDR)
1901 if len(ImageBuffer) > 1 :
1902 IdfGenBinBuffer.write(ImageBuffer[1:])
1903 if PaletteIndex > 1:
1904 IdfGenBinBuffer.write(PALETTE_INFO_HEADER)
1905 if len(PaletteBuffer) > 1:
1906 IdfGenBinBuffer.write(PaletteBuffer[1:])
1907
1908 if IdfGenCFlag:
1909 TotalLength = EFI_HII_ARRAY_SIZE_LENGTH + PACKAGE_HEADER_Length
1910 AutoGenC.Append("\n//\n//Image Pack Definition\n//\n")
1911 AllStr = WriteLine('', CHAR_ARRAY_DEFIN + ' ' + Info.Module.BaseName + 'Images' + '[] = {\n')
1912 AllStr = WriteLine(AllStr, '// STRGATHER_OUTPUT_HEADER')
1913 AllStr = WriteLine(AllStr, CreateArrayItem(DecToHexList(TotalLength)) + '\n')
1914 AllStr = WriteLine(AllStr, '// Image PACKAGE HEADER\n')
1915 IMAGE_PACKAGE_HDR_List = AscToHexList(PACKAGE_HEADER)
1916 IMAGE_PACKAGE_HDR_List += AscToHexList(IMAGE_PACKAGE_HDR)
1917 AllStr = WriteLine(AllStr, CreateArrayItem(IMAGE_PACKAGE_HDR_List, 16) + '\n')
1918 AllStr = WriteLine(AllStr, '// Image DATA\n')
1919 if BufferStr:
1920 AllStr = WriteLine(AllStr, BufferStr)
1921 if PaletteStr:
1922 AllStr = WriteLine(AllStr, '// Palette Header\n')
1923 PALETTE_INFO_HEADER_List = AscToHexList(PALETTE_INFO_HEADER)
1924 AllStr = WriteLine(AllStr, CreateArrayItem(PALETTE_INFO_HEADER_List, 16) + '\n')
1925 AllStr = WriteLine(AllStr, '// Palette Data\n')
1926 AllStr = WriteLine(AllStr, PaletteStr)
1927 AllStr = WriteLine(AllStr, '};')
1928 AutoGenC.Append(AllStr)
1929 AutoGenC.Append("\n")
1930 StringH.Append('\nextern unsigned char ' + Info.Module.BaseName + 'Images[];\n')
1931 StringH.Append("\n#define IMAGE_ARRAY_NAME %sImages\n" % Info.Module.BaseName)
1932
1933 # typedef struct _EFI_HII_IMAGE_PACKAGE_HDR {
1934 # EFI_HII_PACKAGE_HEADER Header; # Standard package header, where Header.Type = EFI_HII_PACKAGE_IMAGES
1935 # UINT32 ImageInfoOffset;
1936 # UINT32 PaletteInfoOffset;
1937 # } EFI_HII_IMAGE_PACKAGE_HDR;
1938
1939 # typedef struct {
1940 # UINT32 Length:24;
1941 # UINT32 Type:8;
1942 # UINT8 Data[];
1943 # } EFI_HII_PACKAGE_HEADER;
1944
1945 # typedef struct _EFI_HII_IMAGE_BLOCK {
1946 # UINT8 BlockType;
1947 # UINT8 BlockBody[];
1948 # } EFI_HII_IMAGE_BLOCK;
1949
1950 def BmpImageDecoder(File, Buffer, PaletteIndex, TransParent):
1951 ImageType, = struct.unpack('2s', Buffer[0:2])
1952 if ImageType!= 'BM': # BMP file type is 'BM'
1953 EdkLogger.error("build", FILE_TYPE_MISMATCH, "The file %s is not a standard BMP file." % File.Path)
1954 BMP_IMAGE_HEADER = collections.namedtuple('BMP_IMAGE_HEADER', ['bfSize','bfReserved1','bfReserved2','bfOffBits','biSize','biWidth','biHeight','biPlanes','biBitCount', 'biCompression', 'biSizeImage','biXPelsPerMeter','biYPelsPerMeter','biClrUsed','biClrImportant'])
1955 BMP_IMAGE_HEADER_STRUCT = struct.Struct('IHHIIIIHHIIIIII')
1956 BmpHeader = BMP_IMAGE_HEADER._make(BMP_IMAGE_HEADER_STRUCT.unpack_from(Buffer[2:]))
1957 #
1958 # Doesn't support compress.
1959 #
1960 if BmpHeader.biCompression != 0:
1961 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The compress BMP file %s is not support." % File.Path)
1962
1963 # The Width and Height is UINT16 type in Image Package
1964 if BmpHeader.biWidth > 0xFFFF:
1965 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The BMP file %s Width is exceed 0xFFFF." % File.Path)
1966 if BmpHeader.biHeight > 0xFFFF:
1967 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "The BMP file %s Height is exceed 0xFFFF." % File.Path)
1968
1969 PaletteBuffer = pack('x')
1970 if BmpHeader.biBitCount == 1:
1971 if TransParent:
1972 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_1BIT_TRANS)
1973 else:
1974 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_1BIT)
1975 ImageBuffer += pack('B', PaletteIndex)
1976 Width = (BmpHeader.biWidth + 7)/8
1977 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1978 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1979 elif BmpHeader.biBitCount == 4:
1980 if TransParent:
1981 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_4BIT_TRANS)
1982 else:
1983 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_4BIT)
1984 ImageBuffer += pack('B', PaletteIndex)
1985 Width = (BmpHeader.biWidth + 1)/2
1986 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1987 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1988 elif BmpHeader.biBitCount == 8:
1989 if TransParent:
1990 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_8BIT_TRANS)
1991 else:
1992 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_8BIT)
1993 ImageBuffer += pack('B', PaletteIndex)
1994 Width = BmpHeader.biWidth
1995 if BmpHeader.bfOffBits > BMP_IMAGE_HEADER_STRUCT.size + 2:
1996 PaletteBuffer = Buffer[BMP_IMAGE_HEADER_STRUCT.size + 2 : BmpHeader.bfOffBits]
1997 elif BmpHeader.biBitCount == 24:
1998 if TransParent:
1999 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_24BIT_TRANS)
2000 else:
2001 ImageBuffer = pack('B', EFI_HII_IIBT_IMAGE_24BIT)
2002 Width = BmpHeader.biWidth * 3
2003 else:
2004 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "Only support the 1 bit, 4 bit, 8bit, 24 bit BMP files.", ExtraData="[%s]" % str(File.Path))
2005
2006 ImageBuffer += pack('H', BmpHeader.biWidth)
2007 ImageBuffer += pack('H', BmpHeader.biHeight)
2008 Start = BmpHeader.bfOffBits
2009 End = BmpHeader.bfSize - 1
2010 for Height in range(0, BmpHeader.biHeight):
2011 if Width % 4 != 0:
2012 Start = End + (Width % 4) - 4 - Width
2013 else:
2014 Start = End - Width
2015 ImageBuffer += Buffer[Start + 1 : Start + Width + 1]
2016 End = Start
2017
2018 # 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
2019 if PaletteBuffer and len(PaletteBuffer) > 1:
2020 PaletteTemp = pack('x')
2021 for Index in range(0, len(PaletteBuffer)):
2022 if Index % 4 == 3:
2023 continue
2024 PaletteTemp += PaletteBuffer[Index]
2025 PaletteBuffer = PaletteTemp[1:]
2026 return ImageBuffer, PaletteBuffer
2027
2028 ## Create common code
2029 #
2030 # @param Info The ModuleAutoGen object
2031 # @param AutoGenC The TemplateString object for C code
2032 # @param AutoGenH The TemplateString object for header file
2033 #
2034 def CreateHeaderCode(Info, AutoGenC, AutoGenH):
2035 # file header
2036 AutoGenH.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.h'}))
2037 # header file Prologue
2038 AutoGenH.Append(gAutoGenHPrologueString.Replace({'File':'AUTOGENH','Guid':Info.Guid.replace('-','_')}))
2039 AutoGenH.Append(gAutoGenHCppPrologueString)
2040 if Info.AutoGenVersion >= 0x00010005:
2041 # header files includes
2042 AutoGenH.Append("#include <%s>\n" % gBasicHeaderFile)
2043 if Info.ModuleType in gModuleTypeHeaderFile \
2044 and gModuleTypeHeaderFile[Info.ModuleType][0] != gBasicHeaderFile:
2045 AutoGenH.Append("#include <%s>\n" % gModuleTypeHeaderFile[Info.ModuleType][0])
2046 #
2047 # if either PcdLib in [LibraryClasses] sections or there exist Pcd section, add PcdLib.h
2048 # As if modules only uses FixedPcd, then PcdLib is not needed in [LibraryClasses] section.
2049 #
2050 if 'PcdLib' in Info.Module.LibraryClasses or Info.Module.Pcds:
2051 AutoGenH.Append("#include <Library/PcdLib.h>\n")
2052
2053 AutoGenH.Append('\nextern GUID gEfiCallerIdGuid;')
2054 AutoGenH.Append('\nextern CHAR8 *gEfiCallerBaseName;\n\n')
2055
2056 if Info.IsLibrary:
2057 return
2058
2059 AutoGenH.Append("#define EFI_CALLER_ID_GUID \\\n %s\n" % GuidStringToGuidStructureString(Info.Guid))
2060
2061 if Info.IsLibrary:
2062 return
2063 # C file header
2064 AutoGenC.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.c'}))
2065 if Info.AutoGenVersion >= 0x00010005:
2066 # C file header files includes
2067 if Info.ModuleType in gModuleTypeHeaderFile:
2068 for Inc in gModuleTypeHeaderFile[Info.ModuleType]:
2069 AutoGenC.Append("#include <%s>\n" % Inc)
2070 else:
2071 AutoGenC.Append("#include <%s>\n" % gBasicHeaderFile)
2072
2073 #
2074 # Publish the CallerId Guid
2075 #
2076 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(Info.Guid))
2077 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *gEfiCallerBaseName = "%s";\n' % Info.Name)
2078
2079 ## Create common code for header file
2080 #
2081 # @param Info The ModuleAutoGen object
2082 # @param AutoGenC The TemplateString object for C code
2083 # @param AutoGenH The TemplateString object for header file
2084 #
2085 def CreateFooterCode(Info, AutoGenC, AutoGenH):
2086 AutoGenH.Append(gAutoGenHEpilogueString)
2087
2088 ## Create code for a module
2089 #
2090 # @param Info The ModuleAutoGen object
2091 # @param AutoGenC The TemplateString object for C code
2092 # @param AutoGenH The TemplateString object for header file
2093 # @param StringH The TemplateString object for header file
2094 # @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
2095 # @param UniGenBinBuffer Buffer to store uni string package data
2096 # @param StringIdf The TemplateString object for header file
2097 # @param IdfGenCFlag IdfString is generated into AutoGen C file when it is set to True
2098 # @param IdfGenBinBuffer Buffer to store Idf string package data
2099 #
2100 def CreateCode(Info, AutoGenC, AutoGenH, StringH, UniGenCFlag, UniGenBinBuffer, StringIdf, IdfGenCFlag, IdfGenBinBuffer):
2101 CreateHeaderCode(Info, AutoGenC, AutoGenH)
2102
2103 if Info.AutoGenVersion >= 0x00010005:
2104 CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH)
2105 CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH)
2106 CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH)
2107 CreatePcdCode(Info, AutoGenC, AutoGenH)
2108 CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH)
2109 CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH)
2110 CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH)
2111 CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH)
2112
2113 if Info.UnicodeFileList:
2114 FileName = "%sStrDefs.h" % Info.Name
2115 StringH.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
2116 StringH.Append(gAutoGenHPrologueString.Replace({'File':'STRDEFS', 'Guid':Info.Guid.replace('-','_')}))
2117 CreateUnicodeStringCode(Info, AutoGenC, StringH, UniGenCFlag, UniGenBinBuffer)
2118
2119 GuidMacros = []
2120 for Guid in Info.Module.Guids:
2121 if Guid in Info.Module.GetGuidsUsedByPcd():
2122 continue
2123 GuidMacros.append('#define %s %s' % (Guid, Info.Module.Guids[Guid]))
2124 for Guid, Value in Info.Module.Protocols.items() + Info.Module.Ppis.items():
2125 GuidMacros.append('#define %s %s' % (Guid, Value))
2126 # supports FixedAtBuild usage in VFR file
2127 if Info.VfrFileList and Info.ModulePcdList:
2128 GuidMacros.append('#define %s %s' % ('FixedPcdGetBool(TokenName)', '_PCD_VALUE_##TokenName'))
2129 GuidMacros.append('#define %s %s' % ('FixedPcdGet8(TokenName)', '_PCD_VALUE_##TokenName'))
2130 GuidMacros.append('#define %s %s' % ('FixedPcdGet16(TokenName)', '_PCD_VALUE_##TokenName'))
2131 GuidMacros.append('#define %s %s' % ('FixedPcdGet32(TokenName)', '_PCD_VALUE_##TokenName'))
2132 GuidMacros.append('#define %s %s' % ('FixedPcdGet64(TokenName)', '_PCD_VALUE_##TokenName'))
2133 for Pcd in Info.ModulePcdList:
2134 if Pcd.Type == TAB_PCDS_FIXED_AT_BUILD:
2135 TokenCName = Pcd.TokenCName
2136 Value = Pcd.DefaultValue
2137 if Pcd.DatumType == 'BOOLEAN':
2138 BoolValue = Value.upper()
2139 if BoolValue == 'TRUE':
2140 Value = '1'
2141 elif BoolValue == 'FALSE':
2142 Value = '0'
2143 for PcdItem in GlobalData.MixedPcd:
2144 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
2145 TokenCName = PcdItem[0]
2146 break
2147 GuidMacros.append('#define %s %s' % ('_PCD_VALUE_'+TokenCName, Value))
2148
2149 if Info.IdfFileList:
2150 GuidMacros.append('#include "%sImgDefs.h"' % Info.Name)
2151
2152 if GuidMacros:
2153 StringH.Append('\n#ifdef VFRCOMPILE\n%s\n#endif\n' % '\n'.join(GuidMacros))
2154
2155 StringH.Append("\n#endif\n")
2156 AutoGenH.Append('#include "%s"\n' % FileName)
2157
2158 if Info.IdfFileList:
2159 FileName = "%sImgDefs.h" % Info.Name
2160 StringIdf.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
2161 StringIdf.Append(gAutoGenHPrologueString.Replace({'File':'IMAGEDEFS', 'Guid':Info.Guid.replace('-','_')}))
2162 CreateIdfFileCode(Info, AutoGenC, StringIdf, IdfGenCFlag, IdfGenBinBuffer)
2163
2164 StringIdf.Append("\n#endif\n")
2165 AutoGenH.Append('#include "%s"\n' % FileName)
2166
2167 CreateFooterCode(Info, AutoGenC, AutoGenH)
2168
2169 # no generation of AutoGen.c for Edk modules without unicode file
2170 if Info.AutoGenVersion < 0x00010005 and len(Info.UnicodeFileList) == 0:
2171 AutoGenC.String = ''
2172
2173 ## Create the code file
2174 #
2175 # @param FilePath The path of code file
2176 # @param Content The content of code file
2177 # @param IsBinaryFile The flag indicating if the file is binary file or not
2178 #
2179 # @retval True If file content is changed or file doesn't exist
2180 # @retval False If the file exists and the content is not changed
2181 #
2182 def Generate(FilePath, Content, IsBinaryFile):
2183 return SaveFileOnChange(FilePath, Content, IsBinaryFile)
2184