Changed the import path
[people/mcb30/basetools.git] / Source / Python / AutoGen / GenC.py
1 #!/usr/bin/env python
2 import string
3
4 import Common.EdkLogger
5
6 from Common.BuildToolError import *
7 from Common.DataType import *
8 from Common.EdkIIWorkspace import *
9 from BuildInfo import *
10 from StrGather import *
11
12 ItemTypeStringDatabase  = {
13     TAB_PCDS_FEATURE_FLAG:'FixedAtBuild',
14     TAB_PCDS_FIXED_AT_BUILD:'FixedAtBuild',
15     TAB_PCDS_PATCHABLE_IN_MODULE:'BinaryPatch',
16     TAB_PCDS_DYNAMIC:'',
17     TAB_PCDS_DYNAMIC+"Default":'',
18     TAB_PCDS_DYNAMIC+"Vpd":'',
19     TAB_PCDS_DYNAMIC+"Hii":'',
20     TAB_PCDS_DYNAMIC_EX:'',
21     TAB_PCDS_DYNAMIC_EX+"Default":'',
22     TAB_PCDS_DYNAMIC_EX+"Vpd":'',
23     TAB_PCDS_DYNAMIC_EX+"Hii":'',
24 }
25
26 gDynamicPcd = [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC+"Default", TAB_PCDS_DYNAMIC+"Vpd", TAB_PCDS_DYNAMIC+"Hii"]
27 gDynamicExPcd = [TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX+"Default", TAB_PCDS_DYNAMIC_EX+"Vpd", TAB_PCDS_DYNAMIC_EX+"Hii"]
28
29 DatumSizeStringDatabase = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOLEAN','VOID*':'8'}
30 DatumSizeStringDatabaseH = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOL','VOID*':'PTR'}
31 DatumSizeStringDatabaseLib = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'Bool','VOID*':'Ptr'}
32
33 PcdPhaseMap = {
34     "PEI_PCD_DRIVER"    :   "PEI",
35     "DXE_PCD_DRIVER"    :   "DXE"
36 }
37
38 PcdDatabaseCommonAutoGenH = """
39 //
40 // The following definition will be generated by build tool
41 //
42
43 //
44 // Common definitions
45 //
46 typedef UINT8 SKU_ID;
47
48 #define PCD_TYPE_SHIFT        28
49
50 #define PCD_TYPE_DATA         (0x0 << PCD_TYPE_SHIFT)
51 #define PCD_TYPE_HII          (0x8 << PCD_TYPE_SHIFT)
52 #define PCD_TYPE_VPD          (0x4 << PCD_TYPE_SHIFT)
53 #define PCD_TYPE_SKU_ENABLED  (0x2 << PCD_TYPE_SHIFT)
54 #define PCD_TYPE_STRING       (0x1 << PCD_TYPE_SHIFT)
55
56 #define PCD_TYPE_ALL_SET      (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_SKU_ENABLED | PCD_TYPE_STRING)
57
58 #define PCD_DATUM_TYPE_SHIFT  24
59
60 #define PCD_DATUM_TYPE_POINTER  (0x0 << PCD_DATUM_TYPE_SHIFT)
61 #define PCD_DATUM_TYPE_UINT8    (0x1 << PCD_DATUM_TYPE_SHIFT)
62 #define PCD_DATUM_TYPE_UINT16   (0x2 << PCD_DATUM_TYPE_SHIFT)
63 #define PCD_DATUM_TYPE_UINT32   (0x4 << PCD_DATUM_TYPE_SHIFT)
64 #define PCD_DATUM_TYPE_UINT64   (0x8 << PCD_DATUM_TYPE_SHIFT)
65
66 #define PCD_DATUM_TYPE_ALL_SET  (PCD_DATUM_TYPE_POINTER | \\
67                                  PCD_DATUM_TYPE_UINT8   | \\
68                                  PCD_DATUM_TYPE_UINT16  | \\
69                                  PCD_DATUM_TYPE_UINT32  | \\
70                                  PCD_DATUM_TYPE_UINT64)
71
72 #define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET))
73
74 typedef struct  {
75   UINT32  ExTokenNumber;
76   UINT16  LocalTokenNumber;   // PCD Number of this particular platform build
77   UINT16  ExGuidIndex;        // Index of GuidTable
78 } DYNAMICEX_MAPPING;
79
80 typedef struct {
81   UINT32  SkuDataStartOffset; //We have to use offsetof MACRO as we don't know padding done by compiler
82   UINT32  SkuIdTableOffset;   //Offset from the PCD_DB
83 } SKU_HEAD;
84
85 typedef struct {
86   UINT16  GuidTableIndex;     // Offset in Guid Table in units of GUID.
87   UINT16  StringIndex;        // Offset in String Table in units of UINT16.
88   UINT16  Offset;             // Offset in Variable
89   UINT16  DefaultValueOffset; // Offset of the Default Value
90 } VARIABLE_HEAD;
91
92 typedef  struct {
93   UINT32  Offset;
94 } VPD_HEAD;
95
96 typedef UINT16 STRING_HEAD;
97
98 typedef UINT16 SIZE_INFO;
99
100 #define offsetof(s,m)  (UINT32) (UINTN) &(((s *)0)->m)
101
102 """
103
104 PcdDatabaseEpilogueAutoGenH = """
105 typedef struct {
106   PEI_PCD_DATABASE PeiDb;
107   DXE_PCD_DATABASE DxeDb;
108 } PCD_DATABASE;
109
110 #define PCD_TOTAL_TOKEN_NUMBER (PEI_LOCAL_TOKEN_NUMBER + DXE_LOCAL_TOKEN_NUMBER)
111
112 """
113
114 PcdDatabaseAutoGenH = """
115 #define ${PHASE}_GUID_TABLE_SIZE                ${GUID_TABLE_SIZE}
116 #define ${PHASE}_STRING_TABLE_SIZE              ${STRING_TABLE_SIZE}
117 #define ${PHASE}_SKUID_TABLE_SIZE               ${SKUID_TABLE_SIZE}
118 #define ${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE  ${LOCAL_TOKEN_NUMBER_TABLE_SIZE}
119 #define ${PHASE}_LOCAL_TOKEN_NUMBER             ${LOCAL_TOKEN_NUMBER}
120 #define ${PHASE}_EXMAPPING_TABLE_SIZE           ${EXMAPPING_TABLE_SIZE}
121 #define ${PHASE}_EX_TOKEN_NUMBER                ${EX_TOKEN_NUMBER}
122 #define ${PHASE}_SIZE_TABLE_SIZE                ${SIZE_TABLE_SIZE}
123 #define ${PHASE}_GUID_TABLE_EMPTY               ${GUID_TABLE_EMPTY}
124 #define ${PHASE}_STRING_TABLE_EMPTY             ${STRING_TABLE_EMPTY}
125 #define ${PHASE}_SKUID_TABLE_EMPTY              ${SKUID_TABLE_EMPTY}
126 #define ${PHASE}_DATABASE_EMPTY                 ${DATABASE_EMPTY}
127 #define ${PHASE}_EXMAP_TABLE_EMPTY              ${EXMAP_TABLE_EMPTY}
128
129 typedef struct {
130 ${BEGIN}  UINT64             ${INIT_CNAME_DECL_UITN64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}];
131 ${END}
132 ${BEGIN}  UINT64             ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64};
133 ${END}
134 ${BEGIN}  UINT32             ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}];
135 ${END}
136 ${BEGIN}  UINT32             ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32};
137 ${END}
138 ${BEGIN}  VPD_HEAD           ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}];
139 ${END}
140   DYNAMICEX_MAPPING  ExMapTable[${PHASE}_EXMAPPING_TABLE_SIZE];
141   UINT32             LocalTokenNumberTable[${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE];
142   GUID               GuidTable[${PHASE}_GUID_TABLE_SIZE];
143 ${BEGIN}  STRING_HEAD        ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}];
144 ${END}
145 ${BEGIN}  VARIABLE_HEAD      ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}[${VARIABLE_HEAD_NUMSKUS_DECL}];
146 ${END}
147 ${BEGIN}  UINT16             StringTable${STRING_TABLE_INDEX}[${STRING_TABLE_LENGTH}]; /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
148 ${END}
149   SIZE_INFO          SizeTable[${PHASE}_SIZE_TABLE_SIZE];
150 ${BEGIN}  UINT16             ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}];
151 ${END}
152 ${BEGIN}  UINT16             ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16};
153 ${END}
154 ${BEGIN}  UINT8              ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}];
155 ${END}
156 ${BEGIN}  UINT8              ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8};
157 ${END}
158 ${BEGIN}  BOOLEAN            ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_BOOLEAN}];
159 ${END}
160 ${BEGIN}  BOOLEAN            ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN};
161 ${END}
162   UINT8              SkuIdTable[${PHASE}_SKUID_TABLE_SIZE];
163 ${SYSTEM_SKU_ID}
164 } ${PHASE}_PCD_DATABASE_INIT;
165
166 typedef struct {
167 ${PCD_DATABASE_UNINIT_EMPTY}
168 ${BEGIN}  UINT64   ${UNINIT_CNAME_DECL_UINT64}_${UNINIT_GUID_DECL_UINT64}[${UNINIT_NUMSKUS_DECL_UINT64}];
169 ${END}
170 ${BEGIN}  UINT32   ${UNINIT_CNAME_DECL_UINT32}_${UNINIT_GUID_DECL_UINT32}[${UNINIT_NUMSKUS_DECL_UINT32}];
171 ${END}
172 ${BEGIN}  UINT16   ${UNINIT_CNAME_DECL_UINT16}_${UNINIT_GUID_DECL_UINT16}[${UNINIT_NUMSKUS_DECL_UINT16}];
173 ${END}
174 ${BEGIN}  UINT8    ${UNINIT_CNAME_DECL_UINT8}_${UNINIT_GUID_DECL_UINT8}[${UNINIT_NUMSKUS_DECL_UINT8}];
175 ${END}
176 ${BEGIN}  BOOLEAN  ${UNINIT_CNAME_DECL_BOOLEAN}_${UNINIT_GUID_DECL_BOOLEAN}[${UNINIT_NUMSKUS_DECL_BOOLEAN}];
177 ${END}
178 } ${PHASE}_PCD_DATABASE_UNINIT;
179
180 #define PCD_${PHASE}_SERVICE_DRIVER_VERSION         2
181
182 typedef struct {
183   ${PHASE}_PCD_DATABASE_INIT    Init;
184   ${PHASE}_PCD_DATABASE_UNINIT  Uninit;
185 } ${PHASE}_PCD_DATABASE;
186
187 #define ${PHASE}_NEX_TOKEN_NUMBER (${PHASE}_LOCAL_TOKEN_NUMBER - ${PHASE}_EX_TOKEN_NUMBER)
188 """
189
190 EmptyPcdDatabaseAutoGenC = """
191 ${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
192   /* ExMapTable */
193   {
194     {0, 0, 0}
195   },
196   /* LocalTokenNumberTable */
197   {
198     0
199   },
200   /* GuidTable */
201   {
202     {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}
203   },
204   /* StringTable */
205   { 0 },
206   /* SizeTable */
207   {
208     0, 0
209   },
210   /* SkuIdTable */
211   { 0 },
212   ${SYSTEM_SKU_ID_VALUE}
213 };
214 """
215
216 PcdDatabaseAutoGenC = """
217 ${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
218 ${BEGIN}  { ${INIT_VALUE_UINT64} }, /*  ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}] */
219 ${END}
220 ${BEGIN}  ${VARDEF_VALUE_UINT64}, /* ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64} */
221 ${END}
222 ${BEGIN}  { ${INIT_VALUE_UINT32} }, /*  ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}] */
223 ${END}
224 ${BEGIN}  ${VARDEF_VALUE_UINT32}, /* ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32} */
225 ${END}
226   /* VPD */
227 ${BEGIN}  { ${VPD_HEAD_VALUE} }, /* ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}] */
228 ${END}
229   /* ExMapTable */
230   {
231 ${BEGIN}    { ${EXMAPPING_TABLE_EXTOKEN}, ${EXMAPPING_TABLE_LOCAL_TOKEN}, ${EXMAPPING_TABLE_GUID_INDEX} },
232 ${END}
233   },
234   /* LocalTokenNumberTable */
235   {
236 ${BEGIN}    offsetof(${PHASE}_PCD_DATABASE, ${TOKEN_INIT}.${TOKEN_CNAME}_${TOKEN_GUID}) | ${TOKEN_TYPE},
237 ${END}
238   },
239   /* GuidTable */
240   {
241 ${BEGIN}    ${GUID_STRUCTURE},
242 ${END}
243   },
244 ${BEGIN}  { ${STRING_HEAD_VALUE} }, /* ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}] */
245 ${END}
246 ${BEGIN}  /* ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}[${VARIABLE_HEAD_NUMSKUS_DECL}] */
247   {
248     ${VARIABLE_HEAD_VALUE}
249   },
250 ${END}
251  /* StringTable */
252 ${BEGIN}  ${STRING_TABLE_VALUE}, /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
253 ${END}
254   /* SizeTable */
255   {
256 ${BEGIN}    ${SIZE_TABLE_CURRENT_LENGTH}, ${SIZE_TABLE_MAXIMUM_LENGTH}, /* ${SIZE_TABLE_CNAME}_${SIZE_TABLE_GUID} */
257 ${END}
258   },
259 ${BEGIN}  { ${INIT_VALUE_UINT16} }, /*  ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}] */
260 ${END}
261 ${BEGIN}  ${VARDEF_VALUE_UINT16}, /* ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16} */
262 ${END}
263 ${BEGIN}  { ${INIT_VALUE_UINT8} }, /*  ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}] */
264 ${END}
265 ${BEGIN}  ${VARDEF_VALUE_UINT8}, /* ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8} */
266 ${END}
267 ${BEGIN}  { ${INIT_VALUE_BOOLEAN} }, /*  ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}] */
268 ${END}
269 ${BEGIN}  ${VARDEF_VALUE_BOOLEAN}, /* ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN} */
270 ${END}
271   /* SkuIdTable */
272   { ${BEGIN}${SKUID_VALUE}, ${END} },
273   ${SYSTEM_SKU_ID_VALUE}
274 };
275 """
276
277 #
278 # AutoGen File Header Templates
279 #
280 AutoGenHeaderString = """\
281 /**
282   DO NOT EDIT
283   FILE auto-generated
284   Module name:
285     $FileName
286   Abstract:       Auto-generated $FileName for building module or library.
287 **/
288 """
289
290 AutoGenHPrologueString = """
291 #ifndef _AUTOGENH_${Guid}
292 #define _AUTOGENH_${Guid}
293
294 extern int __make_me_compile_correctly;
295 """
296
297 AutoGenHEpilogueString = """
298 #endif
299 """
300
301 #
302 # PEI Core Entry Point Templates
303 #
304 PeiCoreEntryPointString = """
305 EFI_STATUS
306 ${Function} (
307   IN EFI_PEI_STARTUP_DESCRIPTOR  *PeiStartupDescriptor,
308   IN VOID                        *OldCoreData
309   );
310
311 EFI_STATUS
312 EFIAPI
313 ProcessModuleEntryPointList (
314   IN EFI_PEI_STARTUP_DESCRIPTOR  *PeiStartupDescriptor,
315   IN VOID                        *OldCoreData
316   )
317
318 {
319   return ${Function} (PeiStartupDescriptor, OldCoreData);
320 }
321 """
322
323 #
324 # DXE Core Entry Point Templates
325 #
326 DxeCoreEntryPointString = """
327 const UINT32 _gUefiDriverRevision = 0;
328
329 VOID
330 ${Function} (
331   IN VOID  *HobStart
332   );
333
334 VOID
335 EFIAPI
336 ProcessModuleEntryPointList (
337   IN VOID  *HobStart
338   )
339
340 {
341   ${Function} (HobStart);
342 }
343 """
344
345 #
346 # PEIM Entry Point Templates
347 #
348 PeimEntryPointString = [
349 """
350 GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;
351
352 EFI_STATUS
353 EFIAPI
354 ProcessModuleEntryPointList (
355   IN EFI_FFS_FILE_HEADER  *FfsHeader,
356   IN EFI_PEI_SERVICES     **PeiServices
357   )
358
359 {
360   return EFI_SUCCESS;
361 }
362 """,
363 """
364 GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;
365
366 EFI_STATUS
367 ${Function} (
368   IN EFI_FFS_FILE_HEADER  *FfsHeader,
369   IN EFI_PEI_SERVICES     **PeiServices
370   );
371
372 EFI_STATUS
373 EFIAPI
374 ProcessModuleEntryPointList (
375   IN EFI_FFS_FILE_HEADER  *FfsHeader,
376   IN EFI_PEI_SERVICES     **PeiServices
377   )
378
379 {
380   return ${Function} (FfsHeader, PeiServices);
381 }
382 """,
383 """
384 GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;
385
386 ${BEGIN}
387 EFI_STATUS
388 ${Function} (
389   IN EFI_FFS_FILE_HEADER  *FfsHeader,
390   IN EFI_PEI_SERVICES     **PeiServices
391   );
392 ${END}
393
394 EFI_STATUS
395 EFIAPI
396 ProcessModuleEntryPointList (
397   IN EFI_FFS_FILE_HEADER  *FfsHeader,
398   IN EFI_PEI_SERVICES     **PeiServices
399   )
400
401 {
402   EFI_STATUS  Status;
403   EFI_STATUS  CombinedStatus;
404
405   CombinedStatus = EFI_LOAD_ERROR;
406 ${BEGIN}
407   Status = ${Function} (FfsHeader, PeiServices);
408   if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {
409     CombinedStatus = Status;
410   }
411 ${END}
412   return CombinedStatus;
413 }
414 """
415 ]
416
417 #
418 # DXE SMM Entry Point Templates
419 #
420 DxeSmmEntryPointString = [
421 """
422 EFI_STATUS
423 EFIAPI
424 ProcessModuleEntryPointList (
425   IN EFI_HANDLE        ImageHandle,
426   IN EFI_SYSTEM_TABLE  *SystemTable
427   )
428
429 {
430   return EFI_SUCCESS;
431 }
432 """,
433 """
434 ${BEGIN}
435 EFI_STATUS
436 ${Function} (
437   IN EFI_HANDLE        ImageHandle,
438   IN EFI_SYSTEM_TABLE  *SystemTable
439   );
440 ${END}
441
442 static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
443 static EFI_STATUS  mDriverEntryPointStatus = EFI_LOAD_ERROR;
444
445 VOID
446 EFIAPI
447 ExitDriver (
448   IN EFI_STATUS  Status
449   )
450 {
451   if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
452     mDriverEntryPointStatus = Status;
453   }
454   LongJump (&mJumpContext, (UINTN)-1);
455   ASSERT (FALSE);
456 }
457
458 EFI_STATUS
459 EFIAPI
460 ProcessModuleEntryPointList (
461   IN EFI_HANDLE        ImageHandle,
462   IN EFI_SYSTEM_TABLE  *SystemTable
463   )
464
465 {
466 ${BEGIN}
467   if (SetJump (&mJumpContext) == 0) {
468     ExitDriver (${Function} (ImageHandle, SystemTable));
469     ASSERT (FALSE);
470   }
471 ${END}
472
473   return mDriverEntryPointStatus;
474 }
475 """
476 ]
477
478 #
479 # UEFI Entry Point Templates
480 #
481 UefiEntryPointString = [
482 """
483 const UINT32 _gUefiDriverRevision = 0;
484
485 EFI_STATUS
486 EFIAPI
487 ProcessModuleEntryPointList (
488   IN EFI_HANDLE        ImageHandle,
489   IN EFI_SYSTEM_TABLE  *SystemTable
490   )
491 {
492   return EFI_SUCCESS;
493 }
494 """,
495 """
496 const UINT32 _gUefiDriverRevision = 0;
497
498 EFI_STATUS
499 ${Function} (
500   IN EFI_HANDLE        ImageHandle,
501   IN EFI_SYSTEM_TABLE  *SystemTable
502   );
503
504 EFI_STATUS
505 EFIAPI
506 ProcessModuleEntryPointList (
507   IN EFI_HANDLE        ImageHandle,
508   IN EFI_SYSTEM_TABLE  *SystemTable
509   )
510
511 {
512   return ${Function} (ImageHandle, SystemTable);
513 }
514
515 VOID
516 EFIAPI
517 ExitDriver (
518   IN EFI_STATUS  Status
519   )
520 {
521   if (EFI_ERROR (Status)) {
522     ProcessLibraryDestructorList (gImageHandle, gST);
523   }
524   gBS->Exit (gImageHandle, Status, 0, NULL);
525 }
526 """,
527 """
528 const UINT32 _gUefiDriverRevision = 0;
529
530 ${BEGIN}
531 EFI_STATUS
532 ${Function} (
533   IN EFI_HANDLE        ImageHandle,
534   IN EFI_SYSTEM_TABLE  *SystemTable
535   );
536 ${END}
537
538 EFI_STATUS
539 EFIAPI
540 ProcessModuleEntryPointList (
541   IN EFI_HANDLE        ImageHandle,
542   IN EFI_SYSTEM_TABLE  *SystemTable
543   )
544
545 {
546   ${BEGIN}
547   if (SetJump (&mJumpContext) == 0) {
548     ExitDriver (${Function} (ImageHandle, SystemTable));
549     ASSERT (FALSE);
550   }
551   ${END}
552   return mDriverEntryPointStatus;
553 }
554
555 static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
556 static EFI_STATUS  mDriverEntryPointStatus = EFI_LOAD_ERROR;
557
558 VOID
559 EFIAPI
560 ExitDriver (
561   IN EFI_STATUS  Status
562   )
563 {
564   if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
565     mDriverEntryPointStatus = Status;
566   }
567   LongJump (&mJumpContext, (UINTN)-1);
568   ASSERT (FALSE);
569 }
570 """
571 ]
572
573 #
574 # UEFI Unload Image Templates
575 #
576 UefiUnloadImageString = [
577 """
578 GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
579
580 EFI_STATUS
581 EFIAPI
582 ProcessModuleUnloadList (
583   IN EFI_HANDLE        ImageHandle
584   )
585 {
586   return EFI_SUCCESS;
587 }
588 """,
589 """
590 GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
591
592 ${BEGIN}
593 EFI_STATUS
594 ${Function} (
595   IN EFI_HANDLE        ImageHandle
596   );
597 ${END}
598
599 EFI_STATUS
600 EFIAPI
601 ProcessModuleUnloadList (
602   IN EFI_HANDLE        ImageHandle
603   )
604 {
605   return ${Function} (ImageHandle);
606 }
607 """,
608 """
609 GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
610
611 ${BEGIN}
612 EFI_STATUS
613 ${Function} (
614   IN EFI_HANDLE        ImageHandle
615   );
616 ${END}
617
618 EFI_STATUS
619 EFIAPI
620 ProcessModuleUnloadList (
621   IN EFI_HANDLE        ImageHandle
622   )
623 {
624   EFI_STATUS  Status;
625
626   Status = EFI_SUCCESS;
627 ${BEGIN}
628   if (EFI_ERROR (Status)) {
629     ${Function} (ImageHandle);
630   } else {
631     Status = ${Function} (ImageHandle);
632   }
633 ${END}
634   return Status;
635 }
636 """
637 ]
638
639 #
640 # Library Constructor and Destructor Templates
641 #
642 LibraryString = [
643 """
644 VOID
645 EFIAPI
646 ProcessLibrary${Type}List (
647   VOID
648   )
649 {
650 }
651 """,
652 """
653 VOID
654 EFIAPI
655 ProcessLibrary${Type}List (
656   IN EFI_FFS_FILE_HEADER       *FfsHeader,
657   IN EFI_PEI_SERVICES          **PeiServices
658   )
659 {
660 }
661 """,
662 """
663 VOID
664 EFIAPI
665 ProcessLibrary${Type}List (
666   IN EFI_HANDLE        ImageHandle,
667   IN EFI_SYSTEM_TABLE  *SystemTable
668   )
669 {
670 }
671 """,
672 """
673 ${BEGIN}
674 RETURN_STATUS
675 EFIAPI
676 ${Function} (
677   VOID
678   );
679 ${END}
680
681 VOID
682 EFIAPI
683 ProcessLibrary${Type}List (
684   VOID
685   )
686 {
687   EFI_STATUS  Status;
688
689 ${BEGIN}
690   Status = ${Function} ();
691   ASSERT_EFI_ERROR (Status);
692 ${END}
693 }
694 """,
695 """
696 ${BEGIN}
697 EFI_STATUS
698 EFIAPI
699 ${Function} (
700   IN EFI_FFS_FILE_HEADER       *FfsHeader,
701   IN EFI_PEI_SERVICES          **PeiServices
702   );
703 ${END}
704
705 VOID
706 EFIAPI
707 ProcessLibrary${Type}List (
708   IN EFI_FFS_FILE_HEADER       *FfsHeader,
709   IN EFI_PEI_SERVICES          **PeiServices
710   )
711 {
712   EFI_STATUS  Status;
713
714 ${BEGIN}
715   Status = ${Function} (FfsHeader, PeiServices);
716   ASSERT_EFI_ERROR (Status);
717 ${END}
718 }
719 """,
720 """
721 ${BEGIN}
722 EFI_STATUS
723 EFIAPI
724 ${Function} (
725   IN EFI_HANDLE        ImageHandle,
726   IN EFI_SYSTEM_TABLE  *SystemTable
727   );
728 ${END}
729
730 VOID
731 EFIAPI
732 ProcessLibrary${Type}List (
733   IN EFI_HANDLE        ImageHandle,
734   IN EFI_SYSTEM_TABLE  *SystemTable
735   )
736 {
737   EFI_STATUS  Status;
738
739 ${BEGIN}
740   Status = ${Function} (ImageHandle, SystemTable);
741   ASSERT_EFI_ERROR (Status);
742 ${END}
743 }
744 """
745 ]
746
747 SpecificationString = """
748 ${BEGIN}
749 #define ${Specification}
750 ${END}
751 """
752
753 BasicHeaderFile = "Base.h"
754
755 ModuleTypeHeaderFile = {
756     "BASE"              :   [BasicHeaderFile],
757     "SEC"               :   ["PiPei.h", "Library/DebugLib.h"],
758     "PEI_CORE"          :   ["PiPei.h", "Library/DebugLib.h"],  
759     "PEIM"              :   ["PiPei.h", "Library/DebugLib.h"],  
760     "DXE_CORE"          :   ["PiDxe.h", "Library/DebugLib.h"],  
761     "DXE_DRIVER"        :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
762     "DXE_SMM_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
763     "DXE_RUNTIME_DRIVER":   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
764     "DXE_SAL_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
765     "UEFI_DRIVER"       :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"],
766     "UEFI_APPLICATION"  :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"],
767     "USER_DEFINED"      :   [BasicHeaderFile]
768 }
769
770 ##ModuleTypeHeaderFile = {
771 ##    "BASE"              :   BasicHeaderFile,
772 ##    "SEC"               :   ["Peim.h", "DebugLib.h", ],         # "PiPei.h",
773 ##    "PEI_CORE"          :   ["PeiCore.h", "DebugLib.h"],        # "PiPei.h",
774 ##    "PEIM"              :   ["Peim.h", "DebugLib.h"],           # PiPei.h",
775 ##    "DXE_CORE"          :   ["DxeCore.h", "DebugLib.h"],        # PiDxe.h",
776 ##    "DXE_DRIVER"        :   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
777 ##    "DXE_SMM_DRIVER"    :   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
778 ##    "DXE_RUNTIME_DRIVER":   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
779 ##    "DXE_SAL_DRIVER"    :   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
780 ##    "UEFI_DRIVER"       :   ["Uefi.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],
781 ##    "UEFI_APPLICATION"  :   ["Uefi.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"]
782 ##}
783
784 def GuidStringToGuidStructureString(Guid):
785   GuidList = Guid.split('-')
786   Result = '{'
787   for Index in range(0,3,1):
788     Result = Result + '0x' + GuidList[Index] + ', '
789   Result = Result + '{0x' + GuidList[3][0:2] + ', 0x' + GuidList[3][2:4]
790   for Index in range(0,12,2):
791     Result = Result + ', 0x' + GuidList[4][Index:Index+2]
792   Result += '}}'
793   return Result
794
795 def GuidStructureStringToGuidString(GuidValue):
796     guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "")
797     guidValueList = guidValueString.split(",")
798     if len(guidValueList) != 11:
799         raise AutoGenError(msg="Invalid GUID value string %s" % GuidValue)
800     return "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" % (
801             int(guidValueList[0], 16),
802             int(guidValueList[1], 16),
803             int(guidValueList[2], 16),
804             int(guidValueList[3], 16),
805             int(guidValueList[4], 16),
806             int(guidValueList[5], 16),
807             int(guidValueList[6], 16),
808             int(guidValueList[7], 16),
809             int(guidValueList[8], 16),
810             int(guidValueList[9], 16),
811             int(guidValueList[10], 16)
812             )
813
814 def GuidStructureStringToGuidValueName(GuidValue):
815     guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "")
816     guidValueList = guidValueString.split(",")
817     if len(guidValueList) != 11:
818         raise AutoGenError(msg="Invalid GUID value string %s" % GuidValue)
819     return "%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x" % (
820             int(guidValueList[0], 16),
821             int(guidValueList[1], 16),
822             int(guidValueList[2], 16),
823             int(guidValueList[3], 16),
824             int(guidValueList[4], 16),
825             int(guidValueList[5], 16),
826             int(guidValueList[6], 16),
827             int(guidValueList[7], 16),
828             int(guidValueList[8], 16),
829             int(guidValueList[9], 16),
830             int(guidValueList[10], 16)
831             )
832
833 def GetGuidValue(packages, cname):
834     for p in packages:
835         if cname in p.Guids:
836             return p.Guids[cname]
837         if cname in p.Protocols:
838             return p.Protocols[cname]
839         if cname in p.Ppis:
840             return p.Ppis[cname]
841     else:
842         raise AutoGenError(msg="Cannot find GUID value for %s in any package" % cname)
843
844 class AutoGenString(object):
845   def __init__(self):
846     self.String = ''
847
848   def Append(self, AppendString, Dictionary=None):
849     if Dictionary == None:
850       self.String += AppendString
851     else:
852       while AppendString.find('${BEGIN}') >= 0:
853         Start = AppendString.find('${BEGIN}')
854         End   = AppendString.find('${END}')
855         SubString = AppendString[AppendString.find('${BEGIN}'):AppendString.find('${END}')+6]
856         Max = 0
857         MaxLen = {}
858         for Key in Dictionary:
859           if SubString.find('$'+Key) >= 0 or SubString.find('${'+Key+'}') >= 0:
860             Value = Dictionary[Key]
861             if type(Value) == type([]):
862               MaxLen[Key] = len(Value)
863             else:
864               MaxLen[Key] = 1
865             if MaxLen[Key] > Max:
866               Max = MaxLen[Key]
867
868         NewString = ''
869         for Index in range(0,Max):
870           NewDict = {'BEGIN':'','END':''}
871           for Key in MaxLen:
872             NewDict[Key] = Dictionary[Key]
873             if type(Dictionary[Key]) == type([]):
874               NewDict[Key] = Dictionary[Key][Index]
875           NewString += string.Template(SubString).safe_substitute(NewDict)
876         AppendString = AppendString[0:Start] + NewString + AppendString[End+6:]
877       NewDict = {}
878       for Key in Dictionary:
879         NewDict[Key] = Dictionary[Key]
880         if type(Dictionary[Key]) == type([]) and len(Dictionary[Key]) > 0:
881           NewDict[Key] = Dictionary[Key][0]
882       self.String += string.Template(AppendString).safe_substitute(NewDict)
883
884 def CreateModulePcdCode(info, autoGenC, autoGenH, pcd):
885     pcdTokenNumber = info.PlatformInfo.PcdTokenNumber
886     #
887     # Write PCDs
888     #
889     pcdTokenName = '_PCD_TOKEN_' + pcd.TokenCName
890     if pcd.Type in gDynamicExPcd:
891         tokenNumber = pcd.TokenValue
892     else:
893         tokenNumber = pcdTokenNumber[pcd.TokenCName, pcd.TokenSpaceGuidCName]
894     autoGenH.Append('#define %s  %d\n' % (pcdTokenName, tokenNumber))
895
896     EdkLogger.debug(EdkLogger.DEBUG_7, "Creating code for " + pcd.TokenCName + "/" + pcd.TokenSpaceGuidCName)
897     if pcd.Type not in ItemTypeStringDatabase:
898         raise AutoGenError(msg="Unknown PCD type [%s] of PCD %s/%s" % (pcd.Type, pcd.TokenCName, pcd.TokenSpaceGuidCName))
899     if pcd.DatumType not in DatumSizeStringDatabase:
900         raise AutoGenError(msg="Unknown datum type [%s] of PCD %s/%s" % (pcd.DatumType, pcd.TokenCName, pcd.TokenSpaceGuidCName))
901
902     datumSize = DatumSizeStringDatabase[pcd.DatumType]
903     datumSizeLib = DatumSizeStringDatabaseLib[pcd.DatumType]
904     getModeName = '_PCD_GET_MODE_' + DatumSizeStringDatabaseH[pcd.DatumType] + '_' + pcd.TokenCName
905     setModeName = '_PCD_SET_MODE_' + DatumSizeStringDatabaseH[pcd.DatumType] + '_' + pcd.TokenCName
906
907     if pcd.Type in gDynamicExPcd:
908         autoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (getModeName, datumSizeLib, pcd.TokenSpaceGuidCName, pcdTokenName))
909         if DatumType == 'VOID*':
910             autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (setModeName, datumSizeLib, pcd.TokenSpaceGuidCName, pcdTokenName))
911         else:
912             autoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (setModeName, datumSizeLib, pcd.TokenSpaceGuidCName, pcdTokenName))
913     elif pcd.Type in gDynamicPcd:
914         autoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (getModeName, datumSizeLib, pcdTokenName))
915         if pcd.DatumType == 'VOID*':
916             autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(setModeName, datumSizeLib, pcdTokenName))
917         else:
918             autoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (setModeName, datumSizeLib, pcdTokenName))
919     else:
920         PcdVariableName = '_gPcd_' + ItemTypeStringDatabase[pcd.Type] + '_' + pcd.TokenCName
921         Const = 'const'
922         if pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
923             Const = ''
924         Type = ''
925         Array = ''
926         Value = pcd.DefaultValue
927         if pcd.DatumType == 'UINT64':
928             Value += 'ULL'
929         if pcd.DatumType == 'VOID*':
930             ArraySize = int(pcd.MaxDatumSize)
931             if Value[0] == '{':
932                 Type = '(VOID *)'
933             else:
934                 Unicode = False
935                 if Value[0] == 'L':
936                     Unicode = True
937                 Value = Value.lstrip('L').strip('"')
938                 NewValue = '{'
939                 for Index in range(0,len(Value)):
940                     NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
941                     if Unicode:
942                         NewValue = NewValue + str(ord(Value[Index]) / 0x100) + ', '
943                 if Unicode:
944                     if ArraySize < (len(Value)*2 + 2):
945                         ArraySize = len(Value)*2 + 2
946                     NewValue = NewValue + '0, '
947                 else:
948                     if ArraySize < (len(Value) + 1):
949                         ArraySize = len(Value) + 1
950                 Value = NewValue + '0 }'
951             Array = '[%d]' % ArraySize
952
953         PcdValueName = '_PCD_VALUE_' + pcd.TokenCName
954         if pcd.DatumType == 'VOID*' and Value[0] == '{':
955             autoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (pcd.TokenCName, pcd.MaxDatumSize))
956             autoGenH.Append('#define %s  %s%s\n' %(PcdValueName, Type, PcdVariableName))
957             autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
958             autoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
959             autoGenH.Append('#define %s  %s%s\n' %(getModeName, Type, PcdVariableName))
960         else:
961             autoGenH.Append('#define %s  %s\n' %(PcdValueName, Value))
962             autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, pcd.DatumType, PcdVariableName, PcdValueName))
963             autoGenH.Append('extern %s  %s  %s%s;\n' % (Const, pcd.DatumType, PcdVariableName, Array))
964             autoGenH.Append('#define %s  %s%s\n' % (getModeName, Type, PcdVariableName))
965
966         if pcd.Type == 'PATCHABLE_IN_MODULE':
967             if pcd.DatumType == 'VOID*':
968                 autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPatchPcdSetPtr(_gPcd_BinaryPatch_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (setModeName, pcd.TokenCName, pcd.TokenCName))
969             else:
970                 autoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (setModeName, PcdVariableName))
971         else:
972             autoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % setModeName)
973
974 def CreateLibraryPcdCode(info, autoGenC, autoGenH, pcd):
975     pcdTokenNumber = info.PlatformInfo.PcdTokenNumber
976     tokenSpaceGuidCName = pcd.TokenSpaceGuidCName
977     tokenCName  = pcd.TokenCName
978     tokenNumber = pcdTokenNumber[tokenCName, tokenSpaceGuidCName]
979     
980     if pcd.Type not in ItemTypeStringDatabase:
981         raise AutoGenError(msg="Unknown PCD type [%s] of PCD %s/%s" % (pcd.Type, pcd.TokenCName, pcd.TokenSpaceGuidCName))
982     if pcd.DatumType not in DatumSizeStringDatabase:
983         raise AutoGenError(msg="Unknown datum type [%s] of PCD %s/%s" % (pcd.DatumType, pcd.TokenCName, pcd.TokenSpaceGuidCName))
984
985     datumType   = pcd.DatumType
986     datumSize   = DatumSizeStringDatabaseH[datumType]
987     datumSizeLib= DatumSizeStringDatabaseLib[datumType]
988     getModeName = '_PCD_GET_MODE_' + datumSize + '_' + tokenCName
989     setModeName = '_PCD_SET_MODE_' + datumSize + '_' + tokenCName
990
991     type = ''
992     array = ''
993     if pcd.DatumType == 'VOID*':
994         type = '(VOID *)'
995         array = '[]'
996
997     autoGenH.Append('#define _PCD_TOKEN_%s  %d\n' % (tokenCName, tokenNumber))
998
999     pcdItemType = pcd.Type
1000     if pcdItemType in gDynamicPcd:
1001         pcdItemType = TAB_PCDS_FIXED_AT_BUILD
1002         if (tokenCName, tokenSpaceGuidCName) in info.PlatformInfo.Platform.Pcds:
1003             pcdItemType  = info.PlatformInfo.Platform.Pcds[tokenCName, tokenSpaceGuidCName].Type
1004     if pcdItemType in gDynamicExPcd:
1005         pcdTokenName = '_PCD_TOKEN_' + tokenCName
1006         autoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (getModeName, datumSizeLib, tokenSpaceGuidCName, pcdTokenName))
1007         if DatumType == 'VOID*':
1008             autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (setModeName,datumSizeLib, tokenSpaceGuidCName, pcdTokenName))
1009         else:
1010             autoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (setModeName, datumSizeLib, tokenSpaceGuidCName, pcdTokenName))
1011     if pcdItemType in gDynamicPcd:
1012         pcdTokenName = '_PCD_TOKEN_' + tokenCName
1013         autoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (getModeName, datumSizeLib, pcdTokenName))
1014         if datumType == 'VOID*':
1015             autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(setModeName, datumSizeLib, pcdTokenName))
1016         else:
1017             autoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (setModeName, datumSizeLib, pcdTokenName))
1018     if pcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
1019         pcdVariableName = '_gPcd_' + ItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + tokenCName
1020         autoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(datumType, tokenCName, array) )
1021         autoGenH.Append('#define %s  %s_gPcd_BinaryPatch_%s\n' %(getModeName, type, tokenCName))
1022         autoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (setModeName, pcdVariableName))
1023     if pcdItemType == TAB_PCDS_FIXED_AT_BUILD or pcdItemType == TAB_PCDS_FEATURE_FLAG:
1024         autoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(datumType, tokenCName, array))
1025         autoGenH.Append('#define %s  %s_gPcd_FixedAtBuild_%s\n' %(getModeName, type, tokenCName))
1026         autoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % setModeName)
1027
1028 def CreatePcdDatabasePhaseSpecificAutoGen (platform, phase):
1029     AutoGenC = AutoGenString()
1030     AutoGenH = AutoGenString()
1031
1032     Dict = {
1033         'PHASE'                         : phase,
1034         'GUID_TABLE_SIZE'               : '1',
1035         'STRING_TABLE_SIZE'             : '1',
1036         'SKUID_TABLE_SIZE'              : '1',
1037         'LOCAL_TOKEN_NUMBER_TABLE_SIZE' : '1',
1038         'LOCAL_TOKEN_NUMBER'            : '0',
1039         'EXMAPPING_TABLE_SIZE'          : '1',
1040         'EX_TOKEN_NUMBER'               : '0',
1041         'SIZE_TABLE_SIZE'               : '2',
1042         'GUID_TABLE_EMPTY'              : 'TRUE',
1043         'STRING_TABLE_EMPTY'            : 'TRUE',
1044         'SKUID_TABLE_EMPTY'             : 'TRUE',
1045         'DATABASE_EMPTY'                : 'TRUE',
1046         'EXMAP_TABLE_EMPTY'             : 'TRUE',
1047         'PCD_DATABASE_UNINIT_EMPTY'     : '  UINT8  dummy; /* PCD_DATABASE_UNINIT is emptry */',
1048         'SYSTEM_SKU_ID'                 : '  SKU_ID             SystemSkuId;',
1049         'SYSTEM_SKU_ID_VALUE'           : '0'
1050     }
1051
1052     for DatumType in ['UINT64','UINT32','UINT16','UINT8','BOOLEAN']:
1053         Dict['VARDEF_CNAME_' + DatumType] = []
1054         Dict['VARDEF_GUID_' + DatumType]  = []
1055         Dict['VARDEF_SKUID_' + DatumType] = []
1056         Dict['VARDEF_VALUE_' + DatumType] = []
1057         for Init in ['INIT','UNINIT']:
1058             Dict[Init+'_CNAME_DECL_' + DatumType]   = []
1059             Dict[Init+'_GUID_DECL_' + DatumType]    = []
1060             Dict[Init+'_NUMSKUS_DECL_' + DatumType] = []
1061             Dict[Init+'_VALUE_' + DatumType]        = []
1062
1063     for Type in ['STRING_HEAD','VPD_HEAD','VARIABLE_HEAD']:
1064         Dict[Type + '_CNAME_DECL']   = []
1065         Dict[Type + '_GUID_DECL']    = []
1066         Dict[Type + '_NUMSKUS_DECL'] = []
1067         Dict[Type + '_VALUE'] = []
1068
1069     Dict['STRING_TABLE_INDEX'] = []
1070     Dict['STRING_TABLE_LENGTH']  = []
1071     Dict['STRING_TABLE_CNAME'] = []
1072     Dict['STRING_TABLE_GUID']  = []
1073     Dict['STRING_TABLE_VALUE'] = []
1074
1075     Dict['SIZE_TABLE_CNAME'] = []
1076     Dict['SIZE_TABLE_GUID']  = []
1077     Dict['SIZE_TABLE_CURRENT_LENGTH']  = []
1078     Dict['SIZE_TABLE_MAXIMUM_LENGTH']  = []
1079
1080     Dict['EXMAPPING_TABLE_EXTOKEN'] = []
1081     Dict['EXMAPPING_TABLE_LOCAL_TOKEN'] = []
1082     Dict['EXMAPPING_TABLE_GUID_INDEX'] = []
1083
1084     Dict['GUID_STRUCTURE'] = []
1085
1086     Dict['SKUID_VALUE'] = []
1087
1088     if phase == 'DXE':
1089         Dict['SYSTEM_SKU_ID'] = ''
1090         Dict['SYSTEM_SKU_ID_VALUE'] = ''
1091
1092     StringTableIndex = 0
1093     StringTableSize = 0
1094     NumberOfLocalTokens = 0
1095     NumberOfPeiLocalTokens = 0
1096     NumberOfDxeLocalTokens = 0
1097     NumberOfExTokens = 0
1098     NumberOfSizeItems = 0
1099     GuidList = []
1100
1101     for Pcd in platform.DynamicPcdList:
1102         CName = Pcd.TokenCName
1103         TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1104         EdkLogger.debug(EdkLogger.DEBUG_5, "PCD: %s %s (%s : %s)" % (CName, TokenSpaceGuidCName, Pcd.Phase, phase))
1105
1106         if Pcd.Phase == 'PEI':
1107             NumberOfPeiLocalTokens += 1
1108         if Pcd.Phase == 'DXE':
1109             NumberOfDxeLocalTokens += 1
1110         if Pcd.Phase != phase:
1111             continue
1112
1113         #
1114         # TODO: need GetGuidValue() definition
1115         #
1116         TokenSpaceGuid = GuidStructureStringToGuidValueName(GetGuidValue(platform.PackageList, TokenSpaceGuidCName))
1117         if Pcd.Type == 'DYNAMIC_EX':
1118             if TokenSpaceGuid not in GuidList:
1119                 GuidList += [TokenSpaceGuid]
1120                 Dict['GUID_STRUCTURE'].append(TokenSpaceGuid)
1121             NumberOfExTokens += 1
1122
1123         ValueList = []
1124         StringHeadOffsetList = []
1125         VpdHeadOffsetList = []
1126         VariableHeadValueList = []
1127         Pcd.InitString = 'UNINIT'
1128
1129         if Pcd.DatumType == 'VOID*':
1130             Pcd.TokenTypeList = ['PCD_DATUM_TYPE_POINTER']
1131         elif Pcd.DatumType == 'BOOLEAN':
1132             Pcd.TokenTypeList = ['PCD_DATUM_TYPE_UINT8']
1133         else:
1134             Pcd.TokenTypeList = ['PCD_DATUM_TYPE_' + Pcd.DatumType]
1135
1136         if len(Pcd.SkuInfoList) > 1:
1137             Pcd.TokenTypeList += ['PCD_TYPE_SKU_ENABLED']
1138
1139         for Sku in Pcd.SkuInfoList:
1140             SkuId = Sku.SkuId
1141             if SkuId == None or SkuId == '':
1142                 continue
1143
1144             if SkuId not in Dict['SKUID_VALUE']:
1145                 Dict['SKUID_VALUE'].append(SkuId)
1146
1147             SkuIdIndex =   Dict['SKUID_VALUE'].index(SkuId)
1148             if len(Sku.VariableName) > 0:
1149                 Pcd.TokenTypeList += ['PCD_TYPE_HII']
1150                 Pcd.InitString = 'INIT'
1151                 VariableNameStructure = '{' + ', '.join(Sku.VariableName) + ', 0x0000}'
1152                 if VariableNameStructure not in Dict['STRING_TABLE_VALUE']:
1153                     Dict['STRING_TABLE_CNAME'].append(CName)
1154                     Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
1155                     if StringTableIndex == 0:
1156                         Dict['STRING_TABLE_INDEX'].append('')
1157                     else:
1158                         Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
1159
1160                     Dict['STRING_TABLE_LENGTH'].append(len(Sku.VariableName) + 1)
1161                     Dict['STRING_TABLE_VALUE'].append(VariableNameStructure)
1162                     StringTableIndex += 1
1163                     StringTableSize += len(Sku.VariableName) + 1
1164
1165                 VariableHeadStringIndex = 0
1166                 for Index in range(Dict['STRING_TABLE_VALUE'].index(VariableNameStructure)):
1167                     VariableHeadStringIndex += Dict['STRING_TABLE_LENGTH'][Index]
1168
1169                 VariableGuid = GuidStructureStringToGuidValueName(self.GetGuidValue(Sku.VariableGuid))
1170                 if VariableGuid not in GuidList:
1171                     GuidList += [VariableGuid]
1172                     Dict['GUID_STRUCTURE'].append(VariableGuid)
1173                 VariableHeadGuidIndex = GuidList.index(VariableGuid)
1174
1175                 VariableHeadValueList.append('%d, %d, %s, offsetof(${PHASE}_PCD_DATABASE, Init.%s_%s_VariableDefault_%s)' %
1176                                              (VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset, CName, TokenSpaceGuid, SkuIdIndex))
1177                 Dict['VARDEF_CNAME_'+Pcd.DatumType].append(CName)
1178                 Dict['VARDEF_GUID_'+Pcd.DatumType].append(TokenSpaceGuid)
1179                 Dict['VARDEF_SKUID_'+Pcd.DatumType].append(SkuIdIndex)
1180                 Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue)
1181             elif Sku.VpdOffset != '':
1182                 Pcd.TokenTypeList += ['PCD_TYPE_VPD']
1183                 Pcd.InitString = 'INIT'
1184                 VpdHeadOffsetList.append(Sku.VpdOffset)
1185             else:
1186                 if Pcd.DatumType == 'VOID*':
1187                     Pcd.TokenTypeList += ['PCD_TYPE_STRING']
1188                     Pcd.InitString = 'INIT'
1189                     if Sku.DefaultValue != '':
1190                         NumberOfSizeItems += 1
1191                         Dict['STRING_TABLE_CNAME'].append(CName)
1192                         Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
1193
1194                         if StringTableIndex == 0:
1195                             Dict['STRING_TABLE_INDEX'].append('')
1196                         else:
1197                             Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
1198                         if Sku.DefaultValue[0] == 'L':
1199                             Size = len(Sku.DefaultValue) - 3
1200                             Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)
1201                         elif Sku.DefaultValue[0] == '"':
1202                             Size = len(Sku.DefaultValue) - 2
1203                             Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)
1204                         elif Sku.DefaultValue[0] == '{':
1205                             Size = len(Sku.DefaultValue.replace(',',' ').split())
1206                             Dict['STRING_TABLE_VALUE'].append('{' + Sku.DefaultValue + '}')
1207
1208                         StringHeadOffsetList.append(str(StringTableSize))
1209                         Dict['SIZE_TABLE_CNAME'].append(CName)
1210                         Dict['SIZE_TABLE_GUID'].append(TokenSpaceGuid)
1211                         Dict['SIZE_TABLE_CURRENT_LENGTH'].append(Size)
1212                         Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(Pcd.MaxDatumSize)
1213                         if Pcd.MaxDatumSize != '' and Pcd.MaxDatumSize > Size:
1214                             Size = int(Pcd.MaxDatumSize)
1215                         Dict['STRING_TABLE_LENGTH'].append(Size)
1216                         StringTableIndex += 1
1217                         StringTableSize += Size
1218                 else:
1219                     Pcd.TokenTypeList += ['PCD_TYPE_DATA']
1220                     if Sku.DefaultValue == 'TRUE':
1221                         Pcd.InitString = 'INIT'
1222                     elif Sku.DefaultValue.find('0x') == 0:
1223                         if int(Sku.DefaultValue,16) != 0:
1224                             Pcd.InitString = 'INIT'
1225                     elif Sku.DefaultValue[0].isdigit():
1226                         if int(Sku.DefaultValue) != 0:
1227                             Pcd.InitString = 'INIT'
1228                     ValueList.append(Sku.DefaultValue)
1229
1230         Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
1231         if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
1232             Dict['VARIABLE_HEAD_CNAME_DECL'].append(CName)
1233             Dict['VARIABLE_HEAD_GUID_DECL'].append(TokenSpaceGuid)
1234             Dict['VARIABLE_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
1235             Dict['VARIABLE_HEAD_VALUE'].append('{ %s }\n' % ' },\n    { '.join(VariableHeadValueList))
1236         if 'PCD_TYPE_VPD' in Pcd.TokenTypeList:
1237             Dict['VPD_HEAD_CNAME_DECL'].append(CName)
1238             Dict['VPD_HEAD_GUID_DECL'].append(TokenSpaceGuid)
1239             Dict['VPD_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
1240             Dict['VPD_HEAD_VALUE'].append('{ %s }' % ' }, { '.join(VpdHeadOffsetList))
1241         if 'PCD_TYPE_STRING' in Pcd.TokenTypeList:
1242             Dict['STRING_HEAD_CNAME_DECL'].append(CName)
1243             Dict['STRING_HEAD_GUID_DECL'].append(TokenSpaceGuid)
1244             Dict['STRING_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
1245             Dict['STRING_HEAD_VALUE'].append(', '.join(StringHeadOffsetList))
1246         if 'PCD_TYPE_DATA' in Pcd.TokenTypeList:
1247             Dict[Pcd.InitString+'_CNAME_DECL_'+Pcd.DatumType].append(CName)
1248             Dict[Pcd.InitString+'_GUID_DECL_'+Pcd.DatumType].append(TokenSpaceGuid)
1249             Dict[Pcd.InitString+'_NUMSKUS_DECL_'+Pcd.DatumType].append(len(Pcd.SkuInfoList))
1250             if Pcd.InitString == 'UNINIT':
1251                 Dict['PCD_DATABASE_UNINIT_EMPTY'] = ''
1252             else:
1253                 Dict[Pcd.InitString+'_VALUE_'+Pcd.DatumType].append(', '.join(ValueList))
1254
1255     if phase == 'PEI':
1256         NumberOfLocalTokens = NumberOfPeiLocalTokens
1257     if phase == 'DXE':
1258         NumberOfLocalTokens = NumberOfDxeLocalTokens
1259
1260     Dict['TOKEN_INIT']       = ['' for x in range(NumberOfLocalTokens)]
1261     Dict['TOKEN_CNAME']      = ['' for x in range(NumberOfLocalTokens)]
1262     Dict['TOKEN_GUID']       = ['' for x in range(NumberOfLocalTokens)]
1263     Dict['TOKEN_TYPE']       = ['' for x in range(NumberOfLocalTokens)]
1264
1265     for Pcd in platform.DynamicPcdList:
1266         CName = Pcd.TokenCName
1267         TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
1268         if Pcd.Phase != phase:
1269             continue
1270
1271         TokenSpaceGuid = GuidStructureStringToGuidValueName(GetGuidValue(platform.PackageList, TokenSpaceGuidCName))
1272         GeneratedTokenNumber = platform.PcdTokenNumber[CName, TokenSpaceGuidCName] - 1
1273         if phase == 'DXE':
1274             GeneratedTokenNumber -= NumberOfPeiLocalTokens
1275         Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Init'
1276         if Pcd.InitString == 'UNINIT':
1277             Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Uninit'
1278         Dict['TOKEN_CNAME'][GeneratedTokenNumber] = CName
1279         Dict['TOKEN_GUID'][GeneratedTokenNumber] = TokenSpaceGuid
1280         Dict['TOKEN_TYPE'][GeneratedTokenNumber] = ' | '.join(Pcd.TokenTypeList)
1281         if Pcd.Type == 'DYNAMIC_EX':
1282             Dict['EXMAPPING_TABLE_EXTOKEN'].append(Pcd.Token)
1283             Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(GeneratedTokenNumber)
1284             Dict['EXMAPPING_TABLE_GUID_INDEX'].append(GuidList.index(TokenSpaceGuid))
1285
1286     if GuidList != []:
1287         Dict['GUID_TABLE_EMPTY'] = 'FALSE'
1288         Dict['GUID_TABLE_SIZE'] = len(GuidList)
1289     else:
1290         Dict['GUID_STRUCTURE'] = [GuidStringToGuidStructureString('00000000-0000-0000-0000-000000000000')]
1291
1292     if StringTableIndex == 0:
1293         Dict['STRING_TABLE_INDEX'].append('')
1294         Dict['STRING_TABLE_LENGTH'].append(1)
1295         Dict['STRING_TABLE_CNAME'].append('')
1296         Dict['STRING_TABLE_GUID'].append('')
1297         Dict['STRING_TABLE_VALUE'].append('{ 0 }')
1298     else:
1299         Dict['STRING_TABLE_EMPTY'] = 'FALSE'
1300         Dict['STRING_TABLE_SIZE'] = StringTableSize
1301
1302     if Dict['SIZE_TABLE_CNAME'] == []:
1303         Dict['SIZE_TABLE_CNAME'].append('')
1304         Dict['SIZE_TABLE_GUID'].append('')
1305         Dict['SIZE_TABLE_CURRENT_LENGTH'].append(0)
1306         Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(0)
1307
1308     if NumberOfLocalTokens != 0:
1309         Dict['DATABASE_EMPTY']                = 'FALSE'
1310         Dict['LOCAL_TOKEN_NUMBER_TABLE_SIZE'] = NumberOfLocalTokens
1311         Dict['LOCAL_TOKEN_NUMBER']            = NumberOfLocalTokens
1312
1313     if NumberOfExTokens != 0:
1314         Dict['EXMAP_TABLE_EMPTY']    = 'FALSE'
1315         Dict['EXMAPPING_TABLE_SIZE'] = NumberOfExTokens
1316         Dict['EX_TOKEN_NUMBER']      = NumberOfExTokens
1317     else:
1318         Dict['EXMAPPING_TABLE_EXTOKEN'].append(0)
1319         Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(0)
1320         Dict['EXMAPPING_TABLE_GUID_INDEX'].append(0)
1321
1322     if NumberOfSizeItems != 0:
1323         Dict['SIZE_TABLE_SIZE'] = NumberOfSizeItems * 2
1324
1325     AutoGenH.Append(PcdDatabaseAutoGenH, Dict)
1326     if NumberOfLocalTokens == 0:
1327         AutoGenC.Append(EmptyPcdDatabaseAutoGenC, Dict)
1328     else:
1329         AutoGenC.Append(PcdDatabaseAutoGenC, Dict)
1330
1331     return AutoGenH, AutoGenC
1332
1333 def CreatePcdDatabaseCode (info, autoGenC, autoGenH):
1334     if info.PcdIsDriver == "":
1335         return
1336     autoGenH.Append(PcdDatabaseCommonAutoGenH)
1337     additionalAutoGenH, additionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (info.PlatformInfo, 'PEI')
1338     autoGenH.Append(additionalAutoGenH.String)
1339
1340     phase = PcdPhaseMap[info.PcdIsDriver]
1341     if phase == 'PEI':
1342         autoGenC.Append(additionalAutoGenC.String)
1343
1344     if phase == 'DXE':
1345         additionalAutoGenH, additionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (info.PlatformInfo, phase)
1346         autoGenH.Append(additionalAutoGenH.String)
1347         autoGenC.Append(additionalAutoGenC.String)
1348         autoGenH.Append(PcdDatabaseEpilogueAutoGenH)
1349
1350 def CreateLibraryConstructorCode(info, autoGenC, autoGenH):
1351     if info.IsLibrary:
1352         return
1353     #
1354     # Library Constructors
1355     #
1356     ConstructorList = []
1357     for lib in info.DependentLibraryList:
1358         if len(lib.ConstructorList) <= 0:
1359             continue
1360         ConstructorList.extend(lib.ConstructorList)
1361
1362     Dict = {'Type':'Constructor', 'Function':ConstructorList}
1363     if info.ModuleType == 'BASE':
1364         if len(ConstructorList) == 0:
1365             autoGenC.Append(LibraryString[0], Dict)
1366         else:
1367             autoGenC.Append(LibraryString[3], Dict)
1368     elif info.ModuleType in ['PEI_CORE','PEIM']:
1369         if len(ConstructorList) == 0:
1370             autoGenC.Append(LibraryString[1], Dict)
1371         else:
1372             autoGenC.Append(LibraryString[4], Dict)
1373     elif info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION']:
1374         if len(ConstructorList) == 0:
1375             autoGenC.Append(LibraryString[2], Dict)
1376         else:
1377             autoGenC.Append(LibraryString[5], Dict)
1378
1379 def CreateLibraryDestructorCode(info, autoGenC, autoGenH):
1380     if info.IsLibrary:
1381         return
1382     #
1383     # Library Destructors
1384     #
1385     DestructorList = []
1386     for lib in info.DependentLibraryList:
1387         if len(lib.DestructorList) <= 0:
1388             continue
1389         DestructorList.extend(lib.DestructorList)
1390
1391     DestructorList.reverse()
1392     if info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION']:
1393         if len(DestructorList) == 0:
1394             autoGenC.Append(LibraryString[2], {'Type':'Destructor','Function':DestructorList})
1395         else:
1396             autoGenC.Append(LibraryString[5], {'Type':'Destructor','Function':DestructorList})
1397
1398
1399 def CreateModuleEntryPointCode(info, autoGenC, autoGenH):
1400     if info.IsLibrary:
1401         return
1402     #
1403     # Module Entry Points
1404     #
1405     NumEntryPoints = len(info.Module.ModuleEntryPointList)
1406     Dict = {'Function':info.Module.ModuleEntryPointList}
1407
1408     if info.ModuleType in ['PEI_CORE', 'DXE_CORE']:
1409         if NumEntryPoints != 1:
1410             raise AutoGenError(msg='%s must have exactly one entry point' % info.ModuleType)
1411     if info.ModuleType == 'PEI_CORE':
1412         autoGenC.Append(PeiCoreEntryPointString, Dict)
1413     elif info.ModuleType == 'DXE_CORE':
1414         autoGenC.Append(DxeCoreEntryPointString, Dict)
1415     elif info.ModuleType == 'PEIM':
1416         if NumEntryPoints < 2:
1417             autoGenC.Append(PeimEntryPointString[NumEntryPoints], Dict)
1418         else:
1419             autoGenC.Append(PeimEntryPointString[2], Dict)
1420     elif info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SMM_DRIVER', 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION']:
1421         if info.ModuleType == 'DXE_SMM_DRIVER':
1422             if NumEntryPoints == 0:
1423                 autoGenC.Append(DxeSmmEntryPointString[0], Dict)
1424             else:
1425                 autoGenC.Append(DxeSmmEntryPointString[1], Dict)
1426         else:
1427             if NumEntryPoints < 2:
1428                 autoGenC.Append(UefiEntryPointString[NumEntryPoints], Dict)
1429             else:
1430                 autoGenC.Append(UefiEntryPointString[2], Dict)
1431
1432 def CreateModuleUnloadImageCode(info, autoGenC, autoGenH):
1433     if info.IsLibrary:
1434         return
1435     #
1436     # Unload Image Handlers
1437     #
1438     NumUnloadImage = len(info.Module.ModuleUnloadImageList)
1439     Dict = {'Count':NumUnloadImage, 'Function':info.Module.ModuleUnloadImageList}
1440     if NumUnloadImage < 2:
1441         autoGenC.Append(UefiUnloadImageString[NumUnloadImage], Dict)
1442     else:
1443         autoGenC.Append(UefiUnloadImageString[2], Dict)
1444
1445 def CreateGuidDefinitionCode(info, autoGenC, autoGenH):
1446     if info.IsLibrary:
1447         return
1448     #
1449     # GUIDs
1450     #
1451     for Key in info.GuidList:
1452         autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  %s = %s;\n' % (Key, info.GuidList[Key]))
1453
1454 def CreateProtocolDefinitionCode(info, autoGenC, autoGenH):
1455     if info.IsLibrary:
1456         return
1457     #
1458     # Protocol GUIDs
1459     #
1460     for Key in info.ProtocolList:
1461         autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  %s = %s;\n' % (Key, info.ProtocolList[Key]))
1462
1463 def CreatePpiDefinitionCode(info, autoGenC, autoGenH):
1464     if info.IsLibrary:
1465         return
1466     #
1467     # PPI GUIDs
1468     #
1469     for Key in info.PpiList:
1470         autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  %s = %s;\n' % (Key, info.PpiList[Key]))
1471
1472 def CreatePcdCode(info, autoGenC, autoGenH):
1473     if info.IsLibrary:
1474         for pcd in info.PcdList:
1475             CreateLibraryPcdCode(info, autoGenC, autoGenH, pcd)
1476     else:
1477         for pcd in info.PcdList:
1478             CreateModulePcdCode(info, autoGenC, autoGenH, pcd)
1479     CreatePcdDatabaseCode(info, autoGenC, autoGenH)
1480
1481 def CreateUnicodeStringCode(info, autoGenC, autoGenH):
1482     if len(info.UnicodeFileList) == 0:
1483         return
1484
1485     cwd = os.getcwd()
1486     os.chdir(info.WorkspaceDir)
1487
1488     incList = [os.path.join(info.WorkspaceDir, inc) for inc in info.IncludePathList]
1489     hCode, cCode = GetStringFiles(info.UnicodeFileList, incList, [], info.Name)
1490     autoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
1491     autoGenC.Append(cCode)
1492     autoGenC.Append("\n")
1493     autoGenH.Append("\n//\n//Unicode String ID\n//\n")
1494     autoGenH.Append(hCode)
1495     autoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % info.Name)
1496     os.chdir(cwd)
1497
1498 def CreateHeaderCode(info, autoGenC, autoGenH):
1499     # file header
1500     autoGenH.Append(AutoGenHeaderString,   {'FileName':'AutoGen.h'})
1501     # header file Prologue
1502     autoGenH.Append(AutoGenHPrologueString,{'Guid':info.Guid.replace('-','_')})
1503     # specification macros
1504     autoGenH.Append(SpecificationString,   {'Specification':info.MacroList})
1505     # header files includes
1506     autoGenH.Append("#include <%s>\n" % BasicHeaderFile)
1507
1508     if info.IsLibrary:
1509         return
1510
1511     # C file header
1512     autoGenC.Append(AutoGenHeaderString, {'FileName':'AutoGen.c'})
1513     # C file header files includes
1514     for inc in ModuleTypeHeaderFile[info.ModuleType]:
1515         autoGenC.Append("#include <%s>\n" % inc)
1516
1517     #
1518     # Publish the CallerId Guid
1519     #
1520     if info.ModuleType == 'BASE':
1521         autoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID  gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(info.Guid))
1522     else:
1523         autoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(info.Guid))
1524
1525 def CreateFooterCode(info, autoGenC, autoGenH):
1526     autoGenH.Append(AutoGenHEpilogueString)
1527
1528 def CreateCode(info, autoGenC, autoGenH):
1529     CreateHeaderCode(info, autoGenC, autoGenH)
1530
1531     CreateLibraryConstructorCode(info, autoGenC, autoGenH)
1532     CreateLibraryDestructorCode(info, autoGenC, autoGenH)
1533     CreateModuleEntryPointCode(info, autoGenC, autoGenH)
1534     CreateModuleUnloadImageCode(info, autoGenC, autoGenH)
1535     CreateGuidDefinitionCode(info, autoGenC, autoGenH)
1536     CreateProtocolDefinitionCode(info, autoGenC, autoGenH)
1537     CreatePpiDefinitionCode(info, autoGenC, autoGenH)
1538     CreatePcdCode(info, autoGenC, autoGenH)
1539     CreateUnicodeStringCode(info, autoGenC, autoGenH)
1540
1541     CreateFooterCode(info, autoGenC, autoGenH)
1542
1543 def Generate(filePath, autoGenC, autoGenH):
1544     CreateDirectory(filePath)
1545
1546     autoGenFileList = []
1547     SaveFile(os.path.join(filePath, "AutoGen.h"), autoGenH.String)
1548     autoGenFileList.append("AutoGen.h")
1549
1550     if autoGenC.String != "":
1551         SaveFile(os.path.join(filePath, "AutoGen.c"), autoGenC.String)
1552         autoGenFileList.append("AutoGen.c")
1553
1554     return autoGenFileList
1555
1556 def SaveFile(file, content):
1557     f = None
1558     if os.path.exists(file):
1559         f = open(file, "r")
1560         if content == f.read():
1561             f.close()
1562             return
1563         f.close()
1564     f = open(file, "w")
1565     f.write(content)
1566     f.close()