summaryrefslogtreecommitdiffstats
path: root/Tools/Source/GenBuild/org/tianocore/build/global/GlobalData.java
blob: a769816720f39c4b948cd82f05cbe4c0a2c0044e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/** @file
  GlobalData class. 
  
  GlobalData provide initializing, instoring, querying and update global data.
  It is a bridge to intercommunicate between multiple component, such as AutoGen,
  PCD and so on.   
 
Copyright (c) 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
package org.tianocore.build.global;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import org.apache.tools.ant.BuildException;
import org.apache.xmlbeans.XmlObject;
import org.tianocore.DbPathAndFilename;
import org.tianocore.FrameworkDatabaseDocument;
import org.tianocore.ModuleSurfaceAreaDocument;
import org.tianocore.ModuleSurfaceAreaDocument.ModuleSurfaceArea;
import org.tianocore.build.id.FpdModuleIdentification;
import org.tianocore.build.id.ModuleIdentification;
import org.tianocore.build.id.PackageIdentification;
import org.tianocore.build.id.PlatformIdentification;
import org.tianocore.build.pcd.entity.MemoryDatabaseManager;
import org.tianocore.build.toolchain.ToolChainAttribute;
import org.tianocore.build.toolchain.ToolChainConfig;
import org.tianocore.build.toolchain.ToolChainElement;
import org.tianocore.build.toolchain.ToolChainInfo;
import org.tianocore.build.toolchain.ToolChainKey;
import org.tianocore.build.toolchain.ToolChainMap;
import org.tianocore.exception.EdkException;
import org.tianocore.logger.EdkLog;

/**
  GlobalData provide initializing, instoring, querying and update global data.
  It is a bridge to intercommunicate between multiple component, such as AutoGen,
  PCD and so on. 
  
  <p>Note that all global information are initialized incrementally. All data will 
  parse and record only of necessary during build time. </p>
  
  @since GenBuild 1.0
**/
public class GlobalData {

    public static Logger log = Logger.getAnonymousLogger();
    
    ///
    /// Record current WORKSPACE Directory
    ///
    private static String workspaceDir = "";
    
    ///
    /// Be used to ensure Global data will be initialized only once.
    ///
    private static boolean globalFlag = false;
    
    ///
    /// Framework Database information: package list and platform list
    ///
    private static Set<PackageIdentification> packageList = new HashSet<PackageIdentification>();  

    private static Set<PlatformIdentification> platformList = new HashSet<PlatformIdentification>();

    ///
    /// Every detail SPD informations: Module list, Library class definition,
    ///   Package header file, GUID/PPI/Protocol definitions
    ///
    private static final Map<PackageIdentification, Spd> spdTable = new HashMap<PackageIdentification, Spd>();

    ///
    /// Build informations are divided into three parts:
    /// 1. From MSA 2. From FPD 3. From FPD' ModuleSA
    ///
    private static Map<ModuleIdentification, Map<String, XmlObject>> nativeMsa = new HashMap<ModuleIdentification, Map<String, XmlObject>>();

    private static Map<FpdModuleIdentification, Map<String, XmlObject>> fpdModuleSA= new HashMap<FpdModuleIdentification, Map<String, XmlObject>>();

    private static XmlObject fpdBuildOptions;

    private static XmlObject fpdDynamicPcds;
    
    ///
    /// Parsed modules list
    ///
    private static Map<FpdModuleIdentification, Map<String, XmlObject>> parsedModules = new HashMap<FpdModuleIdentification, Map<String, XmlObject>>();
    
    ///
    /// built modules list with ARCH, TARGET, TOOLCHAIN
    ///
    private static Set<FpdModuleIdentification> builtModules = new HashSet<FpdModuleIdentification>();
    
    ///
    /// PCD memory database stored all PCD information which collected from FPD,MSA and SPD.
    ///
//    private static final MemoryDatabaseManager pcdDbManager = new MemoryDatabaseManager();

    ///
    /// build target + tool chain family/tag name + arch + command types + command options
    ///
    ///
    /// Tool Chain Data
    /// toolsDef - build tool program information
    /// fpdBuildOption - all modules's build options for tool tag or tool chain families
    /// moduleSaBuildOption - build options for a specific module
    /// 
    private static ToolChainConfig toolsDef;

    private static ToolChainInfo toolChainInfo;
    private static ToolChainInfo toolChainEnvInfo;
    private static ToolChainInfo toolChainPlatformInfo;

    private static ToolChainMap platformToolChainOption;
    private static ToolChainMap platformToolChainFamilyOption;

    private static Map<FpdModuleIdentification, ToolChainMap> moduleToolChainOption = new HashMap<FpdModuleIdentification, ToolChainMap>();
    private static Map<FpdModuleIdentification, ToolChainMap> moduleToolChainFamilyOption = new HashMap<FpdModuleIdentification, ToolChainMap>();

    private static final MemoryDatabaseManager pcdDbManager = new MemoryDatabaseManager();

    /**
      Parse framework database (DB) and all SPD files listed in DB to initialize
      the environment for next build. This method will only be executed only once
      in the whole build process.  
    
      @param workspaceDatabaseFile the file name of framework database
      @param workspaceDir current workspace directory path
      @throws BuildException
            Framework Dababase or SPD or MSA file is not valid
    **/
    public synchronized static void initInfo(String workspaceDatabaseFile, String workspaceDir, String toolsDefFilename ) throws BuildException {
        //
        // ensure this method will be revoked only once
        //
        if (globalFlag) {
            return;
        }
        globalFlag = true;

		// 
        // Backup workspace directory. It will be used by other method
        //
        GlobalData.workspaceDir = workspaceDir.replaceAll("(\\\\)", "/");
        
        //
        // Parse tools definition file
        //
        //
        // If ToolChain has been set up before, do nothing.
        // CONF dir + tools definition file name
        //
        File toolsDefFile = new File(workspaceDir + File.separatorChar + toolsDefFilename);
        System.out.println("Using file [" + toolsDefFile.getPath() + "] as tools definition file. ");
        toolsDef = new ToolChainConfig(toolsDefFile);
        
        //
        // Parse Framework Database
        //
        File dbFile = new File(workspaceDir + File.separatorChar + workspaceDatabaseFile);
        try {
            FrameworkDatabaseDocument db = (FrameworkDatabaseDocument) XmlObject.Factory.parse(dbFile);
            //
            // validate FrameworkDatabaseFile
            //
            if (! db.validate()) {
                throw new BuildException("Framework Database file [" + dbFile.getPath() + "] is invalid.");
            }
            //
            // Get package list
            //
            if (db.getFrameworkDatabase().getPackageList() != null ) {
                List<DbPathAndFilename> packages = db.getFrameworkDatabase().getPackageList().getFilenameList();
                Iterator<DbPathAndFilename> iter = packages.iterator();
                while (iter.hasNext()) {
                    String fileName = iter.next().getStringValue();
                    Spd spd = new Spd(new File(workspaceDir + File.separatorChar + fileName));
                    packageList.add(spd.getPackageId());
                    spdTable.put(spd.getPackageId(), spd);
                }
            }

            //
            // Get platform list
            //
            if (db.getFrameworkDatabase().getPlatformList() != null) {
                List<DbPathAndFilename> platforms = db.getFrameworkDatabase().getPlatformList().getFilenameList();
                Iterator<DbPathAndFilename> iter = platforms.iterator();
                while (iter.hasNext()) {
                    String fileName = iter.next().getStringValue();
                    File fpdFile = new File(workspaceDir + File.separatorChar + fileName);
                    if ( ! fpdFile.exists() ) {
                        throw new BuildException("Platform file [" + fpdFile.getPath() + "] not exists. ");
                    }
                    XmlObject fpdDoc = XmlObject.Factory.parse(fpdFile);
                    //
                    // Verify FPD file, if is invalid, throw Exception
                    //
                    if (! fpdDoc.validate()) {
                        throw new BuildException("Framework Platform Surface Area file [" + fpdFile.getPath() + "] is invalid. ");
                    }
                    //
                    // We can change Map to XmlObject
                    //
                    //
                    // TBD check SPD or FPD is existed in FS
                    //
                    Map<String, XmlObject> fpdDocMap = new HashMap<String, XmlObject>();
                    fpdDocMap.put("PlatformSurfaceArea", fpdDoc);
                    SurfaceAreaQuery.setDoc(fpdDocMap);
                    PlatformIdentification platformId = SurfaceAreaQuery.getFpdHeader();
                    platformId.setFpdFile(fpdFile);
                    platformList.add(platformId);
                }
            }
        } catch (Exception e) {
            throw new BuildException("Parse workspace Database [" + dbFile.getPath() + "] Error.\n" + e.getMessage());
        }
    }
    
    /**
      Get the current WORKSPACE Directory. 
      
      @return current workspace directory
    **/
    public synchronized static String getWorkspacePath() {
        return workspaceDir;
    }


    /**
      Get the MSA file name with absolute path
     */
    public synchronized static File getMsaFile(ModuleIdentification moduleId) throws BuildException {
        File msaFile = null;
        //
        // TBD. Do only when package is null. 
        //
        Iterator iter = packageList.iterator();
        while (iter.hasNext()) {
            PackageIdentification packageId = (PackageIdentification)iter.next();
            Spd spd = spdTable.get(packageId);
            msaFile = spd.getModuleFile(moduleId);
            if (msaFile != null ) {
                break ;
            }
        }
        if (msaFile == null){
            throw new BuildException("Can't find Module [" + moduleId.getName() + "] in all packages. ");
        }
        else {
            return msaFile;
        }
    }

    public synchronized static PackageIdentification getPackageForModule(ModuleIdentification moduleId) {
        //
        // If package already defined in module
        //
        if (moduleId.getPackage() != null) {
            return moduleId.getPackage();
        }
        
        PackageIdentification packageId = null;
        Iterator iter = packageList.iterator();
        while (iter.hasNext()) {
            packageId = (PackageIdentification)iter.next();
            moduleId.setPackage(packageId);
            Spd spd = spdTable.get(packageId);
            if (spd.getModuleFile(moduleId) != null ) {
                break ;
            }
        }
        if (packageId == null){
            throw new BuildException("Can't find Module [" + moduleId.getName() + "] in all packages. ");
        }
        else {
            return packageId;
        }
    }
    
    /**
      Difference between build and parse: ToolChain and Target
    **/
    public synchronized static boolean isModuleBuilt(FpdModuleIdentification moduleId) {
        return builtModules.contains(moduleId);
    }
    
    public synchronized static void registerBuiltModule(FpdModuleIdentification fpdModuleId) {
        builtModules.add(fpdModuleId);
    }

    
    public synchronized static void registerFpdModuleSA(FpdModuleIdentification fpdModuleId, Map<String, XmlObject> doc) {
        Map<String, XmlObject> result = new HashMap<String, XmlObject>();
        Set keySet = doc.keySet();
        Iterator iter = keySet.iterator();
        while (iter.hasNext()){
            String key = (String)iter.next();
            XmlObject item = cloneXmlObject(doc.get(key), true);
            result.put(key, item);
        }
        fpdModuleSA.put(fpdModuleId, result);
    }

    public synchronized static boolean hasFpdModuleSA(FpdModuleIdentification fpdModuleId) {
        return fpdModuleSA.containsKey(fpdModuleId);
    }

    /**
      Query overrided module surface area information. If current is Package
      or Platform build, also include the information from FPD file. 
      
      <p>Note that surface area parsing is incremental. That means the method will 
      only parse the MSA and MBD files if necessary. </p>
    
      @param moduleName the base name of the module
      @return the overrided module surface area information
      @throws BuildException
              MSA or MBD is not valid
    **/
    public synchronized static Map<String, XmlObject> getDoc(FpdModuleIdentification fpdModuleId) throws BuildException {
        if (parsedModules.containsKey(fpdModuleId)) {
            return parsedModules.get(fpdModuleId);
        }
        Map<String, XmlObject> doc = new HashMap<String, XmlObject>();
        ModuleIdentification moduleId = fpdModuleId.getModule();
        //
        // First part: get the MSA files info
        //
        doc.putAll(getNativeMsa(moduleId));
        
        //
        // Second part: put build options
        //
        doc.put("BuildOptions", fpdBuildOptions);
        
        //
        // Third part: get Module info from FPD, such as Library instances, PCDs
        //
        if (fpdModuleSA.containsKey(fpdModuleId)){
            //
            // merge module info in FPD to final Doc
            // For Library Module, do nothing here
            //
            doc.putAll(fpdModuleSA.get(fpdModuleId));
        }
        parsedModules.put(fpdModuleId, doc);
        return doc;
    }

    public synchronized static Map<String, XmlObject> getDoc(ModuleIdentification moduleId, String arch) throws BuildException {
        FpdModuleIdentification fpdModuleId = new FpdModuleIdentification(moduleId, arch);
        return getDoc(fpdModuleId);
    }
    /**
      Query the native MSA information with module base name. 
      
      <p>Note that MSA parsing is incremental. That means the method will 
      only to parse the MSA files when never parsed before. </p>
      
      @param moduleName the base name of the module
      @return the native MSA information
      @throws BuildException
              MSA file is not valid
    **/
    public synchronized static Map<String, XmlObject> getNativeMsa(ModuleIdentification moduleId) throws BuildException {
        if (nativeMsa.containsKey(moduleId)) {
            return nativeMsa.get(moduleId);
        }
        File msaFile = getMsaFile(moduleId);
        Map<String, XmlObject> msaMap = getNativeMsa(msaFile);
        nativeMsa.put(moduleId, msaMap);
        return msaMap;
    }
    
    public synchronized static Map<String, XmlObject> getNativeMsa(File msaFile) throws BuildException {
        if (! msaFile.exists()) {
            throw new BuildException("Surface Area file [" + msaFile.getPath() + "] can't found.");
        }
        try {
            ModuleSurfaceAreaDocument doc = (ModuleSurfaceAreaDocument)XmlObject.Factory.parse(msaFile);
            //
            // Validate File if they accord with XML Schema
            //
            if ( ! doc.validate()){
                throw new BuildException("Module Surface Area file [" + msaFile.getPath() + "] is invalid.");
            }
            //
            // parse MSA file
            //
            ModuleSurfaceArea msa= doc.getModuleSurfaceArea();
            Map<String, XmlObject> msaMap = new HashMap<String, XmlObject>();
            msaMap.put("MsaHeader", cloneXmlObject(msa.getMsaHeader(), true));
            msaMap.put("ModuleDefinitions", cloneXmlObject(msa.getModuleDefinitions(), true));
            msaMap.put("LibraryClassDefinitions", cloneXmlObject(msa.getLibraryClassDefinitions(), true));
            msaMap.put("SourceFiles", cloneXmlObject(msa.getSourceFiles(), true));
            msaMap.put("PackageDependencies", cloneXmlObject(msa.getPackageDependencies(), true));
            msaMap.put("Protocols", cloneXmlObject(msa.getProtocols(), true));
            msaMap.put("PPIs", cloneXmlObject(msa.getPPIs(), true));
            msaMap.put("Guids", cloneXmlObject(msa.getGuids(), true));
            msaMap.put("Externs", cloneXmlObject(msa.getExterns(), true));
            msaMap.put("PcdCoded", cloneXmlObject(msa.getPcdCoded(), true));
            return msaMap;
        }
        catch (Exception ex){
            throw new BuildException(ex.getMessage());
        }
    }
    
    public static Map<String, XmlObject> getFpdBuildOptions() {
        Map<String, XmlObject> map = new HashMap<String, XmlObject>();
        map.put("BuildOptions", fpdBuildOptions);
        return map;
    }
    
    public static void setFpdBuildOptions(XmlObject fpdBuildOptions) {
        GlobalData.fpdBuildOptions = cloneXmlObject(fpdBuildOptions, true);
    }

    public static XmlObject getFpdDynamicPcds() {
        return fpdDynamicPcds;
    }

    public static void setFpdDynamicPcds(XmlObject fpdDynamicPcds) {
        GlobalData.fpdDynamicPcds = fpdDynamicPcds;
    }

    //////////////////////////////////////////////
    //////////////////////////////////////////////
    
    public static Set<ModuleIdentification> getModules(PackageIdentification packageId){
        Spd spd = spdTable.get(packageId);
        if (spd == null ) {
            Set<ModuleIdentification> dummy = new HashSet<ModuleIdentification>();
            return dummy;
        }
        else {
            return spd.getModules();
        }
    }

    /**
     * The header file path is relative to workspace dir
     */
    public static String[] getLibraryClassHeaderFiles(
            PackageIdentification[] packages, String name)
            throws BuildException {
        if (packages == null) {
            // throw Exception or not????
            return new String[0];
        }
        String[] result = null;
        for (int i = 0; i < packages.length; i++) {
            Spd spd = spdTable.get(packages[i]);
            //
            // If find one package defined the library class
            //
            if ((result = spd.getLibClassIncluder(name)) != null) {
                return result;
            }
        }
        //
        // If can't find library class declaration in every package
        //
        throw new BuildException("Can not find library class [" + name
                + "] declaration in every packages. ");
    }

    /**
     * The header file path is relative to workspace dir
     */
    public static String getPackageHeaderFiles(PackageIdentification packages,
            String moduleType) throws BuildException {
        if (packages == null) {
            return new String("");
        }
        Spd spd = spdTable.get(packages);
        //
        // If can't find package header file, skip it
        //
        String temp = null;
        if (spd != null) {
            if ((temp = spd.getPackageIncluder(moduleType)) != null) {
                return temp;
            } else {
                temp = "";
                return temp;
            }
        } else {
            return null;
        }
    }

    /**
     * return two values: {cName, GuidValue}
     */
    public static String[] getGuid(List<PackageIdentification> packages, String name)
            throws BuildException {
        if (packages == null) {
            // throw Exception or not????
            return new String[0];
        }
        String[] result = null;
        Iterator item = packages.iterator();
        while (item.hasNext()){
            Spd spd = spdTable.get(item.next());
            //
            // If find one package defined the GUID
            //
            if ((result = spd.getGuid(name)) != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * return two values: {cName, GuidValue}
     */
    public static String[] getPpiGuid(List<PackageIdentification> packages,
            String name) throws BuildException {
        if (packages == null) {
            return new String[0];
        }
        String[] result = null;
        Iterator item = packages.iterator();
        while (item.hasNext()){
            Spd spd = spdTable.get(item.next());
            //
            // If find one package defined the Ppi GUID
            //
            if ((result = spd.getPpi(name)) != null) {
                return result;
            }
        }
        return null;

    }

    /**
     * return two values: {cName, GuidValue}
     */
    public static String[] getProtocolGuid(List<PackageIdentification> packages,
            String name) throws BuildException {
        if (packages == null) {
            return new String[0];
        }
        String[] result = null;
        Iterator item = packages.iterator();
        while (item.hasNext()){
            Spd spd = spdTable.get(item.next());
            //
            // If find one package defined the protocol GUID
            //
            if ((result = spd.getProtocol(name))!= null){
                return result;
            }
        }
        return null;

    }
    
    public synchronized static PlatformIdentification getPlatformByName(String name) throws BuildException {
        Iterator iter = platformList.iterator();
        while(iter.hasNext()){
            PlatformIdentification platformId = (PlatformIdentification)iter.next();
            if (platformId.getName().equalsIgnoreCase(name)) {
                return platformId;
            }
        }
        throw new BuildException("Can't find platform [" + name + "] in current workspace database. ");
    }
    
    public synchronized static PlatformIdentification getPlatform(String filename) throws BuildException {
        File file = new File(workspaceDir + File.separatorChar + filename);
        Iterator iter = platformList.iterator();
        while(iter.hasNext()){
            PlatformIdentification platformId = (PlatformIdentification)iter.next();
            if (platformId.getFpdFile().getPath().equalsIgnoreCase(file.getPath())) {
                return platformId;
            }
        }
        throw new BuildException("Can't find platform file [" + filename + "] in current workspace database. ");
    }
    
    public synchronized static PackageIdentification refreshPackageIdentification(PackageIdentification packageId) throws BuildException {
        Iterator iter = packageList.iterator();
        while(iter.hasNext()){
            PackageIdentification packageItem = (PackageIdentification)iter.next();
            if (packageItem.equals(packageId)) {
                packageId.setName(packageItem.getName());
                packageId.setSpdFile(packageItem.getSpdFile());
                return packageId;
            }
        }
        throw new BuildException("Can't find package GUID value " + packageId.getGuid() + " under current workspace. ");
    }
    
    public synchronized static ModuleIdentification refreshModuleIdentification(ModuleIdentification moduleId) throws BuildException {
//        System.out.println("1");
//        System.out.println("##" + moduleId.getGuid());
        PackageIdentification packageId = getPackageForModule(moduleId);
//        System.out.println("" + packageId.getGuid());
        moduleId.setPackage(packageId);
        Spd spd = spdTable.get(packageId);
        if (spd == null) {
            throw new BuildException("Can't find package GUID value " + packageId.getGuid() + " under current workspace. ");
        }
        Set<ModuleIdentification> modules = spd.getModules();
        Iterator<ModuleIdentification> iter = modules.iterator();
        while (iter.hasNext()) {
            ModuleIdentification item = iter.next();
            if (item.equals(moduleId)) {
                moduleId.setName(item.getName());
                moduleId.setModuleType(item.getModuleType());
                moduleId.setMsaFile(item.getMsaFile());
                return moduleId;
            }
        }
        throw new BuildException("Can't find module GUID value " + moduleId.getGuid() + " in " + packageId + " under current workspace. ");
    }
    
    public synchronized static Set<PackageIdentification> getPackageList(){
        return packageList;
    }
    ///// remove!!
    private static XmlObject cloneXmlObject(XmlObject object, boolean deep) throws BuildException {
        if ( object == null) {
            return null;
        }
        XmlObject result = null;
        try {
            result = XmlObject.Factory.parse(object.getDomNode()
                            .cloneNode(deep));
        } catch (Exception ex) {
            throw new BuildException(ex.getMessage());
        }
        return result;
    }

    ////// Tool Chain Related, try to refine and put some logic process to ToolChainFactory

    public static ToolChainInfo getToolChainInfo() {
//        GlobalData.log.info(toolsDef.getConfigInfo() + "" + toolChainEnvInfo + toolChainPlatformInfo);
        if (toolChainInfo == null) {
            toolChainInfo = toolsDef.getConfigInfo().intersection(toolChainEnvInfo);
            if (toolChainPlatformInfo != null) {
                toolChainInfo = toolChainInfo.intersection(toolChainPlatformInfo);
            }
            toolChainInfo.addCommands(toolsDef.getConfigInfo().getCommands());
            toolChainInfo.normalize();
            GlobalData.log.info(toolChainInfo + "");
        }
        return toolChainInfo;
    }



    public static void setPlatformToolChainFamilyOption(ToolChainMap map) {
        platformToolChainFamilyOption = map;
    }

    public static void setPlatformToolChainOption(ToolChainMap map) {
        platformToolChainOption = map;
    }

    public static void addModuleToolChainOption(FpdModuleIdentification fpdModuleId,
        ToolChainMap toolChainOption) {
        moduleToolChainOption.put(fpdModuleId, toolChainOption);
    }

    public static void addModuleToolChainFamilyOption(FpdModuleIdentification fpdModuleId,
        ToolChainMap toolChainOption) {
        moduleToolChainFamilyOption.put(fpdModuleId, toolChainOption);
    }

    public static boolean isCommandSet(String target, String toolchain, String arch) {
        String[] commands = getToolChainInfo().getCommands();

        for (int i = 0; i < commands.length; ++i) {
            String cmdName = toolsDef.getConfig().get(new String[] {target, toolchain, arch, commands[i], ToolChainAttribute.NAME.toString()});
            if (cmdName != null && cmdName.length() != 0) {
                return true;
            }
        }

        return false;
    }

    public static String getCommandSetting(String[] commandDescription, FpdModuleIdentification fpdModuleId) throws EdkException {
        ToolChainKey toolChainKey = new ToolChainKey(commandDescription);
        ToolChainMap toolChainConfig = toolsDef.getConfig(); 
        String setting = null;

        if (!commandDescription[ToolChainElement.ATTRIBUTE.value].equals(ToolChainAttribute.FLAGS.toString())) {
            setting = toolChainConfig.get(toolChainKey);
            if (setting == null) {
                setting = "";
            }
            return setting;
        }

        //
        // get module specific options, if any
        //
        // tool tag first
        ToolChainMap option = moduleToolChainOption.get(fpdModuleId);
        ToolChainKey toolChainFamilyKey = null;

        if ((option == null) || (option != null && (setting = option.get(toolChainKey)) == null)) {
            //
            // then tool chain family
            //
            toolChainFamilyKey = new ToolChainKey(commandDescription);
            toolChainFamilyKey.setKey(ToolChainAttribute.FAMILY.toString(), ToolChainElement.ATTRIBUTE.value);
            String family = toolChainConfig.get(toolChainFamilyKey);
            toolChainFamilyKey.setKey(family, ToolChainElement.TOOLCHAIN.value);
            toolChainFamilyKey.setKey(ToolChainAttribute.FLAGS.toString(), ToolChainElement.ATTRIBUTE.value);

            option = moduleToolChainFamilyOption.get(fpdModuleId);
            if (option != null) {                
                setting = option.get(toolChainFamilyKey);
            }
        }

        //
        // get platform options, if any
        //
        if (setting == null) {
            // tool tag first
            if (platformToolChainOption == null || (setting = platformToolChainOption.get(toolChainKey)) == null) {
                // then tool chain family
                if (toolChainFamilyKey == null) {
                    toolChainFamilyKey = new ToolChainKey(commandDescription);
                    toolChainFamilyKey.setKey(ToolChainAttribute.FAMILY.toString(), ToolChainElement.ATTRIBUTE.value);
                    String family = toolChainConfig.get(toolChainFamilyKey);
                    toolChainFamilyKey.setKey(family, ToolChainElement.TOOLCHAIN.value);
                    toolChainFamilyKey.setKey(ToolChainAttribute.FLAGS.toString(), ToolChainElement.ATTRIBUTE.value);
                }

                setting = platformToolChainFamilyOption.get(toolChainFamilyKey);
            }
        }

        if (setting == null) {
            setting = "";
        }

        return setting;
    }
    
    public static void setToolChainEnvInfo(ToolChainInfo envInfo) {
        toolChainEnvInfo = envInfo;
    }
    public static void setToolChainPlatformInfo(ToolChainInfo platformInfo) {
        toolChainPlatformInfo = platformInfo;
    }

    //
    // for PCD
    //
    public synchronized static MemoryDatabaseManager getPCDMemoryDBManager() {
        return pcdDbManager;
    }

    //
    // For PCD get tokenSpaceGUid
    //
    public synchronized static String[] getGuidInfoFromCname(String cName){
        String cNameGuid[] = null;
        String guid = null;
        Set set = spdTable.keySet();
        Iterator iter = set.iterator();

        if (iter == null) {
            return null;
        }

        while (iter.hasNext()){
            Spd spd = (Spd) spdTable.get(iter.next());
            guid = spd.getGuidFromCname(cName);
            if (guid != null){
                cNameGuid = new String[2];
                cNameGuid[0] = cName;
                cNameGuid[1] = guid;
                break;
            }
        }
        return cNameGuid;
    }

    //
    // For PCD
    //
    public synchronized static Map<FpdModuleIdentification, XmlObject> 
                               getFpdModuleSaXmlObject(String xmlObjectName) {
        Set<FpdModuleIdentification> fpdModuleSASet = fpdModuleSA.keySet();
        Iterator item = fpdModuleSASet.iterator();
        

        Map<FpdModuleIdentification, XmlObject> SAPcdBuildDef = new HashMap<FpdModuleIdentification, XmlObject>();
        Map<String, XmlObject> SANode = new HashMap<String, XmlObject>();
        FpdModuleIdentification moduleId;
        while (item.hasNext()) {
            
            moduleId = (FpdModuleIdentification) item.next();
            SANode = fpdModuleSA.get(moduleId);
            try{
                if (SANode.get(xmlObjectName)!= null){
                    SAPcdBuildDef.put(moduleId,
                            (XmlObject) SANode.get(xmlObjectName));

                }
            } catch (Exception e){
                EdkLog.log(EdkLog.EDK_INFO, e.getMessage());
            }
        }
        return SAPcdBuildDef;
    }

    public synchronized static Map<FpdModuleIdentification,XmlObject> getFpdPcdBuildDefinitions() {
        Map<FpdModuleIdentification,XmlObject> pcdBuildDef = getFpdModuleSaXmlObject ("PcdBuildDefinition");

        return pcdBuildDef;
    }
}