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