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