]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/AutoGen/GenC.py
Sync BaseTool trunk (version r2460) into EDKII BaseTools. The change mainly includes:
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / GenC.py
CommitLineData
30fdf114
LG
1## @file
2# Routines for generating AutoGen.h and AutoGen.c
3#
da92f276 4# Copyright (c) 2007 - 2011, Intel Corporation. All rights reserved.<BR>
40d841f6 5# This program and the accompanying materials
30fdf114
LG
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#
16import string
17
18from Common import EdkLogger
19
20from Common.BuildToolError import *
21from Common.DataType import *
22from Common.Misc import *
23from Common.String import StringToArray
24from StrGather import *
25
26## PCD type string
27gItemTypeStringDatabase = {
28 TAB_PCDS_FEATURE_FLAG : 'FixedAtBuild',
29 TAB_PCDS_FIXED_AT_BUILD : 'FixedAtBuild',
30 TAB_PCDS_PATCHABLE_IN_MODULE: 'BinaryPatch',
31 TAB_PCDS_DYNAMIC : '',
32 TAB_PCDS_DYNAMIC_DEFAULT : '',
33 TAB_PCDS_DYNAMIC_VPD : '',
34 TAB_PCDS_DYNAMIC_HII : '',
35 TAB_PCDS_DYNAMIC_EX : '',
36 TAB_PCDS_DYNAMIC_EX_DEFAULT : '',
37 TAB_PCDS_DYNAMIC_EX_VPD : '',
38 TAB_PCDS_DYNAMIC_EX_HII : '',
39}
40
41## Dynamic PCD types
42gDynamicPcd = [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC_DEFAULT, TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_HII]
43
44## Dynamic-ex PCD types
45gDynamicExPcd = [TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX_DEFAULT, TAB_PCDS_DYNAMIC_EX_VPD, TAB_PCDS_DYNAMIC_EX_HII]
46
47## Datum size
48gDatumSizeStringDatabase = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOLEAN','VOID*':'8'}
49gDatumSizeStringDatabaseH = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOL','VOID*':'PTR'}
50gDatumSizeStringDatabaseLib = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'Bool','VOID*':'Ptr'}
51
52## Mapping between PCD driver type and EFI phase
53gPcdPhaseMap = {
54 "PEI_PCD_DRIVER" : "PEI",
55 "DXE_PCD_DRIVER" : "DXE"
56}
57
58gPcdDatabaseCommonAutoGenH = """
59//
60// The following definition will be generated by build tool
61//
62
63//
64// Common definitions
65//
66typedef UINT8 SKU_ID;
67
68#define PCD_TYPE_SHIFT 28
69
b36d134f
LG
70#define PCD_TYPE_DATA (0x0U << PCD_TYPE_SHIFT)
71#define PCD_TYPE_HII (0x8U << PCD_TYPE_SHIFT)
72#define PCD_TYPE_VPD (0x4U << PCD_TYPE_SHIFT)
73#define PCD_TYPE_SKU_ENABLED (0x2U << PCD_TYPE_SHIFT)
74#define PCD_TYPE_STRING (0x1U << PCD_TYPE_SHIFT)
30fdf114
LG
75
76#define PCD_TYPE_ALL_SET (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_SKU_ENABLED | PCD_TYPE_STRING)
77
78#define PCD_DATUM_TYPE_SHIFT 24
79
b36d134f
LG
80#define PCD_DATUM_TYPE_POINTER (0x0U << PCD_DATUM_TYPE_SHIFT)
81#define PCD_DATUM_TYPE_UINT8 (0x1U << PCD_DATUM_TYPE_SHIFT)
82#define PCD_DATUM_TYPE_UINT16 (0x2U << PCD_DATUM_TYPE_SHIFT)
83#define PCD_DATUM_TYPE_UINT32 (0x4U << PCD_DATUM_TYPE_SHIFT)
84#define PCD_DATUM_TYPE_UINT64 (0x8U << PCD_DATUM_TYPE_SHIFT)
30fdf114
LG
85
86#define PCD_DATUM_TYPE_ALL_SET (PCD_DATUM_TYPE_POINTER | \\
87 PCD_DATUM_TYPE_UINT8 | \\
88 PCD_DATUM_TYPE_UINT16 | \\
89 PCD_DATUM_TYPE_UINT32 | \\
90 PCD_DATUM_TYPE_UINT64)
91
92#define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET))
93
94typedef struct {
95 UINT32 ExTokenNumber;
96 UINT16 LocalTokenNumber; // PCD Number of this particular platform build
97 UINT16 ExGuidIndex; // Index of GuidTable
98} DYNAMICEX_MAPPING;
99
100typedef struct {
101 UINT32 SkuDataStartOffset; //We have to use offsetof MACRO as we don't know padding done by compiler
102 UINT32 SkuIdTableOffset; //Offset from the PCD_DB
103} SKU_HEAD;
104
105typedef struct {
106 UINT16 GuidTableIndex; // Offset in Guid Table in units of GUID.
107 UINT16 StringIndex; // Offset in String Table in units of UINT16.
108 UINT16 Offset; // Offset in Variable
109 UINT16 DefaultValueOffset; // Offset of the Default Value
110} VARIABLE_HEAD;
111
112typedef struct {
113 UINT32 Offset;
114} VPD_HEAD;
115
116typedef UINT16 STRING_HEAD;
117
118typedef UINT16 SIZE_INFO;
119
120#define offsetof(s,m) (UINT32) (UINTN) &(((s *)0)->m)
121
122"""
123
124gPcdDatabaseEpilogueAutoGenH = """
125typedef struct {
126 PEI_PCD_DATABASE PeiDb;
127 DXE_PCD_DATABASE DxeDb;
128} PCD_DATABASE;
129
130#define PCD_TOTAL_TOKEN_NUMBER (PEI_LOCAL_TOKEN_NUMBER + DXE_LOCAL_TOKEN_NUMBER)
131
132"""
133
134gPcdDatabaseAutoGenH = TemplateString("""
135#define ${PHASE}_GUID_TABLE_SIZE ${GUID_TABLE_SIZE}
136#define ${PHASE}_STRING_TABLE_SIZE ${STRING_TABLE_SIZE}
137#define ${PHASE}_SKUID_TABLE_SIZE ${SKUID_TABLE_SIZE}
138#define ${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE ${LOCAL_TOKEN_NUMBER_TABLE_SIZE}
139#define ${PHASE}_LOCAL_TOKEN_NUMBER ${LOCAL_TOKEN_NUMBER}
140#define ${PHASE}_EXMAPPING_TABLE_SIZE ${EXMAPPING_TABLE_SIZE}
141#define ${PHASE}_EX_TOKEN_NUMBER ${EX_TOKEN_NUMBER}
142#define ${PHASE}_SIZE_TABLE_SIZE ${SIZE_TABLE_SIZE}
143#define ${PHASE}_GUID_TABLE_EMPTY ${GUID_TABLE_EMPTY}
144#define ${PHASE}_STRING_TABLE_EMPTY ${STRING_TABLE_EMPTY}
145#define ${PHASE}_SKUID_TABLE_EMPTY ${SKUID_TABLE_EMPTY}
146#define ${PHASE}_DATABASE_EMPTY ${DATABASE_EMPTY}
147#define ${PHASE}_EXMAP_TABLE_EMPTY ${EXMAP_TABLE_EMPTY}
148
149typedef struct {
150${BEGIN} UINT64 ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}];
151${END}
152${BEGIN} UINT64 ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64};
153${END}
154${BEGIN} UINT32 ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}];
155${END}
156${BEGIN} UINT32 ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32};
157${END}
158${BEGIN} VPD_HEAD ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}];
159${END}
160 DYNAMICEX_MAPPING ExMapTable[${PHASE}_EXMAPPING_TABLE_SIZE];
161 UINT32 LocalTokenNumberTable[${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE];
162 GUID GuidTable[${PHASE}_GUID_TABLE_SIZE];
163${BEGIN} STRING_HEAD ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}];
164${END}
52302d4d 165${BEGIN} VARIABLE_HEAD ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}];
30fdf114
LG
166${END}
167${BEGIN} UINT8 StringTable${STRING_TABLE_INDEX}[${STRING_TABLE_LENGTH}]; /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
168${END}
169 SIZE_INFO SizeTable[${PHASE}_SIZE_TABLE_SIZE];
170${BEGIN} UINT16 ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}];
171${END}
172${BEGIN} UINT16 ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16};
173${END}
174${BEGIN} UINT8 ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}];
175${END}
176${BEGIN} UINT8 ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8};
177${END}
178${BEGIN} BOOLEAN ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}];
179${END}
180${BEGIN} BOOLEAN ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN};
181${END}
182 UINT8 SkuIdTable[${PHASE}_SKUID_TABLE_SIZE];
183${SYSTEM_SKU_ID}
184} ${PHASE}_PCD_DATABASE_INIT;
185
186typedef struct {
187${PCD_DATABASE_UNINIT_EMPTY}
188${BEGIN} UINT64 ${UNINIT_CNAME_DECL_UINT64}_${UNINIT_GUID_DECL_UINT64}[${UNINIT_NUMSKUS_DECL_UINT64}];
189${END}
190${BEGIN} UINT32 ${UNINIT_CNAME_DECL_UINT32}_${UNINIT_GUID_DECL_UINT32}[${UNINIT_NUMSKUS_DECL_UINT32}];
191${END}
192${BEGIN} UINT16 ${UNINIT_CNAME_DECL_UINT16}_${UNINIT_GUID_DECL_UINT16}[${UNINIT_NUMSKUS_DECL_UINT16}];
193${END}
194${BEGIN} UINT8 ${UNINIT_CNAME_DECL_UINT8}_${UNINIT_GUID_DECL_UINT8}[${UNINIT_NUMSKUS_DECL_UINT8}];
195${END}
196${BEGIN} BOOLEAN ${UNINIT_CNAME_DECL_BOOLEAN}_${UNINIT_GUID_DECL_BOOLEAN}[${UNINIT_NUMSKUS_DECL_BOOLEAN}];
197${END}
198} ${PHASE}_PCD_DATABASE_UNINIT;
199
200#define PCD_${PHASE}_SERVICE_DRIVER_VERSION 2
201
202typedef struct {
203 ${PHASE}_PCD_DATABASE_INIT Init;
204 ${PHASE}_PCD_DATABASE_UNINIT Uninit;
205} ${PHASE}_PCD_DATABASE;
206
207#define ${PHASE}_NEX_TOKEN_NUMBER (${PHASE}_LOCAL_TOKEN_NUMBER - ${PHASE}_EX_TOKEN_NUMBER)
208""")
209
210gEmptyPcdDatabaseAutoGenC = TemplateString("""
211${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
212 /* ExMapTable */
213 {
214 {0, 0, 0}
215 },
216 /* LocalTokenNumberTable */
217 {
218 0
219 },
220 /* GuidTable */
221 {
222 {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}
223 },
224 /* StringTable */
225 { 0 },
226 /* SizeTable */
227 {
228 0, 0
229 },
230 /* SkuIdTable */
231 { 0 },
232 ${SYSTEM_SKU_ID_VALUE}
233};
234""")
235
236gPcdDatabaseAutoGenC = TemplateString("""
237${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
238${BEGIN} { ${INIT_VALUE_UINT64} }, /* ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}] */
239${END}
240${BEGIN} ${VARDEF_VALUE_UINT64}, /* ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64} */
241${END}
242${BEGIN} { ${INIT_VALUE_UINT32} }, /* ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}] */
243${END}
244${BEGIN} ${VARDEF_VALUE_UINT32}, /* ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32} */
245${END}
246 /* VPD */
247${BEGIN} { ${VPD_HEAD_VALUE} }, /* ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}] */
248${END}
249 /* ExMapTable */
250 {
251${BEGIN} { ${EXMAPPING_TABLE_EXTOKEN}, ${EXMAPPING_TABLE_LOCAL_TOKEN}, ${EXMAPPING_TABLE_GUID_INDEX} },
252${END}
253 },
254 /* LocalTokenNumberTable */
255 {
52302d4d 256${BEGIN} offsetof(${PHASE}_PCD_DATABASE, ${TOKEN_INIT}.${TOKEN_CNAME}_${TOKEN_GUID}${VARDEF_HEADER}) | ${TOKEN_TYPE},
30fdf114
LG
257${END}
258 },
259 /* GuidTable */
260 {
261${BEGIN} ${GUID_STRUCTURE},
262${END}
263 },
264${BEGIN} { ${STRING_HEAD_VALUE} }, /* ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}] */
265${END}
52302d4d 266${BEGIN} /* ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}] */
30fdf114
LG
267 {
268 ${VARIABLE_HEAD_VALUE}
269 },
270${END}
271 /* StringTable */
272${BEGIN} ${STRING_TABLE_VALUE}, /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
273${END}
274 /* SizeTable */
275 {
276${BEGIN} ${SIZE_TABLE_MAXIMUM_LENGTH}, ${SIZE_TABLE_CURRENT_LENGTH}, /* ${SIZE_TABLE_CNAME}_${SIZE_TABLE_GUID} */
277${END}
278 },
279${BEGIN} { ${INIT_VALUE_UINT16} }, /* ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}] */
280${END}
281${BEGIN} ${VARDEF_VALUE_UINT16}, /* ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16} */
282${END}
283${BEGIN} { ${INIT_VALUE_UINT8} }, /* ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}] */
284${END}
285${BEGIN} ${VARDEF_VALUE_UINT8}, /* ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8} */
286${END}
287${BEGIN} { ${INIT_VALUE_BOOLEAN} }, /* ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}] */
288${END}
289${BEGIN} ${VARDEF_VALUE_BOOLEAN}, /* ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN} */
290${END}
291 /* SkuIdTable */
292 { ${BEGIN}${SKUID_VALUE}, ${END} },
293 ${SYSTEM_SKU_ID_VALUE}
294};
295""")
296
297
298## AutoGen File Header Templates
299gAutoGenHeaderString = TemplateString("""\
300/**
301 DO NOT EDIT
302 FILE auto-generated
303 Module name:
304 ${FileName}
305 Abstract: Auto-generated ${FileName} for building module or library.
306**/
307""")
308
309gAutoGenHPrologueString = TemplateString("""
310#ifndef _${File}_${Guid}
311#define _${File}_${Guid}
312
2bcc713e
LG
313""")
314
d0acc87a 315gAutoGenHCppPrologueString = """\
d40b2ee6
LG
316#ifdef __cplusplus
317extern "C" {
318#endif
319
2bcc713e 320"""
30fdf114
LG
321
322gAutoGenHEpilogueString = """
d40b2ee6
LG
323
324#ifdef __cplusplus
325}
326#endif
327
30fdf114
LG
328#endif
329"""
330
331## PEI Core Entry Point Templates
332gPeiCoreEntryPointPrototype = TemplateString("""
333${BEGIN}
334VOID
335EFIAPI
336${Function} (
337 IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData,
338 IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList,
339 IN VOID *Context
340 );
341${END}
342""")
343
344gPeiCoreEntryPointString = TemplateString("""
345${BEGIN}
346VOID
347EFIAPI
348ProcessModuleEntryPointList (
349 IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData,
350 IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList,
351 IN VOID *Context
352 )
353
354{
355 ${Function} (SecCoreData, PpiList, Context);
356}
357${END}
358""")
359
360
361## DXE Core Entry Point Templates
362gDxeCoreEntryPointPrototype = TemplateString("""
363${BEGIN}
364VOID
365EFIAPI
366${Function} (
367 IN VOID *HobStart
368 );
369${END}
370""")
371
372gDxeCoreEntryPointString = TemplateString("""
373${BEGIN}
374VOID
375EFIAPI
376ProcessModuleEntryPointList (
377 IN VOID *HobStart
378 )
379
380{
381 ${Function} (HobStart);
382}
383${END}
384""")
385
386## PEIM Entry Point Templates
387gPeimEntryPointPrototype = TemplateString("""
388${BEGIN}
389EFI_STATUS
390EFIAPI
391${Function} (
392 IN EFI_PEI_FILE_HANDLE FileHandle,
393 IN CONST EFI_PEI_SERVICES **PeiServices
394 );
395${END}
396""")
397
30fdf114
LG
398gPeimEntryPointString = [
399TemplateString("""
400GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
401
402EFI_STATUS
403EFIAPI
404ProcessModuleEntryPointList (
405 IN EFI_PEI_FILE_HANDLE FileHandle,
406 IN CONST EFI_PEI_SERVICES **PeiServices
407 )
408
409{
410 return EFI_SUCCESS;
411}
412"""),
413TemplateString("""
414GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
415${BEGIN}
416EFI_STATUS
417EFIAPI
418ProcessModuleEntryPointList (
419 IN EFI_PEI_FILE_HANDLE FileHandle,
420 IN CONST EFI_PEI_SERVICES **PeiServices
421 )
422
423{
424 return ${Function} (FileHandle, PeiServices);
425}
426${END}
427"""),
428TemplateString("""
429GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
430
431EFI_STATUS
432EFIAPI
433ProcessModuleEntryPointList (
434 IN EFI_PEI_FILE_HANDLE FileHandle,
435 IN CONST EFI_PEI_SERVICES **PeiServices
436 )
437
438{
439 EFI_STATUS Status;
440 EFI_STATUS CombinedStatus;
441
442 CombinedStatus = EFI_LOAD_ERROR;
443${BEGIN}
444 Status = ${Function} (FileHandle, PeiServices);
445 if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {
446 CombinedStatus = Status;
447 }
448${END}
449 return CombinedStatus;
450}
451""")
452]
453
b303ea72
LG
454## SMM_CORE Entry Point Templates
455gSmmCoreEntryPointPrototype = TemplateString("""
456${BEGIN}
457EFI_STATUS
458EFIAPI
459${Function} (
460 IN EFI_HANDLE ImageHandle,
461 IN EFI_SYSTEM_TABLE *SystemTable
462 );
463${END}
464""")
465
466gSmmCoreEntryPointString = TemplateString("""
467${BEGIN}
52302d4d 468const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
b303ea72
LG
469const UINT32 _gDxeRevision = ${PiSpecVersion};
470
471EFI_STATUS
472EFIAPI
473ProcessModuleEntryPointList (
474 IN EFI_HANDLE ImageHandle,
475 IN EFI_SYSTEM_TABLE *SystemTable
476 )
477{
478 return ${Function} (ImageHandle, SystemTable);
479}
480${END}
481""")
482
30fdf114
LG
483## DXE SMM Entry Point Templates
484gDxeSmmEntryPointPrototype = TemplateString("""
485${BEGIN}
486EFI_STATUS
487EFIAPI
488${Function} (
489 IN EFI_HANDLE ImageHandle,
490 IN EFI_SYSTEM_TABLE *SystemTable
491 );
492${END}
493""")
494
495gDxeSmmEntryPointString = [
496TemplateString("""
52302d4d 497const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
498const UINT32 _gDxeRevision = ${PiSpecVersion};
499
500EFI_STATUS
501EFIAPI
502ProcessModuleEntryPointList (
503 IN EFI_HANDLE ImageHandle,
504 IN EFI_SYSTEM_TABLE *SystemTable
505 )
506
507{
508 return EFI_SUCCESS;
509}
510"""),
511TemplateString("""
52302d4d 512const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
513const UINT32 _gDxeRevision = ${PiSpecVersion};
514
515static BASE_LIBRARY_JUMP_BUFFER mJumpContext;
52302d4d 516static EFI_STATUS mDriverEntryPointStatus;
30fdf114
LG
517
518VOID
519EFIAPI
520ExitDriver (
521 IN EFI_STATUS Status
522 )
523{
524 if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
525 mDriverEntryPointStatus = Status;
526 }
527 LongJump (&mJumpContext, (UINTN)-1);
528 ASSERT (FALSE);
529}
530
531EFI_STATUS
532EFIAPI
533ProcessModuleEntryPointList (
534 IN EFI_HANDLE ImageHandle,
535 IN EFI_SYSTEM_TABLE *SystemTable
536 )
30fdf114 537{
52302d4d
LG
538 mDriverEntryPointStatus = EFI_LOAD_ERROR;
539
30fdf114
LG
540${BEGIN}
541 if (SetJump (&mJumpContext) == 0) {
542 ExitDriver (${Function} (ImageHandle, SystemTable));
543 ASSERT (FALSE);
544 }
545${END}
546
547 return mDriverEntryPointStatus;
548}
549""")
550]
551
552## UEFI Driver Entry Point Templates
553gUefiDriverEntryPointPrototype = TemplateString("""
554${BEGIN}
555EFI_STATUS
556EFIAPI
557${Function} (
558 IN EFI_HANDLE ImageHandle,
559 IN EFI_SYSTEM_TABLE *SystemTable
560 );
561${END}
562""")
563
564gUefiDriverEntryPointString = [
565TemplateString("""
52302d4d 566const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
567const UINT32 _gDxeRevision = ${PiSpecVersion};
568
569EFI_STATUS
570EFIAPI
571ProcessModuleEntryPointList (
572 IN EFI_HANDLE ImageHandle,
573 IN EFI_SYSTEM_TABLE *SystemTable
574 )
575{
576 return EFI_SUCCESS;
577}
578"""),
579TemplateString("""
52302d4d 580const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
581const UINT32 _gDxeRevision = ${PiSpecVersion};
582
583${BEGIN}
584EFI_STATUS
585EFIAPI
586ProcessModuleEntryPointList (
587 IN EFI_HANDLE ImageHandle,
588 IN EFI_SYSTEM_TABLE *SystemTable
589 )
590
591{
592 return ${Function} (ImageHandle, SystemTable);
593}
594${END}
595VOID
596EFIAPI
597ExitDriver (
598 IN EFI_STATUS Status
599 )
600{
601 if (EFI_ERROR (Status)) {
602 ProcessLibraryDestructorList (gImageHandle, gST);
603 }
604 gBS->Exit (gImageHandle, Status, 0, NULL);
605}
606"""),
607TemplateString("""
52302d4d 608const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
609const UINT32 _gDxeRevision = ${PiSpecVersion};
610
52302d4d
LG
611static BASE_LIBRARY_JUMP_BUFFER mJumpContext;
612static EFI_STATUS mDriverEntryPointStatus;
613
30fdf114
LG
614EFI_STATUS
615EFIAPI
616ProcessModuleEntryPointList (
617 IN EFI_HANDLE ImageHandle,
618 IN EFI_SYSTEM_TABLE *SystemTable
619 )
30fdf114 620{
52302d4d 621 mDriverEntryPointStatus = EFI_LOAD_ERROR;
30fdf114
LG
622 ${BEGIN}
623 if (SetJump (&mJumpContext) == 0) {
624 ExitDriver (${Function} (ImageHandle, SystemTable));
625 ASSERT (FALSE);
626 }
627 ${END}
628 return mDriverEntryPointStatus;
629}
630
30fdf114
LG
631VOID
632EFIAPI
633ExitDriver (
634 IN EFI_STATUS Status
635 )
636{
637 if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
638 mDriverEntryPointStatus = Status;
639 }
640 LongJump (&mJumpContext, (UINTN)-1);
641 ASSERT (FALSE);
642}
643""")
644]
645
646
647## UEFI Application Entry Point Templates
648gUefiApplicationEntryPointPrototype = TemplateString("""
649${BEGIN}
650EFI_STATUS
651EFIAPI
652${Function} (
653 IN EFI_HANDLE ImageHandle,
654 IN EFI_SYSTEM_TABLE *SystemTable
655 );
656${END}
657""")
658
659gUefiApplicationEntryPointString = [
660TemplateString("""
52302d4d 661const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
662
663EFI_STATUS
664EFIAPI
665ProcessModuleEntryPointList (
666 IN EFI_HANDLE ImageHandle,
667 IN EFI_SYSTEM_TABLE *SystemTable
668 )
669{
670 return EFI_SUCCESS;
671}
672"""),
673TemplateString("""
52302d4d 674const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
675
676${BEGIN}
677EFI_STATUS
678EFIAPI
679ProcessModuleEntryPointList (
680 IN EFI_HANDLE ImageHandle,
681 IN EFI_SYSTEM_TABLE *SystemTable
682 )
683
684{
685 return ${Function} (ImageHandle, SystemTable);
686}
687${END}
688VOID
689EFIAPI
690ExitDriver (
691 IN EFI_STATUS Status
692 )
693{
694 if (EFI_ERROR (Status)) {
695 ProcessLibraryDestructorList (gImageHandle, gST);
696 }
697 gBS->Exit (gImageHandle, Status, 0, NULL);
698}
699"""),
700TemplateString("""
52302d4d 701const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
30fdf114
LG
702
703EFI_STATUS
704EFIAPI
705ProcessModuleEntryPointList (
706 IN EFI_HANDLE ImageHandle,
707 IN EFI_SYSTEM_TABLE *SystemTable
708 )
709
710{
711 ${BEGIN}
712 if (SetJump (&mJumpContext) == 0) {
713 ExitDriver (${Function} (ImageHandle, SystemTable));
714 ASSERT (FALSE);
715 }
716 ${END}
717 return mDriverEntryPointStatus;
718}
719
720static BASE_LIBRARY_JUMP_BUFFER mJumpContext;
721static EFI_STATUS mDriverEntryPointStatus = EFI_LOAD_ERROR;
722
723VOID
724EFIAPI
725ExitDriver (
726 IN EFI_STATUS Status
727 )
728{
729 if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
730 mDriverEntryPointStatus = Status;
731 }
732 LongJump (&mJumpContext, (UINTN)-1);
733 ASSERT (FALSE);
734}
735""")
736]
737
738## UEFI Unload Image Templates
739gUefiUnloadImagePrototype = TemplateString("""
740${BEGIN}
741EFI_STATUS
742EFIAPI
743${Function} (
744 IN EFI_HANDLE ImageHandle
745 );
746${END}
747""")
748
749gUefiUnloadImageString = [
750TemplateString("""
751GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
752
753EFI_STATUS
754EFIAPI
755ProcessModuleUnloadList (
756 IN EFI_HANDLE ImageHandle
757 )
758{
759 return EFI_SUCCESS;
760}
761"""),
762TemplateString("""
763GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
764
765${BEGIN}
766EFI_STATUS
767EFIAPI
768ProcessModuleUnloadList (
769 IN EFI_HANDLE ImageHandle
770 )
771{
772 return ${Function} (ImageHandle);
773}
774${END}
775"""),
776TemplateString("""
777GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
778
779EFI_STATUS
780EFIAPI
781ProcessModuleUnloadList (
782 IN EFI_HANDLE ImageHandle
783 )
784{
785 EFI_STATUS Status;
786
787 Status = EFI_SUCCESS;
788${BEGIN}
789 if (EFI_ERROR (Status)) {
790 ${Function} (ImageHandle);
791 } else {
792 Status = ${Function} (ImageHandle);
793 }
794${END}
795 return Status;
796}
797""")
798]
799
800gLibraryStructorPrototype = {
801'BASE' : TemplateString("""${BEGIN}
802RETURN_STATUS
803EFIAPI
804${Function} (
805 VOID
806 );${END}
807"""),
808
809'PEI' : TemplateString("""${BEGIN}
810EFI_STATUS
811EFIAPI
812${Function} (
813 IN EFI_PEI_FILE_HANDLE FileHandle,
814 IN CONST EFI_PEI_SERVICES **PeiServices
815 );${END}
816"""),
817
818'DXE' : TemplateString("""${BEGIN}
819EFI_STATUS
820EFIAPI
821${Function} (
822 IN EFI_HANDLE ImageHandle,
823 IN EFI_SYSTEM_TABLE *SystemTable
824 );${END}
825"""),
826}
827
828gLibraryStructorCall = {
829'BASE' : TemplateString("""${BEGIN}
830 Status = ${Function} ();
831 ASSERT_EFI_ERROR (Status);${END}
832"""),
833
834'PEI' : TemplateString("""${BEGIN}
835 Status = ${Function} (FileHandle, PeiServices);
836 ASSERT_EFI_ERROR (Status);${END}
837"""),
838
839'DXE' : TemplateString("""${BEGIN}
840 Status = ${Function} (ImageHandle, SystemTable);
841 ASSERT_EFI_ERROR (Status);${END}
842"""),
843}
844
845## Library Constructor and Destructor Templates
846gLibraryString = {
847'BASE' : TemplateString("""
848${BEGIN}${FunctionPrototype}${END}
849
850VOID
851EFIAPI
852ProcessLibrary${Type}List (
853 VOID
854 )
855{
856${BEGIN} EFI_STATUS Status;
857${FunctionCall}${END}
858}
859"""),
860
861'PEI' : TemplateString("""
862${BEGIN}${FunctionPrototype}${END}
863
864VOID
865EFIAPI
866ProcessLibrary${Type}List (
867 IN EFI_PEI_FILE_HANDLE FileHandle,
868 IN CONST EFI_PEI_SERVICES **PeiServices
869 )
870{
871${BEGIN} EFI_STATUS Status;
872${FunctionCall}${END}
873}
874"""),
875
876'DXE' : TemplateString("""
877${BEGIN}${FunctionPrototype}${END}
878
879VOID
880EFIAPI
881ProcessLibrary${Type}List (
882 IN EFI_HANDLE ImageHandle,
883 IN EFI_SYSTEM_TABLE *SystemTable
884 )
885{
886${BEGIN} EFI_STATUS Status;
887${FunctionCall}${END}
888}
889"""),
890}
891
30fdf114
LG
892gBasicHeaderFile = "Base.h"
893
894gModuleTypeHeaderFile = {
895 "BASE" : [gBasicHeaderFile],
896 "SEC" : ["PiPei.h", "Library/DebugLib.h"],
897 "PEI_CORE" : ["PiPei.h", "Library/DebugLib.h", "Library/PeiCoreEntryPoint.h"],
898 "PEIM" : ["PiPei.h", "Library/DebugLib.h", "Library/PeimEntryPoint.h"],
899 "DXE_CORE" : ["PiDxe.h", "Library/DebugLib.h", "Library/DxeCoreEntryPoint.h"],
900 "DXE_DRIVER" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
901 "DXE_SMM_DRIVER" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
902 "DXE_RUNTIME_DRIVER": ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
903 "DXE_SAL_DRIVER" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
904 "UEFI_DRIVER" : ["Uefi.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
905 "UEFI_APPLICATION" : ["Uefi.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiApplicationEntryPoint.h"],
b303ea72 906 "SMM_CORE" : ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiDriverEntryPoint.h"],
30fdf114
LG
907 "USER_DEFINED" : [gBasicHeaderFile]
908}
909
910## Create code for module PCDs
911#
912# @param Info The ModuleAutoGen object
913# @param AutoGenC The TemplateString object for C code
914# @param AutoGenH The TemplateString object for header file
915# @param Pcd The PCD object
916#
917def CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd):
918 TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue #Info.GuidList[Pcd.TokenSpaceGuidCName]
919 PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
920 #
921 # Write PCDs
922 #
923 PcdTokenName = '_PCD_TOKEN_' + Pcd.TokenCName
924 if Pcd.Type in gDynamicExPcd:
925 TokenNumber = int(Pcd.TokenValue, 0)
926 else:
927 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
928 EdkLogger.error("build", AUTOGEN_ERROR,
929 "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
930 ExtraData="[%s]" % str(Info))
931 TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
d40b2ee6 932 AutoGenH.Append('\n#define %s %dU\n' % (PcdTokenName, TokenNumber))
30fdf114
LG
933
934 EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for " + Pcd.TokenCName + "." + Pcd.TokenSpaceGuidCName)
935 if Pcd.Type not in gItemTypeStringDatabase:
936 EdkLogger.error("build", AUTOGEN_ERROR,
937 "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
938 ExtraData="[%s]" % str(Info))
939 if Pcd.DatumType not in gDatumSizeStringDatabase:
940 EdkLogger.error("build", AUTOGEN_ERROR,
941 "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
942 ExtraData="[%s]" % str(Info))
943
944 DatumSize = gDatumSizeStringDatabase[Pcd.DatumType]
945 DatumSizeLib = gDatumSizeStringDatabaseLib[Pcd.DatumType]
946 GetModeName = '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + Pcd.TokenCName
947 SetModeName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + Pcd.TokenCName
948
949 if Pcd.Type in gDynamicExPcd:
950 AutoGenH.Append('#define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
951 if Pcd.DatumType == 'VOID*':
952 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
953 else:
954 AutoGenH.Append('#define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
955 elif Pcd.Type in gDynamicPcd:
956 AutoGenH.Append('#define %s LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
957 if Pcd.DatumType == 'VOID*':
958 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
959 else:
960 AutoGenH.Append('#define %s(Value) LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
961 else:
962 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + Pcd.TokenCName
963 Const = 'const'
964 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
965 Const = ''
966 Type = ''
967 Array = ''
52302d4d 968 Value = Pcd.DefaultValue
30fdf114 969 Unicode = False
52302d4d 970 ValueNumber = 0
0d2711a6
LG
971
972 if Pcd.DatumType == 'BOOLEAN':
973 BoolValue = Value.upper()
d0acc87a 974 if BoolValue == 'TRUE' or BoolValue == '1':
d40b2ee6 975 Value = '1U'
d0acc87a 976 elif BoolValue == 'FALSE' or BoolValue == '0':
d40b2ee6 977 Value = '0U'
0d2711a6 978
52302d4d
LG
979 if Pcd.DatumType in ['UINT64', 'UINT32', 'UINT16', 'UINT8']:
980 try:
981 if Value.upper().startswith('0X'):
982 ValueNumber = int (Value, 16)
983 else:
984 ValueNumber = int (Value)
985 except:
986 EdkLogger.error("build", AUTOGEN_ERROR,
987 "PCD value is not valid dec or hex number for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
988 ExtraData="[%s]" % str(Info))
989 if Pcd.DatumType == 'UINT64':
990 if ValueNumber < 0:
991 EdkLogger.error("build", AUTOGEN_ERROR,
992 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
993 ExtraData="[%s]" % str(Info))
994 elif ValueNumber >= 0x10000000000000000:
995 EdkLogger.error("build", AUTOGEN_ERROR,
996 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
997 ExtraData="[%s]" % str(Info))
998 if not Value.endswith('ULL'):
999 Value += 'ULL'
1000 elif Pcd.DatumType == 'UINT32':
1001 if ValueNumber < 0:
1002 EdkLogger.error("build", AUTOGEN_ERROR,
1003 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1004 ExtraData="[%s]" % str(Info))
1005 elif ValueNumber >= 0x100000000:
1006 EdkLogger.error("build", AUTOGEN_ERROR,
1007 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1008 ExtraData="[%s]" % str(Info))
d40b2ee6
LG
1009 if not Value.endswith('U'):
1010 Value += 'U'
52302d4d
LG
1011 elif Pcd.DatumType == 'UINT16':
1012 if ValueNumber < 0:
1013 EdkLogger.error("build", AUTOGEN_ERROR,
1014 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1015 ExtraData="[%s]" % str(Info))
1016 elif ValueNumber >= 0x10000:
1017 EdkLogger.error("build", AUTOGEN_ERROR,
1018 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1019 ExtraData="[%s]" % str(Info))
d40b2ee6
LG
1020 if not Value.endswith('U'):
1021 Value += 'U'
52302d4d
LG
1022 elif Pcd.DatumType == 'UINT8':
1023 if ValueNumber < 0:
1024 EdkLogger.error("build", AUTOGEN_ERROR,
1025 "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1026 ExtraData="[%s]" % str(Info))
1027 elif ValueNumber >= 0x100:
1028 EdkLogger.error("build", AUTOGEN_ERROR,
1029 "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1030 ExtraData="[%s]" % str(Info))
d40b2ee6
LG
1031 if not Value.endswith('U'):
1032 Value += 'U'
30fdf114
LG
1033 if Pcd.DatumType == 'VOID*':
1034 if Pcd.MaxDatumSize == None or Pcd.MaxDatumSize == '':
1035 EdkLogger.error("build", AUTOGEN_ERROR,
1036 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1037 ExtraData="[%s]" % str(Info))
1038
1039 ArraySize = int(Pcd.MaxDatumSize, 0)
1040 if Value[0] == '{':
1041 Type = '(VOID *)'
52302d4d 1042 else:
30fdf114
LG
1043 if Value[0] == 'L':
1044 Unicode = True
1045 Value = Value.lstrip('L') #.strip('"')
1046 Value = eval(Value) # translate escape character
1047 NewValue = '{'
1048 for Index in range(0,len(Value)):
1049 if Unicode:
52302d4d
LG
1050 NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ', '
1051 else:
30fdf114 1052 NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
52302d4d
LG
1053 if Unicode:
1054 ArraySize = ArraySize / 2;
1055
30fdf114 1056 if ArraySize < (len(Value) + 1):
e56468c0 1057 EdkLogger.error("build", AUTOGEN_ERROR,
1058 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1059 ExtraData="[%s]" % str(Info))
52302d4d 1060 Value = NewValue + '0 }'
30fdf114
LG
1061 Array = '[%d]' % ArraySize
1062 #
1063 # skip casting for fixed at build since it breaks ARM assembly.
1064 # Long term we need PCD macros that work in assembly
1065 #
1066 elif Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:
1067 Value = "((%s)%s)" % (Pcd.DatumType, Value)
1068
1069 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1070 PcdValueName = '_PCD_PATCHABLE_VALUE_' + Pcd.TokenCName
1071 else:
1072 PcdValueName = '_PCD_VALUE_' + Pcd.TokenCName
1073
52302d4d
LG
1074 if Pcd.DatumType == 'VOID*':
1075 #
1076 # For unicode, UINT16 array will be generated, so the alignment of unicode is guaranteed.
1077 #
1078 if Unicode:
1079 AutoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (Pcd.TokenCName, Pcd.MaxDatumSize))
1080 AutoGenH.Append('#define %s %s%s\n' %(PcdValueName, Type, PcdVariableName))
1081 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT16 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
1082 AutoGenH.Append('extern %s UINT16 %s%s;\n' %(Const, PcdVariableName, Array))
1083 AutoGenH.Append('#define %s %s%s\n' %(GetModeName, Type, PcdVariableName))
30fdf114
LG
1084 else:
1085 AutoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (Pcd.TokenCName, Pcd.MaxDatumSize))
1086 AutoGenH.Append('#define %s %s%s\n' %(PcdValueName, Type, PcdVariableName))
1087 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
1088 AutoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
1089 AutoGenH.Append('#define %s %s%s\n' %(GetModeName, Type, PcdVariableName))
1090 elif Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1091 AutoGenH.Append('#define %s %s\n' %(PcdValueName, Value))
52302d4d 1092 AutoGenC.Append('volatile %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
30fdf114
LG
1093 AutoGenH.Append('extern volatile %s %s %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
1094 AutoGenH.Append('#define %s %s%s\n' % (GetModeName, Type, PcdVariableName))
1095 else:
1096 AutoGenH.Append('#define %s %s\n' %(PcdValueName, Value))
1097 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
1098 AutoGenH.Append('extern %s %s %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
1099 AutoGenH.Append('#define %s %s%s\n' % (GetModeName, Type, PcdVariableName))
1100
1101 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1102 if Pcd.DatumType == 'VOID*':
1103 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPatchPcdSetPtr(_gPcd_BinaryPatch_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeName, Pcd.TokenCName, Pcd.TokenCName))
1104 else:
1105 AutoGenH.Append('#define %s(Value) (%s = (Value))\n' % (SetModeName, PcdVariableName))
1106 else:
1107 AutoGenH.Append('//#define %s ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)
1108
1109## Create code for library module PCDs
1110#
1111# @param Info The ModuleAutoGen object
1112# @param AutoGenC The TemplateString object for C code
1113# @param AutoGenH The TemplateString object for header file
1114# @param Pcd The PCD object
1115#
1116def CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd):
1117 PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
1118 TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1119 TokenCName = Pcd.TokenCName
1120 TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue #Info.GuidList[TokenSpaceGuidCName]
1121 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
1122 EdkLogger.error("build", AUTOGEN_ERROR,
1123 "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1124 ExtraData="[%s]" % str(Info))
1125 TokenNumber = PcdTokenNumber[TokenCName, TokenSpaceGuidCName]
1126
da92f276
LG
1127 # If PCD is DynamicEx, then use TokenNumber declared in DEC file
1128 if Pcd.Type in gDynamicExPcd:
1129 TokenNumber = int(Pcd.TokenValue, 0)
1130
30fdf114
LG
1131 if Pcd.Type not in gItemTypeStringDatabase:
1132 EdkLogger.error("build", AUTOGEN_ERROR,
1133 "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1134 ExtraData="[%s]" % str(Info))
1135 if Pcd.DatumType not in gDatumSizeStringDatabase:
1136 EdkLogger.error("build", AUTOGEN_ERROR,
1137 "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1138 ExtraData="[%s]" % str(Info))
1139
1140 DatumType = Pcd.DatumType
1141 DatumSize = gDatumSizeStringDatabaseH[DatumType]
1142 DatumSizeLib= gDatumSizeStringDatabaseLib[DatumType]
1143 GetModeName = '_PCD_GET_MODE_' + DatumSize + '_' + TokenCName
1144 SetModeName = '_PCD_SET_MODE_' + DatumSize + '_' + TokenCName
1145
1146 Type = ''
1147 Array = ''
1148 if Pcd.DatumType == 'VOID*':
1149 Type = '(VOID *)'
1150 Array = '[]'
1151
d40b2ee6 1152 AutoGenH.Append('#define _PCD_TOKEN_%s %dU\n' % (TokenCName, TokenNumber))
30fdf114
LG
1153
1154 PcdItemType = Pcd.Type
1155 #if PcdItemType in gDynamicPcd:
1156 # PcdItemType = TAB_PCDS_FIXED_AT_BUILD
1157 # if (TokenCName, TokenSpaceGuidCName) in Info.PlatformInfo.Platform.Pcds:
1158 # PcdItemType = Info.PlatformInfo.Platform.Pcds[TokenCName, TokenSpaceGuidCName].Type
1159 if PcdItemType in gDynamicExPcd:
1160 PcdTokenName = '_PCD_TOKEN_' + TokenCName
1161 AutoGenH.Append('#define %s LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
1162 if DatumType == 'VOID*':
1163 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName,DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
1164 else:
1165 AutoGenH.Append('#define %s(Value) LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
1166 if PcdItemType in gDynamicPcd:
1167 PcdTokenName = '_PCD_TOKEN_' + TokenCName
1168 AutoGenH.Append('#define %s LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
1169 if DatumType == 'VOID*':
1170 AutoGenH.Append('#define %s(SizeOfBuffer, Buffer) LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
1171 else:
1172 AutoGenH.Append('#define %s(Value) LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
1173 if PcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
1174 PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + TokenCName
1175 AutoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(DatumType, TokenCName, Array) )
1176 AutoGenH.Append('#define %s %s_gPcd_BinaryPatch_%s\n' %(GetModeName, Type, TokenCName))
1177 AutoGenH.Append('#define %s(Value) (%s = (Value))\n' % (SetModeName, PcdVariableName))
1178 if PcdItemType == TAB_PCDS_FIXED_AT_BUILD or PcdItemType == TAB_PCDS_FEATURE_FLAG:
1179 AutoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(DatumType, TokenCName, Array))
1180 #AutoGenH.Append('#define _PCD_VALUE_%s _gPcd_FixedAtBuild_%s\n' %(TokenCName, TokenCName))
1181 AutoGenH.Append('#define %s %s_gPcd_FixedAtBuild_%s\n' %(GetModeName, Type, TokenCName))
1182 AutoGenH.Append('//#define %s ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)
1183
1184## Create code for PCD database in DXE or PEI phase
1185#
1186# @param Platform The platform object
1187# @retval tuple Two TemplateString objects for C code and header file,
1188# respectively
1189#
1190def CreatePcdDatabasePhaseSpecificAutoGen (Platform, Phase):
1191 AutoGenC = TemplateString()
1192 AutoGenH = TemplateString()
1193
1194 Dict = {
1195 'PHASE' : Phase,
d0acc87a
LG
1196 'GUID_TABLE_SIZE' : '1U',
1197 'STRING_TABLE_SIZE' : '1U',
1198 'SKUID_TABLE_SIZE' : '1U',
1199 'LOCAL_TOKEN_NUMBER_TABLE_SIZE' : '1U',
1200 'LOCAL_TOKEN_NUMBER' : '0U',
1201 'EXMAPPING_TABLE_SIZE' : '1U',
1202 'EX_TOKEN_NUMBER' : '0U',
1203 'SIZE_TABLE_SIZE' : '2U',
30fdf114
LG
1204 'GUID_TABLE_EMPTY' : 'TRUE',
1205 'STRING_TABLE_EMPTY' : 'TRUE',
1206 'SKUID_TABLE_EMPTY' : 'TRUE',
1207 'DATABASE_EMPTY' : 'TRUE',
1208 'EXMAP_TABLE_EMPTY' : 'TRUE',
1209 'PCD_DATABASE_UNINIT_EMPTY' : ' UINT8 dummy; /* PCD_DATABASE_UNINIT is emptry */',
1210 'SYSTEM_SKU_ID' : ' SKU_ID SystemSkuId;',
d0acc87a 1211 'SYSTEM_SKU_ID_VALUE' : '0U'
30fdf114
LG
1212 }
1213
52302d4d 1214 for DatumType in ['UINT64','UINT32','UINT16','UINT8','BOOLEAN', "VOID*"]:
30fdf114
LG
1215 Dict['VARDEF_CNAME_' + DatumType] = []
1216 Dict['VARDEF_GUID_' + DatumType] = []
1217 Dict['VARDEF_SKUID_' + DatumType] = []
1218 Dict['VARDEF_VALUE_' + DatumType] = []
1219 for Init in ['INIT','UNINIT']:
1220 Dict[Init+'_CNAME_DECL_' + DatumType] = []
1221 Dict[Init+'_GUID_DECL_' + DatumType] = []
1222 Dict[Init+'_NUMSKUS_DECL_' + DatumType] = []
1223 Dict[Init+'_VALUE_' + DatumType] = []
1224
1225 for Type in ['STRING_HEAD','VPD_HEAD','VARIABLE_HEAD']:
1226 Dict[Type + '_CNAME_DECL'] = []
1227 Dict[Type + '_GUID_DECL'] = []
1228 Dict[Type + '_NUMSKUS_DECL'] = []
1229 Dict[Type + '_VALUE'] = []
1230
1231 Dict['STRING_TABLE_INDEX'] = []
1232 Dict['STRING_TABLE_LENGTH'] = []
1233 Dict['STRING_TABLE_CNAME'] = []
1234 Dict['STRING_TABLE_GUID'] = []
1235 Dict['STRING_TABLE_VALUE'] = []
1236
1237 Dict['SIZE_TABLE_CNAME'] = []
1238 Dict['SIZE_TABLE_GUID'] = []
1239 Dict['SIZE_TABLE_CURRENT_LENGTH'] = []
1240 Dict['SIZE_TABLE_MAXIMUM_LENGTH'] = []
1241
1242 Dict['EXMAPPING_TABLE_EXTOKEN'] = []
1243 Dict['EXMAPPING_TABLE_LOCAL_TOKEN'] = []
1244 Dict['EXMAPPING_TABLE_GUID_INDEX'] = []
1245
1246 Dict['GUID_STRUCTURE'] = []
1247
1248 Dict['SKUID_VALUE'] = []
52302d4d 1249 Dict['VARDEF_HEADER'] = []
30fdf114
LG
1250 if Phase == 'DXE':
1251 Dict['SYSTEM_SKU_ID'] = ''
1252 Dict['SYSTEM_SKU_ID_VALUE'] = ''
1253
1254 StringTableIndex = 0
1255 StringTableSize = 0
1256 NumberOfLocalTokens = 0
1257 NumberOfPeiLocalTokens = 0
1258 NumberOfDxeLocalTokens = 0
1259 NumberOfExTokens = 0
1260 NumberOfSizeItems = 0
1261 GuidList = []
9053bc51 1262
30fdf114
LG
1263 for Pcd in Platform.DynamicPcdList:
1264 CName = Pcd.TokenCName
1265 TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1266
1267 EdkLogger.debug(EdkLogger.DEBUG_3, "PCD: %s %s (%s : %s)" % (CName, TokenSpaceGuidCName, Pcd.Phase, Phase))
1268 if Pcd.DatumType not in gDatumSizeStringDatabase:
1269 EdkLogger.error("build", AUTOGEN_ERROR,
1270 "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1271 ExtraData="[%s]" % str(Platform))
1272
1273 if Pcd.Phase == 'PEI':
1274 NumberOfPeiLocalTokens += 1
1275 if Pcd.Phase == 'DXE':
1276 NumberOfDxeLocalTokens += 1
1277 if Pcd.Phase != Phase:
1278 continue
1279
1280 #
1281 # TODO: need GetGuidValue() definition
1282 #
1283 TokenSpaceGuidStructure = Pcd.TokenSpaceGuidValue
1284 TokenSpaceGuid = GuidStructureStringToGuidValueName(TokenSpaceGuidStructure)
1285 if Pcd.Type in gDynamicExPcd:
1286 if TokenSpaceGuid not in GuidList:
1287 GuidList += [TokenSpaceGuid]
1288 Dict['GUID_STRUCTURE'].append(TokenSpaceGuidStructure)
1289 NumberOfExTokens += 1
1290
1291 ValueList = []
1292 StringHeadOffsetList = []
1293 VpdHeadOffsetList = []
1294 VariableHeadValueList = []
1295 Pcd.InitString = 'UNINIT'
1296
e56468c0 1297 if Pcd.DatumType == 'VOID*':
1298 if Pcd.Type not in ["DynamicVpd", "DynamicExVpd"]:
1299 Pcd.TokenTypeList = ['PCD_TYPE_STRING']
1300 else:
1301 Pcd.TokenTypeList = []
30fdf114
LG
1302 elif Pcd.DatumType == 'BOOLEAN':
1303 Pcd.TokenTypeList = ['PCD_DATUM_TYPE_UINT8']
1304 else:
1305 Pcd.TokenTypeList = ['PCD_DATUM_TYPE_' + Pcd.DatumType]
1306
1307 if len(Pcd.SkuInfoList) > 1:
1308 Pcd.TokenTypeList += ['PCD_TYPE_SKU_ENABLED']
1309
1310 for SkuName in Pcd.SkuInfoList:
1311 Sku = Pcd.SkuInfoList[SkuName]
1312 SkuId = Sku.SkuId
1313 if SkuId == None or SkuId == '':
1314 continue
1315
d0acc87a
LG
1316 if (SkuId + 'U') not in Dict['SKUID_VALUE']:
1317 Dict['SKUID_VALUE'].append(SkuId + 'U')
30fdf114 1318
d0acc87a 1319 SkuIdIndex = Dict['SKUID_VALUE'].index(SkuId + 'U')
30fdf114
LG
1320 if len(Sku.VariableName) > 0:
1321 Pcd.TokenTypeList += ['PCD_TYPE_HII']
1322 Pcd.InitString = 'INIT'
1323 VariableNameStructure = StringToArray(Sku.VariableName)
1324 if VariableNameStructure not in Dict['STRING_TABLE_VALUE']:
1325 Dict['STRING_TABLE_CNAME'].append(CName)
1326 Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
1327 if StringTableIndex == 0:
1328 Dict['STRING_TABLE_INDEX'].append('')
1329 else:
1330 Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
1331
1332 Dict['STRING_TABLE_LENGTH'].append((len(Sku.VariableName) - 3 + 1) * 2)
1333 Dict['STRING_TABLE_VALUE'].append(VariableNameStructure)
1334 StringTableIndex += 1
1335 StringTableSize += (len(Sku.VariableName) - 3 + 1) * 2
1336
1337 VariableHeadStringIndex = 0
1338 for Index in range(Dict['STRING_TABLE_VALUE'].index(VariableNameStructure)):
1339 VariableHeadStringIndex += Dict['STRING_TABLE_LENGTH'][Index]
1340
1341 VariableGuidStructure = Sku.VariableGuidValue
1342 VariableGuid = GuidStructureStringToGuidValueName(VariableGuidStructure)
1343 if VariableGuid not in GuidList:
1344 GuidList += [VariableGuid]
1345 Dict['GUID_STRUCTURE'].append(VariableGuidStructure)
1346 VariableHeadGuidIndex = GuidList.index(VariableGuid)
1347
52302d4d 1348 if "PCD_TYPE_STRING" in Pcd.TokenTypeList:
d0acc87a 1349 VariableHeadValueList.append('%dU, %dU, %sU, offsetof(%s_PCD_DATABASE, Init.%s_%s)' %
52302d4d
LG
1350 (VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset,
1351 Phase, CName, TokenSpaceGuid))
1352 else:
d0acc87a 1353 VariableHeadValueList.append('%dU, %dU, %sU, offsetof(%s_PCD_DATABASE, Init.%s_%s_VariableDefault_%s)' %
52302d4d
LG
1354 (VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset,
1355 Phase, CName, TokenSpaceGuid, SkuIdIndex))
30fdf114
LG
1356 Dict['VARDEF_CNAME_'+Pcd.DatumType].append(CName)
1357 Dict['VARDEF_GUID_'+Pcd.DatumType].append(TokenSpaceGuid)
1358 Dict['VARDEF_SKUID_'+Pcd.DatumType].append(SkuIdIndex)
52302d4d
LG
1359 if "PCD_TYPE_STRING" in Pcd.TokenTypeList:
1360 Dict['VARDEF_VALUE_' + Pcd.DatumType].append("%s_%s[%d]" % (Pcd.TokenCName, TokenSpaceGuid, SkuIdIndex))
1361 else:
d0acc87a
LG
1362 #
1363 # ULL (for UINT64) or U(other integer type) should be append to avoid
1364 # warning under linux building environment.
1365 #
1366 if Pcd.DatumType == "UINT64":
1367 Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue + "ULL")
1368 elif Pcd.DatumType in ("UINT32", "UINT16", "UINT8"):
1369 Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue + "U")
1370 elif Pcd.DatumType == "BOOLEAN":
1371 if Sku.HiiDefaultValue in ["1", "0"]:
1372 Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue + "U")
1373 else:
1374 Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue)
1375
30fdf114
LG
1376 elif Sku.VpdOffset != '':
1377 Pcd.TokenTypeList += ['PCD_TYPE_VPD']
1378 Pcd.InitString = 'INIT'
d0acc87a 1379 VpdHeadOffsetList.append(str(Sku.VpdOffset) + 'U')
9053bc51 1380 continue
52302d4d
LG
1381
1382 if Pcd.DatumType == 'VOID*':
1383 Pcd.TokenTypeList += ['PCD_TYPE_STRING']
1384 Pcd.InitString = 'INIT'
1385 if Sku.HiiDefaultValue != '' and Sku.DefaultValue == '':
1386 Sku.DefaultValue = Sku.HiiDefaultValue
1387 if Sku.DefaultValue != '':
1388 NumberOfSizeItems += 1
1389 Dict['STRING_TABLE_CNAME'].append(CName)
1390 Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
1391
1392 if StringTableIndex == 0:
1393 Dict['STRING_TABLE_INDEX'].append('')
1394 else:
1395 Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
1396 if Sku.DefaultValue[0] == 'L':
1397 Size = (len(Sku.DefaultValue) - 3 + 1) * 2
1398 Dict['STRING_TABLE_VALUE'].append(StringToArray(Sku.DefaultValue))
1399 elif Sku.DefaultValue[0] == '"':
1400 Size = len(Sku.DefaultValue) - 2 + 1
1401 Dict['STRING_TABLE_VALUE'].append(StringToArray(Sku.DefaultValue))
1402 elif Sku.DefaultValue[0] == '{':
1403 Size = len(Sku.DefaultValue.replace(',',' ').split())
1404 Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)
1405
d0acc87a 1406 StringHeadOffsetList.append(str(StringTableSize) + 'U')
52302d4d
LG
1407 Dict['SIZE_TABLE_CNAME'].append(CName)
1408 Dict['SIZE_TABLE_GUID'].append(TokenSpaceGuid)
d0acc87a
LG
1409 Dict['SIZE_TABLE_CURRENT_LENGTH'].append(str(Size) + 'U')
1410 Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(str(Pcd.MaxDatumSize) + 'U')
52302d4d
LG
1411 if Pcd.MaxDatumSize != '':
1412 MaxDatumSize = int(Pcd.MaxDatumSize, 0)
e56468c0 1413 if MaxDatumSize < Size:
1414 EdkLogger.error("build", AUTOGEN_ERROR,
1415 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
1416 ExtraData="[%s]" % str(Platform))
1417 Size = MaxDatumSize
52302d4d
LG
1418 Dict['STRING_TABLE_LENGTH'].append(Size)
1419 StringTableIndex += 1
1420 StringTableSize += (Size)
30fdf114 1421 else:
52302d4d 1422 if "PCD_TYPE_HII" not in Pcd.TokenTypeList:
30fdf114
LG
1423 Pcd.TokenTypeList += ['PCD_TYPE_DATA']
1424 if Sku.DefaultValue == 'TRUE':
1425 Pcd.InitString = 'INIT'
1426 else:
1427 try:
1428 if int(Sku.DefaultValue, 0) != 0:
1429 Pcd.InitString = 'INIT'
1430 except:
1431 pass
52302d4d
LG
1432
1433 #
1434 # For UNIT64 type PCD's value, ULL should be append to avoid
1435 # warning under linux building environment.
1436 #
1437 if Pcd.DatumType == "UINT64":
1438 ValueList.append(Sku.DefaultValue + "ULL")
d40b2ee6
LG
1439 elif Pcd.DatumType in ("UINT32", "UINT16", "UINT8"):
1440 ValueList.append(Sku.DefaultValue + "U")
d0acc87a
LG
1441 elif Pcd.DatumType == "BOOLEAN":
1442 if Sku.DefaultValue in ["1", "0"]:
1443 ValueList.append(Sku.DefaultValue + "U")
52302d4d
LG
1444 else:
1445 ValueList.append(Sku.DefaultValue)
30fdf114
LG
1446
1447 Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
52302d4d 1448
30fdf114
LG
1449
1450 if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
1451 Dict['VARIABLE_HEAD_CNAME_DECL'].append(CName)
1452 Dict['VARIABLE_HEAD_GUID_DECL'].append(TokenSpaceGuid)
1453 Dict['VARIABLE_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
1454 Dict['VARIABLE_HEAD_VALUE'].append('{ %s }\n' % ' },\n { '.join(VariableHeadValueList))
52302d4d
LG
1455 Dict['VARDEF_HEADER'].append('_Variable_Header')
1456 else:
1457 Dict['VARDEF_HEADER'].append('')
30fdf114
LG
1458 if 'PCD_TYPE_VPD' in Pcd.TokenTypeList:
1459 Dict['VPD_HEAD_CNAME_DECL'].append(CName)
1460 Dict['VPD_HEAD_GUID_DECL'].append(TokenSpaceGuid)
1461 Dict['VPD_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
1462 Dict['VPD_HEAD_VALUE'].append('{ %s }' % ' }, { '.join(VpdHeadOffsetList))
1463 if 'PCD_TYPE_STRING' in Pcd.TokenTypeList:
1464 Dict['STRING_HEAD_CNAME_DECL'].append(CName)
1465 Dict['STRING_HEAD_GUID_DECL'].append(TokenSpaceGuid)
1466 Dict['STRING_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
1467 Dict['STRING_HEAD_VALUE'].append(', '.join(StringHeadOffsetList))
1468 if 'PCD_TYPE_DATA' in Pcd.TokenTypeList:
1469 Dict[Pcd.InitString+'_CNAME_DECL_'+Pcd.DatumType].append(CName)
1470 Dict[Pcd.InitString+'_GUID_DECL_'+Pcd.DatumType].append(TokenSpaceGuid)
1471 Dict[Pcd.InitString+'_NUMSKUS_DECL_'+Pcd.DatumType].append(len(Pcd.SkuInfoList))
1472 if Pcd.InitString == 'UNINIT':
1473 Dict['PCD_DATABASE_UNINIT_EMPTY'] = ''
1474 else:
1475 Dict[Pcd.InitString+'_VALUE_'+Pcd.DatumType].append(', '.join(ValueList))
1476
1477 if Phase == 'PEI':
1478 NumberOfLocalTokens = NumberOfPeiLocalTokens
1479 if Phase == 'DXE':
1480 NumberOfLocalTokens = NumberOfDxeLocalTokens
1481
1482 Dict['TOKEN_INIT'] = ['' for x in range(NumberOfLocalTokens)]
1483 Dict['TOKEN_CNAME'] = ['' for x in range(NumberOfLocalTokens)]
1484 Dict['TOKEN_GUID'] = ['' for x in range(NumberOfLocalTokens)]
1485 Dict['TOKEN_TYPE'] = ['' for x in range(NumberOfLocalTokens)]
52302d4d 1486
30fdf114
LG
1487 for Pcd in Platform.DynamicPcdList:
1488 CName = Pcd.TokenCName
1489 TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1490 if Pcd.Phase != Phase:
1491 continue
1492
1493 TokenSpaceGuid = GuidStructureStringToGuidValueName(Pcd.TokenSpaceGuidValue) #(Platform.PackageList, TokenSpaceGuidCName))
1494 GeneratedTokenNumber = Platform.PcdTokenNumber[CName, TokenSpaceGuidCName] - 1
1495 if Phase == 'DXE':
1496 GeneratedTokenNumber -= NumberOfPeiLocalTokens
1497
1498 EdkLogger.debug(EdkLogger.DEBUG_1, "PCD = %s.%s" % (CName, TokenSpaceGuidCName))
1499 EdkLogger.debug(EdkLogger.DEBUG_1, "phase = %s" % Phase)
1500 EdkLogger.debug(EdkLogger.DEBUG_1, "GeneratedTokenNumber = %s" % str(GeneratedTokenNumber))
1501
1502 Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Init'
1503 if Pcd.InitString == 'UNINIT':
1504 Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Uninit'
1505 Dict['TOKEN_CNAME'][GeneratedTokenNumber] = CName
1506 Dict['TOKEN_GUID'][GeneratedTokenNumber] = TokenSpaceGuid
1507 Dict['TOKEN_TYPE'][GeneratedTokenNumber] = ' | '.join(Pcd.TokenTypeList)
d0acc87a
LG
1508
1509 Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
1510 #
1511 # Update VARDEF_HEADER
1512 #
1513 if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
1514 Dict['VARDEF_HEADER'][GeneratedTokenNumber] = '_Variable_Header'
1515 else:
1516 Dict['VARDEF_HEADER'][GeneratedTokenNumber] = ''
1517
1518
30fdf114 1519 if Pcd.Type in gDynamicExPcd:
d0acc87a 1520 Dict['EXMAPPING_TABLE_EXTOKEN'].append(str(Pcd.TokenValue) + 'U')
30fdf114
LG
1521 if Phase == 'DXE':
1522 GeneratedTokenNumber += NumberOfPeiLocalTokens
1523 #
1524 # Per, PCD architecture specification, PCD Token Number is 1 based and 0 is defined as invalid token number.
1525 # For each EX type PCD, a PCD Token Number is assigned. When the
1526 # PCD Driver/PEIM map EX_GUID and EX_TOKEN_NUMBER to the PCD Token Number,
1527 # the non-EX Protocol/PPI interface can be called to get/set the value. This assumption is made by
1528 # Pcd Driver/PEIM in MdeModulePkg.
1529 # Therefore, 1 is added to GeneratedTokenNumber to generate a PCD Token Number before being inserted
1530 # to the EXMAPPING_TABLE.
1531 #
d0acc87a
LG
1532 Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(str(GeneratedTokenNumber + 1) + 'U')
1533 Dict['EXMAPPING_TABLE_GUID_INDEX'].append(str(GuidList.index(TokenSpaceGuid)) + 'U')
30fdf114
LG
1534
1535 if GuidList != []:
1536 Dict['GUID_TABLE_EMPTY'] = 'FALSE'
d0acc87a 1537 Dict['GUID_TABLE_SIZE'] = str(len(GuidList)) + 'U'
30fdf114
LG
1538 else:
1539 Dict['GUID_STRUCTURE'] = [GuidStringToGuidStructureString('00000000-0000-0000-0000-000000000000')]
1540
1541 if StringTableIndex == 0:
1542 Dict['STRING_TABLE_INDEX'].append('')
1543 Dict['STRING_TABLE_LENGTH'].append(1)
1544 Dict['STRING_TABLE_CNAME'].append('')
1545 Dict['STRING_TABLE_GUID'].append('')
1546 Dict['STRING_TABLE_VALUE'].append('{ 0 }')
1547 else:
1548 Dict['STRING_TABLE_EMPTY'] = 'FALSE'
d0acc87a 1549 Dict['STRING_TABLE_SIZE'] = str(StringTableSize) + 'U'
30fdf114
LG
1550
1551 if Dict['SIZE_TABLE_CNAME'] == []:
1552 Dict['SIZE_TABLE_CNAME'].append('')
1553 Dict['SIZE_TABLE_GUID'].append('')
d0acc87a
LG
1554 Dict['SIZE_TABLE_CURRENT_LENGTH'].append('0U')
1555 Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append('0U')
30fdf114
LG
1556
1557 if NumberOfLocalTokens != 0:
1558 Dict['DATABASE_EMPTY'] = 'FALSE'
1559 Dict['LOCAL_TOKEN_NUMBER_TABLE_SIZE'] = NumberOfLocalTokens
1560 Dict['LOCAL_TOKEN_NUMBER'] = NumberOfLocalTokens
1561
1562 if NumberOfExTokens != 0:
1563 Dict['EXMAP_TABLE_EMPTY'] = 'FALSE'
d0acc87a
LG
1564 Dict['EXMAPPING_TABLE_SIZE'] = str(NumberOfExTokens) + 'U'
1565 Dict['EX_TOKEN_NUMBER'] = str(NumberOfExTokens) + 'U'
30fdf114 1566 else:
d0acc87a
LG
1567 Dict['EXMAPPING_TABLE_EXTOKEN'].append('0U')
1568 Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append('0U')
1569 Dict['EXMAPPING_TABLE_GUID_INDEX'].append('0U')
30fdf114
LG
1570
1571 if NumberOfSizeItems != 0:
d0acc87a 1572 Dict['SIZE_TABLE_SIZE'] = str(NumberOfSizeItems * 2) + 'U'
30fdf114
LG
1573
1574 AutoGenH.Append(gPcdDatabaseAutoGenH.Replace(Dict))
1575 if NumberOfLocalTokens == 0:
1576 AutoGenC.Append(gEmptyPcdDatabaseAutoGenC.Replace(Dict))
1577 else:
1578 AutoGenC.Append(gPcdDatabaseAutoGenC.Replace(Dict))
1579
1580 return AutoGenH, AutoGenC
1581
1582## Create code for PCD database
1583#
1584# @param Info The ModuleAutoGen object
1585# @param AutoGenC The TemplateString object for C code
1586# @param AutoGenH The TemplateString object for header file
1587#
1588def CreatePcdDatabaseCode (Info, AutoGenC, AutoGenH):
1589 if Info.PcdIsDriver == "":
1590 return
1591 if Info.PcdIsDriver not in gPcdPhaseMap:
1592 EdkLogger.error("build", AUTOGEN_ERROR, "Not supported PcdIsDriver type:%s" % Info.PcdIsDriver,
1593 ExtraData="[%s]" % str(Info))
1594
1595 AutoGenH.Append(gPcdDatabaseCommonAutoGenH)
1596 AdditionalAutoGenH, AdditionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (Info.PlatformInfo, 'PEI')
1597 AutoGenH.Append(AdditionalAutoGenH.String)
1598
1599 Phase = gPcdPhaseMap[Info.PcdIsDriver]
1600 if Phase == 'PEI':
1601 AutoGenC.Append(AdditionalAutoGenC.String)
1602
1603 if Phase == 'DXE':
1604 AdditionalAutoGenH, AdditionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (Info.PlatformInfo, Phase)
1605 AutoGenH.Append(AdditionalAutoGenH.String)
1606 AutoGenC.Append(AdditionalAutoGenC.String)
1607 AutoGenH.Append(gPcdDatabaseEpilogueAutoGenH)
1608
1609## Create code for library constructor
1610#
1611# @param Info The ModuleAutoGen object
1612# @param AutoGenC The TemplateString object for C code
1613# @param AutoGenH The TemplateString object for header file
1614#
1615def CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH):
1616 #
1617 # Library Constructors
1618 #
1619 ConstructorPrototypeString = TemplateString()
1620 ConstructorCallingString = TemplateString()
1621 if Info.IsLibrary:
1622 DependentLibraryList = [Info.Module]
1623 else:
1624 DependentLibraryList = Info.DependentLibraryList
1625 for Lib in DependentLibraryList:
1626 if len(Lib.ConstructorList) <= 0:
1627 continue
1628 Dict = {'Function':Lib.ConstructorList}
1629 if Lib.ModuleType in ['BASE', 'SEC']:
1630 ConstructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1631 ConstructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1632 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1633 ConstructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1634 ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1635 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
b303ea72 1636 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
30fdf114
LG
1637 ConstructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1638 ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1639
1640 if str(ConstructorPrototypeString) == '':
1641 ConstructorPrototypeList = []
1642 else:
1643 ConstructorPrototypeList = [str(ConstructorPrototypeString)]
1644 if str(ConstructorCallingString) == '':
1645 ConstructorCallingList = []
1646 else:
1647 ConstructorCallingList = [str(ConstructorCallingString)]
1648
1649 Dict = {
1650 'Type' : 'Constructor',
1651 'FunctionPrototype' : ConstructorPrototypeList,
1652 'FunctionCall' : ConstructorCallingList
1653 }
1654 if Info.IsLibrary:
1655 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1656 else:
1657 if Info.ModuleType in ['BASE', 'SEC']:
1658 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1659 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1660 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1661 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
b303ea72 1662 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
30fdf114
LG
1663 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1664
1665## Create code for library destructor
1666#
1667# @param Info The ModuleAutoGen object
1668# @param AutoGenC The TemplateString object for C code
1669# @param AutoGenH The TemplateString object for header file
1670#
1671def CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH):
1672 #
1673 # Library Destructors
1674 #
1675 DestructorPrototypeString = TemplateString()
1676 DestructorCallingString = TemplateString()
1677 if Info.IsLibrary:
1678 DependentLibraryList = [Info.Module]
1679 else:
1680 DependentLibraryList = Info.DependentLibraryList
1681 for Index in range(len(DependentLibraryList)-1, -1, -1):
1682 Lib = DependentLibraryList[Index]
1683 if len(Lib.DestructorList) <= 0:
1684 continue
1685 Dict = {'Function':Lib.DestructorList}
1686 if Lib.ModuleType in ['BASE', 'SEC']:
1687 DestructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
1688 DestructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
1689 elif Lib.ModuleType in ['PEI_CORE','PEIM']:
1690 DestructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
1691 DestructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
1692 elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
b303ea72 1693 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION', 'SMM_CORE']:
30fdf114
LG
1694 DestructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
1695 DestructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))
1696
1697 if str(DestructorPrototypeString) == '':
1698 DestructorPrototypeList = []
1699 else:
1700 DestructorPrototypeList = [str(DestructorPrototypeString)]
1701 if str(DestructorCallingString) == '':
1702 DestructorCallingList = []
1703 else:
1704 DestructorCallingList = [str(DestructorCallingString)]
1705
1706 Dict = {
1707 'Type' : 'Destructor',
1708 'FunctionPrototype' : DestructorPrototypeList,
1709 'FunctionCall' : DestructorCallingList
1710 }
1711 if Info.IsLibrary:
1712 AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
1713 else:
1714 if Info.ModuleType in ['BASE', 'SEC']:
1715 AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
1716 elif Info.ModuleType in ['PEI_CORE','PEIM']:
1717 AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
1718 elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
b303ea72 1719 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
30fdf114
LG
1720 AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))
1721
1722
1723## Create code for ModuleEntryPoint
1724#
1725# @param Info The ModuleAutoGen object
1726# @param AutoGenC The TemplateString object for C code
1727# @param AutoGenH The TemplateString object for header file
1728#
1729def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH):
1730 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1731 return
1732 #
1733 # Module Entry Points
1734 #
1735 NumEntryPoints = len(Info.Module.ModuleEntryPointList)
1736 if 'PI_SPECIFICATION_VERSION' in Info.Module.Specification:
1737 PiSpecVersion = Info.Module.Specification['PI_SPECIFICATION_VERSION']
1738 else:
da92f276 1739 PiSpecVersion = '0x00000000'
52302d4d
LG
1740 if 'UEFI_SPECIFICATION_VERSION' in Info.Module.Specification:
1741 UefiSpecVersion = Info.Module.Specification['UEFI_SPECIFICATION_VERSION']
30fdf114 1742 else:
da92f276 1743 UefiSpecVersion = '0x00000000'
30fdf114 1744 Dict = {
52302d4d 1745 'Function' : Info.Module.ModuleEntryPointList,
d0acc87a
LG
1746 'PiSpecVersion' : PiSpecVersion + 'U',
1747 'UefiSpecVersion': UefiSpecVersion + 'U'
30fdf114
LG
1748 }
1749
1750 if Info.ModuleType in ['PEI_CORE', 'DXE_CORE', 'SMM_CORE']:
da92f276
LG
1751 if Info.SourceFileList <> None and Info.SourceFileList <> []:
1752 if NumEntryPoints != 1:
1753 EdkLogger.error(
1754 "build",
1755 AUTOGEN_ERROR,
1756 '%s must have exactly one entry point' % Info.ModuleType,
1757 File=str(Info),
1758 ExtraData= ", ".join(Info.Module.ModuleEntryPointList)
1759 )
30fdf114
LG
1760 if Info.ModuleType == 'PEI_CORE':
1761 AutoGenC.Append(gPeiCoreEntryPointString.Replace(Dict))
1762 AutoGenH.Append(gPeiCoreEntryPointPrototype.Replace(Dict))
1763 elif Info.ModuleType == 'DXE_CORE':
1764 AutoGenC.Append(gDxeCoreEntryPointString.Replace(Dict))
1765 AutoGenH.Append(gDxeCoreEntryPointPrototype.Replace(Dict))
1766 elif Info.ModuleType == 'SMM_CORE':
1767 AutoGenC.Append(gSmmCoreEntryPointString.Replace(Dict))
b303ea72 1768 AutoGenH.Append(gSmmCoreEntryPointPrototype.Replace(Dict))
30fdf114
LG
1769 elif Info.ModuleType == 'PEIM':
1770 if NumEntryPoints < 2:
1771 AutoGenC.Append(gPeimEntryPointString[NumEntryPoints].Replace(Dict))
1772 else:
1773 AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict))
1774 AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict))
b303ea72
LG
1775 elif Info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:
1776 if NumEntryPoints < 2:
1777 AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Replace(Dict))
30fdf114 1778 else:
b303ea72
LG
1779 AutoGenC.Append(gUefiDriverEntryPointString[2].Replace(Dict))
1780 AutoGenH.Append(gUefiDriverEntryPointPrototype.Replace(Dict))
1781 elif Info.ModuleType == 'DXE_SMM_DRIVER':
1782 if NumEntryPoints == 0:
1783 AutoGenC.Append(gDxeSmmEntryPointString[0].Replace(Dict))
1784 else:
1785 AutoGenC.Append(gDxeSmmEntryPointString[1].Replace(Dict))
1786 AutoGenH.Append(gDxeSmmEntryPointPrototype.Replace(Dict))
30fdf114
LG
1787 elif Info.ModuleType == 'UEFI_APPLICATION':
1788 if NumEntryPoints < 2:
1789 AutoGenC.Append(gUefiApplicationEntryPointString[NumEntryPoints].Replace(Dict))
1790 else:
1791 AutoGenC.Append(gUefiApplicationEntryPointString[2].Replace(Dict))
1792 AutoGenH.Append(gUefiApplicationEntryPointPrototype.Replace(Dict))
1793
1794## Create code for ModuleUnloadImage
1795#
1796# @param Info The ModuleAutoGen object
1797# @param AutoGenC The TemplateString object for C code
1798# @param AutoGenH The TemplateString object for header file
1799#
1800def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH):
1801 if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
1802 return
1803 #
1804 # Unload Image Handlers
1805 #
1806 NumUnloadImage = len(Info.Module.ModuleUnloadImageList)
d0acc87a 1807 Dict = {'Count':str(NumUnloadImage) + 'U', 'Function':Info.Module.ModuleUnloadImageList}
30fdf114
LG
1808 if NumUnloadImage < 2:
1809 AutoGenC.Append(gUefiUnloadImageString[NumUnloadImage].Replace(Dict))
1810 else:
1811 AutoGenC.Append(gUefiUnloadImageString[2].Replace(Dict))
1812 AutoGenH.Append(gUefiUnloadImagePrototype.Replace(Dict))
1813
1814## Create code for GUID
1815#
1816# @param Info The ModuleAutoGen object
1817# @param AutoGenC The TemplateString object for C code
1818# @param AutoGenH The TemplateString object for header file
1819#
1820def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH):
1821 if Info.IsLibrary:
1822 return
1823
1824 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1825 GuidType = "GUID"
1826 else:
1827 GuidType = "EFI_GUID"
1828
1829 if Info.GuidList:
1830 AutoGenC.Append("\n// Guids\n")
1831 #
1832 # GUIDs
1833 #
1834 for Key in Info.GuidList:
1835 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.GuidList[Key]))
1836
1837## Create code for protocol
1838#
1839# @param Info The ModuleAutoGen object
1840# @param AutoGenC The TemplateString object for C code
1841# @param AutoGenH The TemplateString object for header file
1842#
1843def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH):
1844 if Info.IsLibrary:
1845 return
1846
1847 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1848 GuidType = "GUID"
1849 else:
1850 GuidType = "EFI_GUID"
1851
1852 if Info.ProtocolList:
1853 AutoGenC.Append("\n// Protocols\n")
1854 #
1855 # Protocol GUIDs
1856 #
1857 for Key in Info.ProtocolList:
1858 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.ProtocolList[Key]))
1859
1860## Create code for PPI
1861#
1862# @param Info The ModuleAutoGen object
1863# @param AutoGenC The TemplateString object for C code
1864# @param AutoGenH The TemplateString object for header file
1865#
1866def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH):
1867 if Info.IsLibrary:
1868 return
1869
1870 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1871 GuidType = "GUID"
1872 else:
1873 GuidType = "EFI_GUID"
1874
1875 if Info.PpiList:
1876 AutoGenC.Append("\n// PPIs\n")
1877 #
1878 # PPI GUIDs
1879 #
1880 for Key in Info.PpiList:
1881 AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.PpiList[Key]))
1882
1883## Create code for PCD
1884#
1885# @param Info The ModuleAutoGen object
1886# @param AutoGenC The TemplateString object for C code
1887# @param AutoGenH The TemplateString object for header file
1888#
1889def CreatePcdCode(Info, AutoGenC, AutoGenH):
da92f276
LG
1890
1891 # Collect Token Space GUIDs used by DynamicEc PCDs
1892 TokenSpaceList = []
1893 for Pcd in Info.ModulePcdList:
1894 if Pcd.Type in gDynamicExPcd and Pcd.TokenSpaceGuidCName not in TokenSpaceList:
1895 TokenSpaceList += [Pcd.TokenSpaceGuidCName]
1896
1897 # Add extern declarations to AutoGen.h if one or more Token Space GUIDs were found
1898 if TokenSpaceList <> []:
1899 AutoGenH.Append("\n// Definition of PCD Token Space GUIDs used in this module\n\n")
1900 if Info.ModuleType in ["USER_DEFINED", "BASE"]:
1901 GuidType = "GUID"
1902 else:
1903 GuidType = "EFI_GUID"
1904 for Item in TokenSpaceList:
1905 AutoGenH.Append('extern %s %s;\n' % (GuidType, Item))
1906
30fdf114
LG
1907 if Info.IsLibrary:
1908 if Info.ModulePcdList:
1909 AutoGenH.Append("\n// PCD definitions\n")
1910 for Pcd in Info.ModulePcdList:
1911 CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd)
1912 else:
1913 if Info.ModulePcdList:
1914 AutoGenH.Append("\n// Definition of PCDs used in this module\n")
1915 AutoGenC.Append("\n// Definition of PCDs used in this module\n")
1916 for Pcd in Info.ModulePcdList:
1917 CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd)
1918
1919 if Info.LibraryPcdList:
1920 AutoGenH.Append("\n// Definition of PCDs used in libraries is in AutoGen.c\n")
1921 AutoGenC.Append("\n// Definition of PCDs used in libraries\n")
1922 for Pcd in Info.LibraryPcdList:
1923 CreateModulePcdCode(Info, AutoGenC, AutoGenC, Pcd)
1924 CreatePcdDatabaseCode(Info, AutoGenC, AutoGenH)
1925
1926## Create code for unicode string definition
1927#
1928# @param Info The ModuleAutoGen object
1929# @param AutoGenC The TemplateString object for C code
1930# @param AutoGenH The TemplateString object for header file
b303ea72
LG
1931# @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
1932# @param UniGenBinBuffer Buffer to store uni string package data
30fdf114 1933#
b303ea72 1934def CreateUnicodeStringCode(Info, AutoGenC, AutoGenH, UniGenCFlag, UniGenBinBuffer):
30fdf114
LG
1935 WorkingDir = os.getcwd()
1936 os.chdir(Info.WorkspaceDir)
1937
1938 IncList = [Info.MetaFile.Dir]
1939 # Get all files under [Sources] section in inf file for EDK-II module
6780eef1 1940 EDK2Module = True
30fdf114
LG
1941 SrcList = [F for F in Info.SourceFileList]
1942 if Info.AutoGenVersion < 0x00010005:
6780eef1 1943 EDK2Module = False
30fdf114
LG
1944 # Get all files under the module directory for EDK-I module
1945 Cwd = os.getcwd()
1946 os.chdir(Info.MetaFile.Dir)
1947 for Root, Dirs, Files in os.walk("."):
1948 if 'CVS' in Dirs:
1949 Dirs.remove('CVS')
1950 if '.svn' in Dirs:
1951 Dirs.remove('.svn')
1952 for File in Files:
1953 File = PathClass(os.path.join(Root, File), Info.MetaFile.Dir)
1954 if File in SrcList:
1955 continue
1956 SrcList.append(File)
1957 os.chdir(Cwd)
1958
1959 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-c') > -1:
1960 CompatibleMode = True
1961 else:
1962 CompatibleMode = False
1963
1964 #
6780eef1 1965 # -s is a temporary option dedicated for building .UNI files with ISO 639-2 language codes of EDK Shell in EDK2
30fdf114
LG
1966 #
1967 if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-s') > -1:
1968 if CompatibleMode:
1969 EdkLogger.error("build", AUTOGEN_ERROR,
1970 "-c and -s build options should be used exclusively",
1971 ExtraData="[%s]" % str(Info))
1972 ShellMode = True
1973 else:
1974 ShellMode = False
1975
6780eef1
LG
1976 #RFC4646 is only for EDKII modules and ISO639-2 for EDK modules
1977 if EDK2Module:
1978 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.RFCLanguages]
1979 else:
1980 FilterInfo = [EDK2Module] + [Info.PlatformInfo.Platform.ISOLanguages]
1981 Header, Code = GetStringFiles(Info.UnicodeFileList, SrcList, IncList, Info.IncludePathList, ['.uni', '.inf'], Info.Name, CompatibleMode, ShellMode, UniGenCFlag, UniGenBinBuffer, FilterInfo)
b303ea72
LG
1982 if CompatibleMode or UniGenCFlag:
1983 AutoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
1984 AutoGenC.Append(Code)
1985 AutoGenC.Append("\n")
30fdf114
LG
1986 AutoGenH.Append("\n//\n//Unicode String ID\n//\n")
1987 AutoGenH.Append(Header)
b303ea72
LG
1988 if CompatibleMode or UniGenCFlag:
1989 AutoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % Info.Name)
30fdf114
LG
1990 os.chdir(WorkingDir)
1991
1992## Create common code
1993#
1994# @param Info The ModuleAutoGen object
1995# @param AutoGenC The TemplateString object for C code
1996# @param AutoGenH The TemplateString object for header file
1997#
1998def CreateHeaderCode(Info, AutoGenC, AutoGenH):
1999 # file header
2000 AutoGenH.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.h'}))
2001 # header file Prologue
2002 AutoGenH.Append(gAutoGenHPrologueString.Replace({'File':'AUTOGENH','Guid':Info.Guid.replace('-','_')}))
2bcc713e 2003 AutoGenH.Append(gAutoGenHCppPrologueString)
30fdf114 2004 if Info.AutoGenVersion >= 0x00010005:
30fdf114
LG
2005 # header files includes
2006 AutoGenH.Append("#include <%s>\n" % gBasicHeaderFile)
2007 if Info.ModuleType in gModuleTypeHeaderFile \
2008 and gModuleTypeHeaderFile[Info.ModuleType][0] != gBasicHeaderFile:
2009 AutoGenH.Append("#include <%s>\n" % gModuleTypeHeaderFile[Info.ModuleType][0])
b36d134f
LG
2010 #
2011 # if either PcdLib in [LibraryClasses] sections or there exist Pcd section, add PcdLib.h
2012 # As if modules only uses FixedPcd, then PcdLib is not needed in [LibraryClasses] section.
2013 #
2014 if 'PcdLib' in Info.Module.LibraryClasses or Info.Module.Pcds:
4234283c
LG
2015 AutoGenH.Append("#include <Library/PcdLib.h>\n")
2016
30fdf114
LG
2017 AutoGenH.Append('\nextern GUID gEfiCallerIdGuid;\n\n')
2018
2019 if Info.IsLibrary:
2020 return
2021
2022 AutoGenH.Append("#define EFI_CALLER_ID_GUID \\\n %s\n" % GuidStringToGuidStructureString(Info.Guid))
2023
2024 if Info.IsLibrary:
2025 return
2026 # C file header
2027 AutoGenC.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.c'}))
2028 if Info.AutoGenVersion >= 0x00010005:
2029 # C file header files includes
2030 if Info.ModuleType in gModuleTypeHeaderFile:
2031 for Inc in gModuleTypeHeaderFile[Info.ModuleType]:
2032 AutoGenC.Append("#include <%s>\n" % Inc)
2033 else:
2034 AutoGenC.Append("#include <%s>\n" % gBasicHeaderFile)
2035
2036 #
2037 # Publish the CallerId Guid
2038 #
2039 AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(Info.Guid))
2040
2041## Create common code for header file
2042#
2043# @param Info The ModuleAutoGen object
2044# @param AutoGenC The TemplateString object for C code
2045# @param AutoGenH The TemplateString object for header file
2046#
2047def CreateFooterCode(Info, AutoGenC, AutoGenH):
2048 AutoGenH.Append(gAutoGenHEpilogueString)
2049
2050## Create code for a module
2051#
2052# @param Info The ModuleAutoGen object
2053# @param AutoGenC The TemplateString object for C code
2054# @param AutoGenH The TemplateString object for header file
b303ea72
LG
2055# @param UniGenCFlag UniString is generated into AutoGen C file when it is set to True
2056# @param UniGenBinBuffer Buffer to store uni string package data
30fdf114 2057#
b303ea72 2058def CreateCode(Info, AutoGenC, AutoGenH, StringH, UniGenCFlag, UniGenBinBuffer):
30fdf114
LG
2059 CreateHeaderCode(Info, AutoGenC, AutoGenH)
2060
2061 if Info.AutoGenVersion >= 0x00010005:
2062 CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH)
2063 CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH)
2064 CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH)
2065 CreatePcdCode(Info, AutoGenC, AutoGenH)
2066 CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH)
2067 CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH)
2068 CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH)
2069 CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH)
2070
2071 if Info.UnicodeFileList:
2072 FileName = "%sStrDefs.h" % Info.Name
2073 StringH.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
2074 StringH.Append(gAutoGenHPrologueString.Replace({'File':'STRDEFS', 'Guid':Info.Guid.replace('-','_')}))
b303ea72 2075 CreateUnicodeStringCode(Info, AutoGenC, StringH, UniGenCFlag, UniGenBinBuffer)
30fdf114
LG
2076 StringH.Append("\n#endif\n")
2077 AutoGenH.Append('#include "%s"\n' % FileName)
2078
2079 CreateFooterCode(Info, AutoGenC, AutoGenH)
2080
b36d134f 2081 # no generation of AutoGen.c for Edk modules without unicode file
30fdf114
LG
2082 if Info.AutoGenVersion < 0x00010005 and len(Info.UnicodeFileList) == 0:
2083 AutoGenC.String = ''
2084
2085## Create the code file
2086#
b303ea72
LG
2087# @param FilePath The path of code file
2088# @param Content The content of code file
2089# @param IsBinaryFile The flag indicating if the file is binary file or not
30fdf114
LG
2090#
2091# @retval True If file content is changed or file doesn't exist
2092# @retval False If the file exists and the content is not changed
2093#
b303ea72
LG
2094def Generate(FilePath, Content, IsBinaryFile):
2095 return SaveFileOnChange(FilePath, Content, IsBinaryFile)
30fdf114 2096