Introduce a new property INCLUDE_PATHS. This property can used by customized build...
[mirror_edk2.git] / Tools / Source / GenBuild / org / tianocore / build / ModuleBuildFileGenerator.java
1 /** @file
2
3 Copyright (c) 2006, Intel Corporation
4 All rights reserved. This program and the accompanying materials
5 are licensed and made available under the terms and conditions of the BSD License
6 which accompanies this distribution. The full text of the license may be found at
7 http://opensource.org/licenses/bsd-license.php
8
9 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 **/
12 package org.tianocore.build;
13
14 import java.io.File;
15 import java.util.LinkedHashMap;
16 import java.util.Map;
17 import java.io.FileOutputStream;
18 import java.io.OutputStreamWriter;
19
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.Result;
24 import javax.xml.transform.Source;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.dom.DOMSource;
28 import javax.xml.transform.stream.StreamResult;
29
30 import org.apache.tools.ant.BuildException;
31 import org.apache.tools.ant.Project;
32 import org.tianocore.build.fpd.FpdParserTask;
33 import org.tianocore.build.global.SurfaceAreaQuery;
34 import org.tianocore.build.global.PropertyManager;
35 import org.tianocore.build.id.FpdModuleIdentification;
36 import org.tianocore.build.id.ModuleIdentification;
37 import org.tianocore.build.id.PackageIdentification;
38 import org.w3c.dom.Comment;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Element;
41 import org.w3c.dom.Node;
42
43 public class ModuleBuildFileGenerator {
44
45 ///
46 /// Pass: TARGET, TOOLCHAIN, ARCH
47 /// PACKAGE, PACKAGE_GUID, PACKAGE_VERSION
48 ///
49 String[] inheritProperties = {"ARCH", "MODULE_GUID", "MODULE_VERSION", "PLATFORM_FILE", "PACKAGE_GUID", "PACKAGE_VERSION"};
50
51 ///
52 /// The information at the header of <em>build.xml</em>.
53 ///
54 private String info = "DO NOT EDIT \n"
55 + "This file is auto-generated by the build utility\n"
56 + "\n"
57 + "Abstract:\n"
58 + "Auto-generated ANT build file for build EFI Modules and Platforms\n";
59
60 private FpdModuleIdentification fpdModuleId;
61
62 private Project project;
63
64 private String ffsKeyword;
65
66 private String[] includes;
67
68 public ModuleBuildFileGenerator(Project project, String ffsKeyword, FpdModuleIdentification fpdModuleId, String[] includes) {
69 this.project = project;
70 this.fpdModuleId = fpdModuleId;
71 this.ffsKeyword = ffsKeyword;
72 this.includes = includes;
73 }
74
75 /**
76 The whole BaseName_build.xml is composed of seven part.
77 <ul>
78 <li> ANT properties; </li>
79 <li> Dependent module (dependent library instances in most case); </li>
80 <li> Source files; </li>
81 <li> Sections if module is not library; </li>
82 <li> Output (different for library module and driver module); </li>
83 <li> Clean; </li>
84 <li> Clean all. </li>
85 </ul>
86
87 @throws BuildException
88 Error throws during BaseName_build.xml generating.
89 **/
90 public void genBuildFile(String buildFilename) throws BuildException {
91 FfsProcess fp = new FfsProcess();
92 DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
93 try {
94 DocumentBuilder dombuilder = domfac.newDocumentBuilder();
95 Document document = dombuilder.newDocument();
96 Comment rootComment = document.createComment(info);
97
98 //
99 // create root element and its attributes
100 //
101 Element root = document.createElement("project");
102 root.setAttribute("name", fpdModuleId.getModule().getName());
103 root.setAttribute("default", "all");
104 root.setAttribute("basedir", ".");
105
106 //
107 // element for External ANT tasks
108 //
109 root.appendChild(document.createComment("Apply external ANT tasks"));
110 Element ele = document.createElement("taskdef");
111 ele.setAttribute("resource", "frameworktasks.tasks");
112 root.appendChild(ele);
113 ele = document.createElement("taskdef");
114 ele.setAttribute("resource", "cpptasks.tasks");
115 root.appendChild(ele);
116 ele = document.createElement("typedef");
117 ele.setAttribute("resource", "cpptasks.types");
118 root.appendChild(ele);
119 ele = document.createElement("taskdef");
120 ele.setAttribute("resource", "net/sf/antcontrib/antlib.xml");
121 root.appendChild(ele);
122
123 //
124 // Generate the default target,
125 // which depends on init, sections and output target
126 //
127 root.appendChild(document.createComment("Default target"));
128 ele = document.createElement("target");
129 ele.setAttribute("name", "all");
130 ele.setAttribute("depends", "libraries, sourcefiles, sections, output");
131 root.appendChild(ele);
132
133 //
134 // compile all source files
135 //
136 root.appendChild(document.createComment("Compile all dependency Library instances."));
137 ele = document.createElement("target");
138 ele.setAttribute("name", "libraries");
139
140 //
141 // Parse all sourfiles but files specified in sections
142 //
143 applyLibraryInstance(document, ele);
144 root.appendChild(ele);
145
146 //
147 // compile all source files
148 //
149 root.appendChild(document.createComment("sourcefiles target"));
150 ele = document.createElement("target");
151 ele.setAttribute("name", "sourcefiles");
152
153 //
154 // Parse all sourfiles but files specified in sections
155 //
156 applyCompileElement(document, ele);
157 root.appendChild(ele);
158
159 //
160 // generate the init target
161 // main purpose is create all nessary pathes
162 // generate the sections target
163 //
164 root.appendChild(document.createComment("sections target"));
165 ele = document.createElement("target");
166 ele.setAttribute("name", "sections");
167 applySectionsElement(document, ele, fp);
168 root.appendChild(ele);
169
170 //
171 // generate the output target
172 //
173 root.appendChild(document.createComment("output target"));
174 ele = document.createElement("target");
175 ele.setAttribute("name", "output");
176 applyOutputElement(document, ele, fp);
177 root.appendChild(ele);
178
179
180 //
181 // generate the clean target
182 //
183 root.appendChild(document.createComment("clean target"));
184 ele = document.createElement("target");
185 ele.setAttribute("name", "clean");
186 applyCleanElement(document, ele);
187 root.appendChild(ele);
188
189 //
190 // generate the Clean All target
191 //
192 root.appendChild(document.createComment("Clean All target"));
193 ele = document.createElement("target");
194 ele.setAttribute("name", "cleanall");
195 applyDeepcleanElement(document, ele);
196 root.appendChild(ele);
197
198 //
199 // add the root element to the document
200 //
201 document.appendChild(rootComment);
202 document.appendChild(root);
203 //
204 // Prepare the DOM document for writing
205 //
206 Source source = new DOMSource(document);
207
208 //
209 // Prepare the output file
210 //
211 File file = new File(buildFilename);
212
213 //
214 // generate all directory path
215 //
216 (new File(file.getParent())).mkdirs();
217 FileOutputStream outputStream = new FileOutputStream(file);
218 Result result = new StreamResult(new OutputStreamWriter(outputStream));
219
220 //
221 // Write the DOM document to the file
222 //
223 Transformer xformer = TransformerFactory.newInstance().newTransformer();
224 xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
225 xformer.setOutputProperty(OutputKeys.INDENT, "yes");
226 xformer.transform(source, result);
227 } catch (Exception ex) {
228 throw new BuildException("Generating the module [" + fpdModuleId.getModule().getName() + "] build.xml file failed!.\n" + ex.getMessage());
229 }
230 }
231
232 /**
233 Generate the clean elements for BaseName_build.xml.
234
235 @param document current BaseName_build.xml XML document
236 @param root Root element for current
237 **/
238 private void applyCleanElement(Document document, Node root) {
239 //
240 // <delete includeemptydirs="true">
241 // <fileset dir="${DEST_DIR_OUTPUT}" includes="" excludes="" />
242 // </delete>
243 //
244 Element deleteEle = document.createElement("delete");
245 deleteEle.setAttribute("includeemptydirs", "true");
246 Element filesetEle = document.createElement("fileset");
247 filesetEle.setAttribute("dir", "${DEST_DIR_OUTPUT}");
248 filesetEle.setAttribute("includes", "**/*");
249 filesetEle.setAttribute("excludes", "*.xml");
250 deleteEle.appendChild(filesetEle);
251 root.appendChild(deleteEle);
252 }
253
254 /**
255 Generate the cleanall elements for BaseName_build.xml.
256
257 @param document current BaseName_build.xml XML document
258 @param root Root element for current
259 **/
260 private void applyDeepcleanElement(Document document, Node root) {
261 //
262 // <delete includeemptydirs="true">
263 // <fileset dir="${DEST_DIR_OUTPUT}" includes="" excludes="" />
264 // </delete>
265 //
266 Element deleteEle = document.createElement("delete");
267 deleteEle.setAttribute("includeemptydirs", "true");
268 Element filesetEle = document.createElement("fileset");
269 filesetEle.setAttribute("dir", "${DEST_DIR_OUTPUT}");
270 filesetEle.setAttribute("includes", "**/*");
271 filesetEle.setAttribute("excludes", "*.xml");
272 deleteEle.appendChild(filesetEle);
273 root.appendChild(deleteEle);
274
275 //
276 // <delete includeemptydirs="true">
277 // <fileset dir="${DEST_DIR_DEBUG}" includes="" />
278 // </delete>
279 //
280 deleteEle = document.createElement("delete");
281 deleteEle.setAttribute("includeemptydirs", "true");
282 filesetEle = document.createElement("fileset");
283 filesetEle.setAttribute("dir", "${DEST_DIR_DEBUG}");
284 filesetEle.setAttribute("includes", "**/*");
285 deleteEle.appendChild(filesetEle);
286 root.appendChild(deleteEle);
287 }
288
289 /**
290 Generate the dependent library instances elements for BaseName_build.xml.
291
292 @param document current BaseName_build.xml XML document
293 @param root Root element for current
294 **/
295 private void applyLibraryInstance(Document document, Node root) {
296 ModuleIdentification[] libinstances = SurfaceAreaQuery.getLibraryInstance(fpdModuleId.getArch());
297 for (int i = 0; i < libinstances.length; i++) {
298 //
299 // Put package file path to module identification
300 //
301 PackageIdentification packageId = libinstances[i].getPackage();
302
303 //
304 // Generate ANT script to build library instances
305 //
306 Element ele = document.createElement("GenBuild");
307 ele.setAttribute("type", "build");
308
309 //
310 // Prepare pass down information
311 //
312 Map<String, String> passDownMap = new LinkedHashMap<String, String>();
313 for (int j = 0; j < inheritProperties.length; j ++){
314 passDownMap.put(inheritProperties[j], "${" + inheritProperties[j] + "}");
315 }
316
317 passDownMap.put("MODULE_GUID", libinstances[i].getGuid());
318 passDownMap.put("MODULE_VERSION", libinstances[i].getVersion());
319
320 passDownMap.put("PACKAGE_GUID", packageId.getGuid());
321 passDownMap.put("PACKAGE_VERSION", packageId.getVersion());
322
323 for (int j = 0; j < inheritProperties.length; j ++){
324 Element property = document.createElement("property");
325 property.setAttribute("name", inheritProperties[j]);
326 property.setAttribute("value", passDownMap.get(inheritProperties[j]));
327 ele.appendChild(property);
328 }
329
330 root.appendChild(ele);
331 }
332 }
333
334 /**
335 Generate the build source files elements for BaseName_build.xml.
336
337 @param document current BaseName_build.xml XML document
338 @param root Root element for current
339 **/
340 private void applyCompileElement(Document document, Node root) {
341 //
342 // sourceFiles[][0] is FileType, [][1] is File name relative to Module_Dir
343 //
344 String[][] sourceFiles = SurfaceAreaQuery.getSourceFiles(fpdModuleId.getArch());
345
346 FileProcess fileProcess = new FileProcess();
347 fileProcess.init(project, includes, document);
348
349 //
350 // Initialize some properties by user
351 //
352 Element initEle = document.createElement("Build_Init");
353 root.appendChild(initEle);
354
355 String moduleDir = project.getProperty("MODULE_DIR");
356 //
357 // Parse all Unicode files
358 //
359 for (int i = 0; i < sourceFiles.length; i++) {
360 //
361 // Go through all source files. Add MODULE_DIR to preffix
362 //
363 File sourceFile = new File(moduleDir + File.separatorChar + sourceFiles[i][1]);
364 sourceFiles[i][1] = sourceFile.getPath();
365 String filetype = sourceFiles[i][0];
366 if (filetype != null) {
367 fileProcess.parseFile(sourceFiles[i][1], filetype, root, true);
368 } else {
369 fileProcess.parseFile(sourceFiles[i][1], root, true);
370 }
371 }
372
373 //
374 // If exist Unicode file
375 //
376 if (fileProcess.isUnicodeExist()) {
377 Element ele = document.createElement("Build_Unicode_Database");
378 ele.setAttribute("FILEPATH", ".");
379 ele.setAttribute("FILENAME", "${BASE_NAME}");
380 Element includesEle = document.createElement("EXTRA.INC");
381 for (int i = 0; i < includes.length; i++) {
382 Element includeEle = document.createElement("includepath");
383 includeEle.setAttribute("path", includes[i]);
384 includesEle.appendChild(includeEle);
385 }
386 ele.appendChild(includesEle);
387 root.appendChild(ele);
388 }
389
390 //
391 // Parse AutoGen.c & AutoGen.h
392 //
393 if ( ! fpdModuleId.getModule().getName().equalsIgnoreCase("Shell")) {
394 fileProcess.parseFile(project.getProperty("DEST_DIR_DEBUG") + File.separatorChar + "AutoGen.c", root, false);
395 }
396
397 //
398 // Parse all source files but Unicode files
399 //
400 for (int i = 0; i < sourceFiles.length; i++) {
401 String filetype = sourceFiles[i][0];
402 if (filetype != null) {
403 fileProcess.parseFile(sourceFiles[i][1], filetype, root, false);
404 } else {
405 fileProcess.parseFile(sourceFiles[i][1], root, false);
406 }
407 }
408
409 //
410 // Initialize SOURCE_FILES for dependcy check use
411 //
412 String str = "";
413 for (int i = 0; i < sourceFiles.length; i++) {
414 str += " " + sourceFiles[i][1];
415 }
416 PropertyManager.setProperty(project, "SOURCE_FILES", str.replaceAll("(\\\\)", "/"));
417 }
418
419 /**
420 Generate the section elements for BaseName_build.xml. Library module will
421 skip this process.
422
423 @param document current BaseName_build.xml XML document
424 @param root Root element for current
425 **/
426 private void applySectionsElement(Document document, Node root, FfsProcess fp) {
427 if (fpdModuleId.getModule().isLibrary()) {
428 return ;
429 }
430 if (fp.initSections(ffsKeyword, project, fpdModuleId)) {
431 String targetFilename = fpdModuleId.getModule().getGuid() + "-" + "${BASE_NAME}" + FpdParserTask.getSuffix(fpdModuleId.getModule().getModuleType());
432 String[] list = fp.getGenSectionElements(document, "${BASE_NAME}", fpdModuleId.getModule().getGuid(), targetFilename);
433
434 for (int i = 0; i < list.length; i++) {
435 Element ele = document.createElement(list[i]);
436 ele.setAttribute("FILEPATH", ".");
437 ele.setAttribute("FILENAME", "${BASE_NAME}");
438 root.appendChild(ele);
439 }
440 }
441 }
442
443 /**
444 Generate the output elements for BaseName_build.xml. If module is library,
445 call the <em>LIB</em> command, else call the <em>GenFfs</em> command.
446
447 @param document current BaseName_build.xml XML document
448 @param root Root element for current
449 **/
450 private void applyOutputElement(Document document, Node root, FfsProcess fp) {
451 if (fpdModuleId.getModule().isLibrary()) {
452 //
453 // call Lib command
454 //
455 Element cc = document.createElement("Build_Library");
456 cc.setAttribute("FILENAME", fpdModuleId.getModule().getName());
457 root.appendChild(cc);
458 }
459 //
460 // if it is a module but library
461 //
462 else {
463 if (fp.getFfsNode() != null) {
464 root.appendChild(fp.getFfsNode());
465 }
466 }
467 }
468
469 }