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