summaryrefslogtreecommitdiff
path: root/Tools/Java/Source/GenBuild/org/tianocore/build/fpd/FpdParserForThread.java
blob: ac930f12571aca0bb4bd925092eefff3c3036893 (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
/** @file
 This file is ANT task FpdParserTask. 
 
 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.fpd;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Ant;
import org.apache.xmlbeans.XmlObject;

import org.tianocore.build.global.GenBuildLogger;
import org.tianocore.build.global.GlobalData;
import org.tianocore.build.global.OutputManager;
import org.tianocore.build.id.FpdModuleIdentification;
import org.tianocore.build.id.ModuleIdentification;
import org.tianocore.build.FrameworkBuildTask;
import org.tianocore.build.GenBuildThread;
import org.tianocore.common.exception.EdkException;
import org.tianocore.common.logger.EdkLog;

/**

  @since GenBuild 1.0
**/
public class FpdParserForThread extends FpdParserTask {
    
    public static Map<FpdModuleIdentification, GenBuildThread> allThreads = new LinkedHashMap<FpdModuleIdentification, GenBuildThread>();
    
    List<String> queueList = new ArrayList<String>();
    
    public final static Object deamonSemaphore =  new Object();
    
    private final static Object countSemaphore =  new Object();
    
    public static int STATUS_DEPENDENCY_NOT_READY = 1;
    
    public static int STATUS_DEPENDENCY_READY = 2;
    
    public static int STATUS_START_RUN = 3;
    
    public static int STATUS_END_RUN = 4;
    
    private int currentQueueCode = 0;
    
    public static int currentRunNumber = 0;
    
    public static int totalNumber = 0;
    
    public static int remainNumber = 0;
    
    public static ThreadGroup tg = new ThreadGroup("Framework");
    
    public static FpdModuleIdentification errorModule = null;
    
    /**
      Public construct method. It is necessary for ANT task.
    **/
    public FpdParserForThread() {
    }

    /**
     

    **/
    public void execute() throws BuildException {
        
        this.setTaskName(".........");
        //
        // Parse FPD file
        //
        parseFpdFile();

        //
        // Prepare BUILD_DIR
        //
        isUnified = OutputManager.getInstance().prepareBuildDir(getProject());
        String buildDir = getProject().getProperty("BUILD_DIR");
        
        //
        // For every Target and ToolChain
        //
        String[] targetList = GlobalData.getToolChainInfo().getTargets();
        for (int i = 0; i < targetList.length; i++) {
            String[] toolchainList = GlobalData.getToolChainInfo().getTagnames();
            for(int j = 0; j < toolchainList.length; j++) {
                //
                // Prepare FV_DIR
                //
                String ffsCommonDir = buildDir + File.separatorChar
                                + targetList[i] + "_"
                                + toolchainList[j];
                File fvDir = new File(ffsCommonDir + File.separatorChar + "FV");
                fvDir.mkdirs();
                getProject().setProperty("FV_DIR", fvDir.getPath().replaceAll("(\\\\)", "/"));

                //
                // Gen Fv.inf files
                //
                genFvInfFiles(ffsCommonDir);
            }
        }

        //
        // Gen build.xml
        //
        String platformBuildFile = buildDir + File.separatorChar + platformId.getName() + "_build.xml";
        PlatformBuildFileGenerator fileGenerator = new PlatformBuildFileGenerator(getProject(), outfiles, fvs, isUnified, saq, platformBuildFile, aprioriType);
        fileGenerator.genBuildFile();
        
        //
        // Prepare Queue
        //
        queueList.add("libqueue");
        
        String[] validFv = saq.getFpdValidImageNames();
        
        for (int i = 0; i < validFv.length; i++) {
            queueList.add(validFv[i]);
        }
        
        Iterator<String> fvsNameIter = fvs.keySet().iterator();
        
        while (fvsNameIter.hasNext()) {
            String fvName = fvsNameIter.next();
            if (!isContain(validFv, fvName)) {
                queueList.add(fvName);
            }
        }
        
        //
        // Ant call ${PLATFORM}_build.xml
        //
        Ant ant = new Ant();
        ant.setProject(getProject());
        ant.setAntfile(platformBuildFile);
        ant.setTarget("prebuild");
        ant.setInheritAll(true);
        ant.init();
        ant.execute();
        
        remainNumber = totalNumber = allThreads.size();
        
        EdkLog.log(this, EdkLog.EDK_ALWAYS, "Total thread number is " + totalNumber);
        GenBuildLogger.setCacheEnable(true);
        //
        // Waiting for all thread over, or time out
        //
        synchronized (deamonSemaphore) {

            while (true) {
                //
                // If all modules are already built
                //
                if (currentQueueCode >= queueList.size()) {
                    break ;
                }
                
                int percentage = (totalNumber - remainNumber) * 100 / totalNumber;
                updateTaskName(percentage);
                EdkLog.log(this, EdkLog.EDK_ALWAYS, percentage + "% finished. Has built " + (totalNumber - remainNumber) + " modules of " + totalNumber + " total. ");

                Set<FpdModuleIdentification> currentQueueModules = fvs.get(queueList.get(currentQueueCode));
                
                if (currentQueueModules == null) {
                    ++currentQueueCode;
                    continue ;
                }
                Iterator<FpdModuleIdentification> currentIter = currentQueueModules.iterator();

                GenBuildThread a = null;

                boolean existNoneReady = false;

                while (currentIter.hasNext()) {
                    GenBuildThread item = allThreads.get(currentIter.next()); 
                    if (item.getStatus() == STATUS_DEPENDENCY_NOT_READY) {
                        existNoneReady = true;
                    } else if (item.getStatus() == STATUS_DEPENDENCY_READY) {
                        a = item;
                        addCount();
                        a.start();
                        if (currentRunNumber == FrameworkBuildTask.MAX_CONCURRENT_THREAD_NUMBER) {
                            break ;
                        }
                    }
                }

                if (a != null) {
                    //
                    // Exist ready thread
                    //
                    EdkLog.log(this, EdkLog.EDK_DEBUG, "Exist ready thread");

                } else if (existNoneReady && currentRunNumber == 0) {
                    //
                    // No active thread, but still have dependency not read thread
                    //
                    throw new BuildException("Existing some modules can't resolve depedencies. ");
                } else if (!existNoneReady && currentRunNumber == 0) {
                    //
                    // Current queue build finish, move to next
                    //
                    EdkLog.log(this, EdkLog.EDK_DEBUG, "Current queue build finish, move to next");
                    ++currentQueueCode;
                    continue ;
                } else {
                    //
                    // active thread exist, but no ready thread
                    //
                    EdkLog.log(this, EdkLog.EDK_DEBUG, "Active thread exist, but no ready thread. Current running number is " + currentRunNumber);
                }

                try {
                    deamonSemaphore.wait();
                    
                    //
                    // if find error. Waiting running threads to finish
                    //
                    if (errorModule != null) {
                        while (currentRunNumber > 0) {
                            deamonSemaphore.wait();
                        }
                        
                        GenBuildLogger.setCacheEnable(false);
                        
                        GenBuildLogger.flushErrorModuleLog(errorModule);
                        
                        EdkLog.flushLogToFile(new File(buildDir + File.separatorChar + "build.log"));
                        
                        throw new BuildException(errorModule + " build error. ");
                    }
                } catch (InterruptedException ex) {
                    BuildException e = new BuildException("Thread wait Error. \n" + ex.getMessage());
                    e.setStackTrace(ex.getStackTrace());
                    throw e;
                }
            }
        }
        
        GenBuildLogger.setCacheEnable(false);
        //
        // call fvs, postbuild
        //
        ant = new Ant();
        ant.setProject(getProject());
        ant.setAntfile(platformBuildFile);
        ant.setTarget("fvs");
        ant.setInheritAll(true);
        ant.init();
        ant.execute();
        
        ant = new Ant();
        ant.setProject(getProject());
        ant.setAntfile(platformBuildFile);
        ant.setTarget("postbuild");
        ant.setInheritAll(true);
        ant.init();
        ant.execute();
        
        EdkLog.flushLogToFile(new File(buildDir + File.separatorChar + "build.log"));
    }

    
    /**
      Parse all modules listed in FPD file. 
    **/
    void parseModuleSAFiles() throws EdkException{
        
        Map<FpdModuleIdentification, Map<String, XmlObject>> moduleSAs = saq.getFpdModules();

        //
        // For every Module lists in FPD file.
        //
        Set<FpdModuleIdentification> keys = moduleSAs.keySet();
        Iterator<FpdModuleIdentification> iter = keys.iterator();
        while (iter.hasNext()) {
            FpdModuleIdentification fpdModuleId = iter.next();
            
            //
            // Generate GenBuildThread
            //
            GenBuildThread genBuildThread = new GenBuildThread(fpdModuleId.getModule(), fpdModuleId.getArch());
            genBuildThread.setParentModuleId(null);
            genBuildThread.setProject(getProject());
            
            Set<FpdModuleIdentification> dependencies = new LinkedHashSet<FpdModuleIdentification>();
            
            GlobalData.registerFpdModuleSA(fpdModuleId, moduleSAs.get(fpdModuleId));
            
            //
            // Add all dependent Library Instance
            //
            saq.push(GlobalData.getDoc(fpdModuleId));

            ModuleIdentification[] libinstances = saq.getLibraryInstance(fpdModuleId.getArch());
            saq.pop();
            
            for (int i = 0; i < libinstances.length; i++) {
                FpdModuleIdentification libFpdModuleId = new FpdModuleIdentification(libinstances[i], fpdModuleId.getArch());
                //
                // Add to dependencies
                //
                dependencies.add(libFpdModuleId);
                
                //
                // Create thread for library instances
                //
                GenBuildThread liBuildThread = new GenBuildThread(libinstances[i], fpdModuleId.getArch());
                liBuildThread.setParentModuleId(fpdModuleId.getModule());
                liBuildThread.setProject(getProject());
                liBuildThread.setStatus(STATUS_DEPENDENCY_READY);
                liBuildThread.setHighPriority(true);
                allThreads.put(libFpdModuleId, liBuildThread);
                
                updateFvs("libqueue", libFpdModuleId);
                
                saq.push(GlobalData.getDoc(libinstances[i], fpdModuleId.getArch()));
                GlobalData.addMsaBuildOption(libinstances[i], parseMsaBuildOptions(false));
                GlobalData.addMsaFamilyBuildOption(libinstances[i], parseMsaBuildOptions(true));
                saq.pop();
            }
            
            genBuildThread.setDependencies(dependencies);
            
//            if (dependencies.size() == 0) {
                genBuildThread.setStatus(STATUS_DEPENDENCY_READY);
//            }
            
            allThreads.put(fpdModuleId, genBuildThread);
            
            //
            // Put fpdModuleId to the corresponding FV
            //
            saq.push(GlobalData.getDoc(fpdModuleId));
            String fvBinding = saq.getModuleFvBindingKeyword();

            fpdModuleId.setFvBinding(fvBinding);
            updateFvs(fvBinding, fpdModuleId);

            //
            // Prepare for out put file name
            //
            ModuleIdentification moduleId = fpdModuleId.getModule();

            String baseName = saq.getModuleOutputFileBasename();
            
            if (baseName == null) {
                baseName = moduleId.getName();
            }
            outfiles.put(fpdModuleId, fpdModuleId.getArch() + File.separatorChar
                         + moduleId.getGuid() + "-" + baseName
                         + getSuffix(moduleId.getModuleType()));

            //
            // parse module build options, if any
            //
            GlobalData.addModuleToolChainOption(fpdModuleId, parseModuleBuildOptions(false));
            GlobalData.addModuleToolChainFamilyOption(fpdModuleId, parseModuleBuildOptions(true));
            
            //
            // parse MSA build options
            //
            GlobalData.addMsaBuildOption(moduleId, parseMsaBuildOptions(false));
            GlobalData.addMsaFamilyBuildOption(moduleId, parseMsaBuildOptions(true));

            saq.pop();
        }
    }
    
    private boolean isContain(String[] list, String item) {
        for (int i = 0; i < list.length; i++) {
            if (list[i].equalsIgnoreCase(item)) {
                return true;
            }
        }
        return false;
    }
    
    public synchronized static void addCount() {
        synchronized (countSemaphore) {
            ++currentRunNumber;
        }
    }
    
    public synchronized static void subCount() {
        synchronized (countSemaphore) {
            --currentRunNumber;
            --remainNumber;
        }
    }
    
    private void updateTaskName(int percentage){
        int number = percentage/10;
        StringBuffer str = new StringBuffer(9);
        for(int i = 0; i < 9; i++) {
            if (i < number) {
                str.append('>');
            } else {
                str.append('.');
            }
        }
        this.setTaskName(str.toString());
    }
}