]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/build/build.py
BaseTools: Add support to merge Prebuild and Postbuild into build Process
[mirror_edk2.git] / BaseTools / Source / Python / build / build.py
1 ## @file
2 # build a platform or a module
3 #
4 # Copyright (c) 2014, Hewlett-Packard Development Company, L.P.<BR>
5 # Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
6 #
7 # This program and the accompanying materials
8 # are licensed and made available under the terms and conditions of the BSD License
9 # which accompanies this distribution. The full text of the license may be found at
10 # http://opensource.org/licenses/bsd-license.php
11 #
12 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14 #
15
16 ##
17 # Import Modules
18 #
19 import Common.LongFilePathOs as os
20 import re
21 import StringIO
22 import sys
23 import glob
24 import time
25 import platform
26 import traceback
27 import encodings.ascii
28 import itertools
29
30 from struct import *
31 from threading import *
32 from optparse import OptionParser
33 from subprocess import *
34 from Common import Misc as Utils
35
36 from Common.LongFilePathSupport import OpenLongFilePath as open
37 from Common.LongFilePathSupport import LongFilePath
38 from Common.TargetTxtClassObject import *
39 from Common.ToolDefClassObject import *
40 from Common.DataType import *
41 from Common.BuildVersion import gBUILD_VERSION
42 from AutoGen.AutoGen import *
43 from Common.BuildToolError import *
44 from Workspace.WorkspaceDatabase import *
45 from Common.MultipleWorkspace import MultipleWorkspace as mws
46
47 from BuildReport import BuildReport
48 from GenPatchPcdTable.GenPatchPcdTable import *
49 from PatchPcdValue.PatchPcdValue import *
50
51 import Common.EdkLogger
52 import Common.GlobalData as GlobalData
53
54 # Version and Copyright
55 VersionNumber = "0.60" + ' ' + gBUILD_VERSION
56 __version__ = "%prog Version " + VersionNumber
57 __copyright__ = "Copyright (c) 2007 - 2016, Intel Corporation All rights reserved."
58
59 ## standard targets of build command
60 gSupportedTarget = ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run']
61
62 ## build configuration file
63 gBuildConfiguration = "target.txt"
64 gToolsDefinition = "tools_def.txt"
65
66 TemporaryTablePattern = re.compile(r'^_\d+_\d+_[a-fA-F0-9]+$')
67 TmpTableDict = {}
68
69 ## Check environment PATH variable to make sure the specified tool is found
70 #
71 # If the tool is found in the PATH, then True is returned
72 # Otherwise, False is returned
73 #
74 def IsToolInPath(tool):
75 if os.environ.has_key('PATHEXT'):
76 extns = os.environ['PATHEXT'].split(os.path.pathsep)
77 else:
78 extns = ('',)
79 for pathDir in os.environ['PATH'].split(os.path.pathsep):
80 for ext in extns:
81 if os.path.exists(os.path.join(pathDir, tool + ext)):
82 return True
83 return False
84
85 ## Check environment variables
86 #
87 # Check environment variables that must be set for build. Currently they are
88 #
89 # WORKSPACE The directory all packages/platforms start from
90 # EDK_TOOLS_PATH The directory contains all tools needed by the build
91 # PATH $(EDK_TOOLS_PATH)/Bin/<sys> must be set in PATH
92 #
93 # If any of above environment variable is not set or has error, the build
94 # will be broken.
95 #
96 def CheckEnvVariable():
97 # check WORKSPACE
98 if "WORKSPACE" not in os.environ:
99 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",
100 ExtraData="WORKSPACE")
101
102 WorkspaceDir = os.path.normcase(os.path.normpath(os.environ["WORKSPACE"]))
103 if not os.path.exists(WorkspaceDir):
104 EdkLogger.error("build", FILE_NOT_FOUND, "WORKSPACE doesn't exist", ExtraData="%s" % WorkspaceDir)
105 elif ' ' in WorkspaceDir:
106 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in WORKSPACE path",
107 ExtraData=WorkspaceDir)
108 os.environ["WORKSPACE"] = WorkspaceDir
109
110 # set multiple workspace
111 PackagesPath = os.getenv("PACKAGES_PATH")
112 mws.setWs(WorkspaceDir, PackagesPath)
113
114 #
115 # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP
116 #
117 if "ECP_SOURCE" not in os.environ:
118 os.environ["ECP_SOURCE"] = mws.join(WorkspaceDir, GlobalData.gEdkCompatibilityPkg)
119 if "EFI_SOURCE" not in os.environ:
120 os.environ["EFI_SOURCE"] = os.environ["ECP_SOURCE"]
121 if "EDK_SOURCE" not in os.environ:
122 os.environ["EDK_SOURCE"] = os.environ["ECP_SOURCE"]
123
124 #
125 # Unify case of characters on case-insensitive systems
126 #
127 EfiSourceDir = os.path.normcase(os.path.normpath(os.environ["EFI_SOURCE"]))
128 EdkSourceDir = os.path.normcase(os.path.normpath(os.environ["EDK_SOURCE"]))
129 EcpSourceDir = os.path.normcase(os.path.normpath(os.environ["ECP_SOURCE"]))
130
131 os.environ["EFI_SOURCE"] = EfiSourceDir
132 os.environ["EDK_SOURCE"] = EdkSourceDir
133 os.environ["ECP_SOURCE"] = EcpSourceDir
134 os.environ["EDK_TOOLS_PATH"] = os.path.normcase(os.environ["EDK_TOOLS_PATH"])
135
136 if not os.path.exists(EcpSourceDir):
137 EdkLogger.verbose("ECP_SOURCE = %s doesn't exist. Edk modules could not be built." % EcpSourceDir)
138 elif ' ' in EcpSourceDir:
139 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in ECP_SOURCE path",
140 ExtraData=EcpSourceDir)
141 if not os.path.exists(EdkSourceDir):
142 if EdkSourceDir == EcpSourceDir:
143 EdkLogger.verbose("EDK_SOURCE = %s doesn't exist. Edk modules could not be built." % EdkSourceDir)
144 else:
145 EdkLogger.error("build", PARAMETER_INVALID, "EDK_SOURCE does not exist",
146 ExtraData=EdkSourceDir)
147 elif ' ' in EdkSourceDir:
148 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in EDK_SOURCE path",
149 ExtraData=EdkSourceDir)
150 if not os.path.exists(EfiSourceDir):
151 if EfiSourceDir == EcpSourceDir:
152 EdkLogger.verbose("EFI_SOURCE = %s doesn't exist. Edk modules could not be built." % EfiSourceDir)
153 else:
154 EdkLogger.error("build", PARAMETER_INVALID, "EFI_SOURCE does not exist",
155 ExtraData=EfiSourceDir)
156 elif ' ' in EfiSourceDir:
157 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in EFI_SOURCE path",
158 ExtraData=EfiSourceDir)
159
160 # check those variables on single workspace case
161 if not PackagesPath:
162 # change absolute path to relative path to WORKSPACE
163 if EfiSourceDir.upper().find(WorkspaceDir.upper()) != 0:
164 EdkLogger.error("build", PARAMETER_INVALID, "EFI_SOURCE is not under WORKSPACE",
165 ExtraData="WORKSPACE = %s\n EFI_SOURCE = %s" % (WorkspaceDir, EfiSourceDir))
166 if EdkSourceDir.upper().find(WorkspaceDir.upper()) != 0:
167 EdkLogger.error("build", PARAMETER_INVALID, "EDK_SOURCE is not under WORKSPACE",
168 ExtraData="WORKSPACE = %s\n EDK_SOURCE = %s" % (WorkspaceDir, EdkSourceDir))
169 if EcpSourceDir.upper().find(WorkspaceDir.upper()) != 0:
170 EdkLogger.error("build", PARAMETER_INVALID, "ECP_SOURCE is not under WORKSPACE",
171 ExtraData="WORKSPACE = %s\n ECP_SOURCE = %s" % (WorkspaceDir, EcpSourceDir))
172
173 # check EDK_TOOLS_PATH
174 if "EDK_TOOLS_PATH" not in os.environ:
175 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",
176 ExtraData="EDK_TOOLS_PATH")
177
178 # check PATH
179 if "PATH" not in os.environ:
180 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",
181 ExtraData="PATH")
182
183 GlobalData.gWorkspace = WorkspaceDir
184 GlobalData.gEfiSource = EfiSourceDir
185 GlobalData.gEdkSource = EdkSourceDir
186 GlobalData.gEcpSource = EcpSourceDir
187
188 GlobalData.gGlobalDefines["WORKSPACE"] = WorkspaceDir
189 GlobalData.gGlobalDefines["EFI_SOURCE"] = EfiSourceDir
190 GlobalData.gGlobalDefines["EDK_SOURCE"] = EdkSourceDir
191 GlobalData.gGlobalDefines["ECP_SOURCE"] = EcpSourceDir
192 GlobalData.gGlobalDefines["EDK_TOOLS_PATH"] = os.environ["EDK_TOOLS_PATH"]
193
194 ## Get normalized file path
195 #
196 # Convert the path to be local format, and remove the WORKSPACE path at the
197 # beginning if the file path is given in full path.
198 #
199 # @param FilePath File path to be normalized
200 # @param Workspace Workspace path which the FilePath will be checked against
201 #
202 # @retval string The normalized file path
203 #
204 def NormFile(FilePath, Workspace):
205 # check if the path is absolute or relative
206 if os.path.isabs(FilePath):
207 FileFullPath = os.path.normpath(FilePath)
208 else:
209 FileFullPath = os.path.normpath(mws.join(Workspace, FilePath))
210 Workspace = mws.getWs(Workspace, FilePath)
211
212 # check if the file path exists or not
213 if not os.path.isfile(FileFullPath):
214 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData="\t%s (Please give file in absolute path or relative to WORKSPACE)" % FileFullPath)
215
216 # remove workspace directory from the beginning part of the file path
217 if Workspace[-1] in ["\\", "/"]:
218 return FileFullPath[len(Workspace):]
219 else:
220 return FileFullPath[(len(Workspace) + 1):]
221
222 ## Get the output of an external program
223 #
224 # This is the entrance method of thread reading output of an external program and
225 # putting them in STDOUT/STDERR of current program.
226 #
227 # @param From The stream message read from
228 # @param To The stream message put on
229 # @param ExitFlag The flag used to indicate stopping reading
230 #
231 def ReadMessage(From, To, ExitFlag):
232 while True:
233 # read one line a time
234 Line = From.readline()
235 # empty string means "end"
236 if Line != None and Line != "":
237 To(Line.rstrip())
238 else:
239 break
240 if ExitFlag.isSet():
241 break
242
243 ## Launch an external program
244 #
245 # This method will call subprocess.Popen to execute an external program with
246 # given options in specified directory. Because of the dead-lock issue during
247 # redirecting output of the external program, threads are used to to do the
248 # redirection work.
249 #
250 # @param Command A list or string containing the call of the program
251 # @param WorkingDir The directory in which the program will be running
252 #
253 def LaunchCommand(Command, WorkingDir):
254 # if working directory doesn't exist, Popen() will raise an exception
255 if not os.path.isdir(WorkingDir):
256 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=WorkingDir)
257
258 # Command is used as the first Argument in following Popen().
259 # It could be a string or sequence. We find that if command is a string in following Popen(),
260 # ubuntu may fail with an error message that the command is not found.
261 # So here we may need convert command from string to list instance.
262 if not isinstance(Command, list):
263 if platform.system() != 'Windows':
264 Command = Command.split()
265
266 Proc = None
267 EndOfProcedure = None
268 try:
269 # launch the command
270 Proc = Popen(Command, stdout=PIPE, stderr=PIPE, env=os.environ, cwd=WorkingDir, bufsize=-1)
271
272 # launch two threads to read the STDOUT and STDERR
273 EndOfProcedure = Event()
274 EndOfProcedure.clear()
275 if Proc.stdout:
276 StdOutThread = Thread(target=ReadMessage, args=(Proc.stdout, EdkLogger.info, EndOfProcedure))
277 StdOutThread.setName("STDOUT-Redirector")
278 StdOutThread.setDaemon(False)
279 StdOutThread.start()
280
281 if Proc.stderr:
282 StdErrThread = Thread(target=ReadMessage, args=(Proc.stderr, EdkLogger.quiet, EndOfProcedure))
283 StdErrThread.setName("STDERR-Redirector")
284 StdErrThread.setDaemon(False)
285 StdErrThread.start()
286
287 # waiting for program exit
288 Proc.wait()
289 except: # in case of aborting
290 # terminate the threads redirecting the program output
291 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
292 if EndOfProcedure != None:
293 EndOfProcedure.set()
294 if Proc == None:
295 if type(Command) != type(""):
296 Command = " ".join(Command)
297 EdkLogger.error("build", COMMAND_FAILURE, "Failed to start command", ExtraData="%s [%s]" % (Command, WorkingDir))
298
299 if Proc.stdout:
300 StdOutThread.join()
301 if Proc.stderr:
302 StdErrThread.join()
303
304 # check the return code of the program
305 if Proc.returncode != 0:
306 if type(Command) != type(""):
307 Command = " ".join(Command)
308 # print out the Response file and its content when make failure
309 RespFile = os.path.join(WorkingDir, 'OUTPUT', 'respfilelist.txt')
310 if os.path.isfile(RespFile):
311 f = open(RespFile)
312 RespContent = f.read()
313 f.close()
314 EdkLogger.info(RespContent)
315
316 EdkLogger.error("build", COMMAND_FAILURE, ExtraData="%s [%s]" % (Command, WorkingDir))
317
318 ## The smallest unit that can be built in multi-thread build mode
319 #
320 # This is the base class of build unit. The "Obj" parameter must provide
321 # __str__(), __eq__() and __hash__() methods. Otherwise there could be build units
322 # missing build.
323 #
324 # Currently the "Obj" should be only ModuleAutoGen or PlatformAutoGen objects.
325 #
326 class BuildUnit:
327 ## The constructor
328 #
329 # @param self The object pointer
330 # @param Obj The object the build is working on
331 # @param Target The build target name, one of gSupportedTarget
332 # @param Dependency The BuildUnit(s) which must be completed in advance
333 # @param WorkingDir The directory build command starts in
334 #
335 def __init__(self, Obj, BuildCommand, Target, Dependency, WorkingDir="."):
336 self.BuildObject = Obj
337 self.Dependency = Dependency
338 self.WorkingDir = WorkingDir
339 self.Target = Target
340 self.BuildCommand = BuildCommand
341 if not BuildCommand:
342 EdkLogger.error("build", OPTION_MISSING,
343 "No build command found for this module. "
344 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
345 (Obj.BuildTarget, Obj.ToolChain, Obj.Arch),
346 ExtraData=str(Obj))
347
348
349 ## str() method
350 #
351 # It just returns the string representation of self.BuildObject
352 #
353 # @param self The object pointer
354 #
355 def __str__(self):
356 return str(self.BuildObject)
357
358 ## "==" operator method
359 #
360 # It just compares self.BuildObject with "Other". So self.BuildObject must
361 # provide its own __eq__() method.
362 #
363 # @param self The object pointer
364 # @param Other The other BuildUnit object compared to
365 #
366 def __eq__(self, Other):
367 return Other != None and self.BuildObject == Other.BuildObject \
368 and self.BuildObject.Arch == Other.BuildObject.Arch
369
370 ## hash() method
371 #
372 # It just returns the hash value of self.BuildObject which must be hashable.
373 #
374 # @param self The object pointer
375 #
376 def __hash__(self):
377 return hash(self.BuildObject) + hash(self.BuildObject.Arch)
378
379 def __repr__(self):
380 return repr(self.BuildObject)
381
382 ## The smallest module unit that can be built by nmake/make command in multi-thread build mode
383 #
384 # This class is for module build by nmake/make build system. The "Obj" parameter
385 # must provide __str__(), __eq__() and __hash__() methods. Otherwise there could
386 # be make units missing build.
387 #
388 # Currently the "Obj" should be only ModuleAutoGen object.
389 #
390 class ModuleMakeUnit(BuildUnit):
391 ## The constructor
392 #
393 # @param self The object pointer
394 # @param Obj The ModuleAutoGen object the build is working on
395 # @param Target The build target name, one of gSupportedTarget
396 #
397 def __init__(self, Obj, Target):
398 Dependency = [ModuleMakeUnit(La, Target) for La in Obj.LibraryAutoGenList]
399 BuildUnit.__init__(self, Obj, Obj.BuildCommand, Target, Dependency, Obj.MakeFileDir)
400 if Target in [None, "", "all"]:
401 self.Target = "tbuild"
402
403 ## The smallest platform unit that can be built by nmake/make command in multi-thread build mode
404 #
405 # This class is for platform build by nmake/make build system. The "Obj" parameter
406 # must provide __str__(), __eq__() and __hash__() methods. Otherwise there could
407 # be make units missing build.
408 #
409 # Currently the "Obj" should be only PlatformAutoGen object.
410 #
411 class PlatformMakeUnit(BuildUnit):
412 ## The constructor
413 #
414 # @param self The object pointer
415 # @param Obj The PlatformAutoGen object the build is working on
416 # @param Target The build target name, one of gSupportedTarget
417 #
418 def __init__(self, Obj, Target):
419 Dependency = [ModuleMakeUnit(Lib, Target) for Lib in self.BuildObject.LibraryAutoGenList]
420 Dependency.extend([ModuleMakeUnit(Mod, Target) for Mod in self.BuildObject.ModuleAutoGenList])
421 BuildUnit.__init__(self, Obj, Obj.BuildCommand, Target, Dependency, Obj.MakeFileDir)
422
423 ## The class representing the task of a module build or platform build
424 #
425 # This class manages the build tasks in multi-thread build mode. Its jobs include
426 # scheduling thread running, catching thread error, monitor the thread status, etc.
427 #
428 class BuildTask:
429 # queue for tasks waiting for schedule
430 _PendingQueue = sdict()
431 _PendingQueueLock = threading.Lock()
432
433 # queue for tasks ready for running
434 _ReadyQueue = sdict()
435 _ReadyQueueLock = threading.Lock()
436
437 # queue for run tasks
438 _RunningQueue = sdict()
439 _RunningQueueLock = threading.Lock()
440
441 # queue containing all build tasks, in case duplicate build
442 _TaskQueue = sdict()
443
444 # flag indicating error occurs in a running thread
445 _ErrorFlag = threading.Event()
446 _ErrorFlag.clear()
447 _ErrorMessage = ""
448
449 # BoundedSemaphore object used to control the number of running threads
450 _Thread = None
451
452 # flag indicating if the scheduler is started or not
453 _SchedulerStopped = threading.Event()
454 _SchedulerStopped.set()
455
456 ## Start the task scheduler thread
457 #
458 # @param MaxThreadNumber The maximum thread number
459 # @param ExitFlag Flag used to end the scheduler
460 #
461 @staticmethod
462 def StartScheduler(MaxThreadNumber, ExitFlag):
463 SchedulerThread = Thread(target=BuildTask.Scheduler, args=(MaxThreadNumber, ExitFlag))
464 SchedulerThread.setName("Build-Task-Scheduler")
465 SchedulerThread.setDaemon(False)
466 SchedulerThread.start()
467 # wait for the scheduler to be started, especially useful in Linux
468 while not BuildTask.IsOnGoing():
469 time.sleep(0.01)
470
471 ## Scheduler method
472 #
473 # @param MaxThreadNumber The maximum thread number
474 # @param ExitFlag Flag used to end the scheduler
475 #
476 @staticmethod
477 def Scheduler(MaxThreadNumber, ExitFlag):
478 BuildTask._SchedulerStopped.clear()
479 try:
480 # use BoundedSemaphore to control the maximum running threads
481 BuildTask._Thread = BoundedSemaphore(MaxThreadNumber)
482 #
483 # scheduling loop, which will exits when no pending/ready task and
484 # indicated to do so, or there's error in running thread
485 #
486 while (len(BuildTask._PendingQueue) > 0 or len(BuildTask._ReadyQueue) > 0 \
487 or not ExitFlag.isSet()) and not BuildTask._ErrorFlag.isSet():
488 EdkLogger.debug(EdkLogger.DEBUG_8, "Pending Queue (%d), Ready Queue (%d)"
489 % (len(BuildTask._PendingQueue), len(BuildTask._ReadyQueue)))
490
491 # get all pending tasks
492 BuildTask._PendingQueueLock.acquire()
493 BuildObjectList = BuildTask._PendingQueue.keys()
494 #
495 # check if their dependency is resolved, and if true, move them
496 # into ready queue
497 #
498 for BuildObject in BuildObjectList:
499 Bt = BuildTask._PendingQueue[BuildObject]
500 if Bt.IsReady():
501 BuildTask._ReadyQueue[BuildObject] = BuildTask._PendingQueue.pop(BuildObject)
502 BuildTask._PendingQueueLock.release()
503
504 # launch build thread until the maximum number of threads is reached
505 while not BuildTask._ErrorFlag.isSet():
506 # empty ready queue, do nothing further
507 if len(BuildTask._ReadyQueue) == 0:
508 break
509
510 # wait for active thread(s) exit
511 BuildTask._Thread.acquire(True)
512
513 # start a new build thread
514 Bo = BuildTask._ReadyQueue.keys()[0]
515 Bt = BuildTask._ReadyQueue.pop(Bo)
516
517 # move into running queue
518 BuildTask._RunningQueueLock.acquire()
519 BuildTask._RunningQueue[Bo] = Bt
520 BuildTask._RunningQueueLock.release()
521
522 Bt.Start()
523 # avoid tense loop
524 time.sleep(0.01)
525
526 # avoid tense loop
527 time.sleep(0.01)
528
529 # wait for all running threads exit
530 if BuildTask._ErrorFlag.isSet():
531 EdkLogger.quiet("\nWaiting for all build threads exit...")
532 # while not BuildTask._ErrorFlag.isSet() and \
533 while len(BuildTask._RunningQueue) > 0:
534 EdkLogger.verbose("Waiting for thread ending...(%d)" % len(BuildTask._RunningQueue))
535 EdkLogger.debug(EdkLogger.DEBUG_8, "Threads [%s]" % ", ".join([Th.getName() for Th in threading.enumerate()]))
536 # avoid tense loop
537 time.sleep(0.1)
538 except BaseException, X:
539 #
540 # TRICK: hide the output of threads left runing, so that the user can
541 # catch the error message easily
542 #
543 EdkLogger.SetLevel(EdkLogger.ERROR)
544 BuildTask._ErrorFlag.set()
545 BuildTask._ErrorMessage = "build thread scheduler error\n\t%s" % str(X)
546
547 BuildTask._PendingQueue.clear()
548 BuildTask._ReadyQueue.clear()
549 BuildTask._RunningQueue.clear()
550 BuildTask._TaskQueue.clear()
551 BuildTask._SchedulerStopped.set()
552
553 ## Wait for all running method exit
554 #
555 @staticmethod
556 def WaitForComplete():
557 BuildTask._SchedulerStopped.wait()
558
559 ## Check if the scheduler is running or not
560 #
561 @staticmethod
562 def IsOnGoing():
563 return not BuildTask._SchedulerStopped.isSet()
564
565 ## Abort the build
566 @staticmethod
567 def Abort():
568 if BuildTask.IsOnGoing():
569 BuildTask._ErrorFlag.set()
570 BuildTask.WaitForComplete()
571
572 ## Check if there's error in running thread
573 #
574 # Since the main thread cannot catch exceptions in other thread, we have to
575 # use threading.Event to communicate this formation to main thread.
576 #
577 @staticmethod
578 def HasError():
579 return BuildTask._ErrorFlag.isSet()
580
581 ## Get error message in running thread
582 #
583 # Since the main thread cannot catch exceptions in other thread, we have to
584 # use a static variable to communicate this message to main thread.
585 #
586 @staticmethod
587 def GetErrorMessage():
588 return BuildTask._ErrorMessage
589
590 ## Factory method to create a BuildTask object
591 #
592 # This method will check if a module is building or has been built. And if
593 # true, just return the associated BuildTask object in the _TaskQueue. If
594 # not, create and return a new BuildTask object. The new BuildTask object
595 # will be appended to the _PendingQueue for scheduling later.
596 #
597 # @param BuildItem A BuildUnit object representing a build object
598 # @param Dependency The dependent build object of BuildItem
599 #
600 @staticmethod
601 def New(BuildItem, Dependency=None):
602 if BuildItem in BuildTask._TaskQueue:
603 Bt = BuildTask._TaskQueue[BuildItem]
604 return Bt
605
606 Bt = BuildTask()
607 Bt._Init(BuildItem, Dependency)
608 BuildTask._TaskQueue[BuildItem] = Bt
609
610 BuildTask._PendingQueueLock.acquire()
611 BuildTask._PendingQueue[BuildItem] = Bt
612 BuildTask._PendingQueueLock.release()
613
614 return Bt
615
616 ## The real constructor of BuildTask
617 #
618 # @param BuildItem A BuildUnit object representing a build object
619 # @param Dependency The dependent build object of BuildItem
620 #
621 def _Init(self, BuildItem, Dependency=None):
622 self.BuildItem = BuildItem
623
624 self.DependencyList = []
625 if Dependency == None:
626 Dependency = BuildItem.Dependency
627 else:
628 Dependency.extend(BuildItem.Dependency)
629 self.AddDependency(Dependency)
630 # flag indicating build completes, used to avoid unnecessary re-build
631 self.CompleteFlag = False
632
633 ## Check if all dependent build tasks are completed or not
634 #
635 def IsReady(self):
636 ReadyFlag = True
637 for Dep in self.DependencyList:
638 if Dep.CompleteFlag == True:
639 continue
640 ReadyFlag = False
641 break
642
643 return ReadyFlag
644
645 ## Add dependent build task
646 #
647 # @param Dependency The list of dependent build objects
648 #
649 def AddDependency(self, Dependency):
650 for Dep in Dependency:
651 if not Dep.BuildObject.IsBinaryModule:
652 self.DependencyList.append(BuildTask.New(Dep)) # BuildTask list
653
654 ## The thread wrapper of LaunchCommand function
655 #
656 # @param Command A list or string contains the call of the command
657 # @param WorkingDir The directory in which the program will be running
658 #
659 def _CommandThread(self, Command, WorkingDir):
660 try:
661 LaunchCommand(Command, WorkingDir)
662 self.CompleteFlag = True
663 except:
664 #
665 # TRICK: hide the output of threads left runing, so that the user can
666 # catch the error message easily
667 #
668 if not BuildTask._ErrorFlag.isSet():
669 GlobalData.gBuildingModule = "%s [%s, %s, %s]" % (str(self.BuildItem.BuildObject),
670 self.BuildItem.BuildObject.Arch,
671 self.BuildItem.BuildObject.ToolChain,
672 self.BuildItem.BuildObject.BuildTarget
673 )
674 EdkLogger.SetLevel(EdkLogger.ERROR)
675 BuildTask._ErrorFlag.set()
676 BuildTask._ErrorMessage = "%s broken\n %s [%s]" % \
677 (threading.currentThread().getName(), Command, WorkingDir)
678 # indicate there's a thread is available for another build task
679 BuildTask._RunningQueueLock.acquire()
680 BuildTask._RunningQueue.pop(self.BuildItem)
681 BuildTask._RunningQueueLock.release()
682 BuildTask._Thread.release()
683
684 ## Start build task thread
685 #
686 def Start(self):
687 EdkLogger.quiet("Building ... %s" % repr(self.BuildItem))
688 Command = self.BuildItem.BuildCommand + [self.BuildItem.Target]
689 self.BuildTread = Thread(target=self._CommandThread, args=(Command, self.BuildItem.WorkingDir))
690 self.BuildTread.setName("build thread")
691 self.BuildTread.setDaemon(False)
692 self.BuildTread.start()
693
694 ## The class contains the information related to EFI image
695 #
696 class PeImageInfo():
697 ## Constructor
698 #
699 # Constructor will load all required image information.
700 #
701 # @param BaseName The full file path of image.
702 # @param Guid The GUID for image.
703 # @param Arch Arch of this image.
704 # @param OutputDir The output directory for image.
705 # @param DebugDir The debug directory for image.
706 # @param ImageClass PeImage Information
707 #
708 def __init__(self, BaseName, Guid, Arch, OutputDir, DebugDir, ImageClass):
709 self.BaseName = BaseName
710 self.Guid = Guid
711 self.Arch = Arch
712 self.OutputDir = OutputDir
713 self.DebugDir = DebugDir
714 self.Image = ImageClass
715 self.Image.Size = (self.Image.Size / 0x1000 + 1) * 0x1000
716
717 ## The class implementing the EDK2 build process
718 #
719 # The build process includes:
720 # 1. Load configuration from target.txt and tools_def.txt in $(WORKSPACE)/Conf
721 # 2. Parse DSC file of active platform
722 # 3. Parse FDF file if any
723 # 4. Establish build database, including parse all other files (module, package)
724 # 5. Create AutoGen files (C code file, depex file, makefile) if necessary
725 # 6. Call build command
726 #
727 class Build():
728 ## Constructor
729 #
730 # Constructor will load all necessary configurations, parse platform, modules
731 # and packages and the establish a database for AutoGen.
732 #
733 # @param Target The build command target, one of gSupportedTarget
734 # @param WorkspaceDir The directory of workspace
735 # @param BuildOptions Build options passed from command line
736 #
737 def __init__(self, Target, WorkspaceDir, BuildOptions):
738 self.WorkspaceDir = WorkspaceDir
739 self.Target = Target
740 self.PlatformFile = BuildOptions.PlatformFile
741 self.ModuleFile = BuildOptions.ModuleFile
742 self.ArchList = BuildOptions.TargetArch
743 self.ToolChainList = BuildOptions.ToolChain
744 self.BuildTargetList= BuildOptions.BuildTarget
745 self.Fdf = BuildOptions.FdfFile
746 self.FdList = BuildOptions.RomImage
747 self.FvList = BuildOptions.FvImage
748 self.CapList = BuildOptions.CapName
749 self.SilentMode = BuildOptions.SilentMode
750 self.ThreadNumber = BuildOptions.ThreadNumber
751 self.SkipAutoGen = BuildOptions.SkipAutoGen
752 self.Reparse = BuildOptions.Reparse
753 self.SkuId = BuildOptions.SkuId
754 self.ConfDirectory = BuildOptions.ConfDirectory
755 self.SpawnMode = True
756 self.BuildReport = BuildReport(BuildOptions.ReportFile, BuildOptions.ReportType)
757 self.TargetTxt = TargetTxtClassObject()
758 self.ToolDef = ToolDefClassObject()
759 GlobalData.BuildOptionPcd = BuildOptions.OptionPcd
760 #Set global flag for build mode
761 GlobalData.gIgnoreSource = BuildOptions.IgnoreSources
762
763 if self.ConfDirectory:
764 # Get alternate Conf location, if it is absolute, then just use the absolute directory name
765 ConfDirectoryPath = os.path.normpath(self.ConfDirectory)
766
767 if not os.path.isabs(ConfDirectoryPath):
768 # Since alternate directory name is not absolute, the alternate directory is located within the WORKSPACE
769 # This also handles someone specifying the Conf directory in the workspace. Using --conf=Conf
770 ConfDirectoryPath = mws.join(self.WorkspaceDir, ConfDirectoryPath)
771 else:
772 # Get standard WORKSPACE/Conf use the absolute path to the WORKSPACE/Conf
773 ConfDirectoryPath = mws.join(self.WorkspaceDir, 'Conf')
774 GlobalData.gConfDirectory = ConfDirectoryPath
775 GlobalData.gDatabasePath = os.path.normpath(os.path.join(ConfDirectoryPath, GlobalData.gDatabasePath))
776
777 if BuildOptions.DisableCache:
778 self.Db = WorkspaceDatabase(":memory:")
779 else:
780 self.Db = WorkspaceDatabase(GlobalData.gDatabasePath, self.Reparse)
781 self.BuildDatabase = self.Db.BuildObject
782 self.Platform = None
783 self.LoadFixAddress = 0
784 self.UniFlag = BuildOptions.Flag
785 self.BuildModules = []
786 self.Db_Flag = False
787 self.LaunchPrebuildFlag = False
788 self.PrebuildScript = ''
789 self.PostbuildScript = ''
790 self.PlatformBuildPath = os.path.join(GlobalData.gConfDirectory,'.cache', '.PlatformBuild')
791 if BuildOptions.CommandLength:
792 GlobalData.gCommandMaxLength = BuildOptions.CommandLength
793
794 # print dot character during doing some time-consuming work
795 self.Progress = Utils.Progressor()
796 # print current build environment and configuration
797 EdkLogger.quiet("%-16s = %s" % ("WORKSPACE", os.environ["WORKSPACE"]))
798 if "PACKAGES_PATH" in os.environ:
799 # WORKSPACE env has been converted before. Print the same path style with WORKSPACE env.
800 EdkLogger.quiet("%-16s = %s" % ("PACKAGES_PATH", os.path.normcase(os.path.normpath(os.environ["PACKAGES_PATH"]))))
801 EdkLogger.quiet("%-16s = %s" % ("ECP_SOURCE", os.environ["ECP_SOURCE"]))
802 EdkLogger.quiet("%-16s = %s" % ("EDK_SOURCE", os.environ["EDK_SOURCE"]))
803 EdkLogger.quiet("%-16s = %s" % ("EFI_SOURCE", os.environ["EFI_SOURCE"]))
804 EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_PATH", os.environ["EDK_TOOLS_PATH"]))
805 if "EDK_TOOLS_BIN" in os.environ:
806 # Print the same path style with WORKSPACE env.
807 EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_BIN", os.path.normcase(os.path.normpath(os.environ["EDK_TOOLS_BIN"]))))
808
809 self.InitPreBuild()
810 self.InitPostBuild()
811 if self.PrebuildScript:
812 EdkLogger.quiet("%-16s = %s" % ("PREBUILD", self.PrebuildScript))
813 if self.PostbuildScript:
814 EdkLogger.quiet("%-16s = %s" % ("POSTBUILD", self.PostbuildScript))
815 if self.PrebuildScript:
816 self.LaunchPrebuild()
817 if not (self.LaunchPrebuildFlag and os.path.exists(self.PlatformBuildPath)):
818 self.InitBuild()
819
820 EdkLogger.info("")
821 os.chdir(self.WorkspaceDir)
822
823 ## Load configuration
824 #
825 # This method will parse target.txt and get the build configurations.
826 #
827 def LoadConfiguration(self):
828 #
829 # Check target.txt and tools_def.txt and Init them
830 #
831 BuildConfigurationFile = os.path.normpath(os.path.join(GlobalData.gConfDirectory, gBuildConfiguration))
832 if os.path.isfile(BuildConfigurationFile) == True:
833 StatusCode = self.TargetTxt.LoadTargetTxtFile(BuildConfigurationFile)
834
835 ToolDefinitionFile = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF]
836 if ToolDefinitionFile == '':
837 ToolDefinitionFile = gToolsDefinition
838 ToolDefinitionFile = os.path.normpath(mws.join(self.WorkspaceDir, 'Conf', ToolDefinitionFile))
839 if os.path.isfile(ToolDefinitionFile) == True:
840 StatusCode = self.ToolDef.LoadToolDefFile(ToolDefinitionFile)
841 else:
842 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=ToolDefinitionFile)
843 else:
844 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile)
845
846 # if no ARCH given in command line, get it from target.txt
847 if not self.ArchList:
848 self.ArchList = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TARGET_ARCH]
849 self.ArchList = tuple(self.ArchList)
850
851 # if no build target given in command line, get it from target.txt
852 if not self.BuildTargetList:
853 self.BuildTargetList = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TARGET]
854
855 # if no tool chain given in command line, get it from target.txt
856 if not self.ToolChainList:
857 self.ToolChainList = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_TAG]
858 if self.ToolChainList == None or len(self.ToolChainList) == 0:
859 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE, ExtraData="No toolchain given. Don't know how to build.\n")
860
861 # check if the tool chains are defined or not
862 NewToolChainList = []
863 for ToolChain in self.ToolChainList:
864 if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG]:
865 EdkLogger.warn("build", "Tool chain [%s] is not defined" % ToolChain)
866 else:
867 NewToolChainList.append(ToolChain)
868 # if no tool chain available, break the build
869 if len(NewToolChainList) == 0:
870 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,
871 ExtraData="[%s] not defined. No toolchain available for build!\n" % ", ".join(self.ToolChainList))
872 else:
873 self.ToolChainList = NewToolChainList
874
875 if self.ThreadNumber == None:
876 self.ThreadNumber = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER]
877 if self.ThreadNumber == '':
878 self.ThreadNumber = 0
879 else:
880 self.ThreadNumber = int(self.ThreadNumber, 0)
881
882 if self.ThreadNumber == 0:
883 self.ThreadNumber = 1
884
885 if not self.PlatformFile:
886 PlatformFile = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_ACTIVE_PLATFORM]
887 if not PlatformFile:
888 # Try to find one in current directory
889 WorkingDirectory = os.getcwd()
890 FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.dsc')))
891 FileNum = len(FileList)
892 if FileNum >= 2:
893 EdkLogger.error("build", OPTION_MISSING,
894 ExtraData="There are %d DSC files in %s. Use '-p' to specify one.\n" % (FileNum, WorkingDirectory))
895 elif FileNum == 1:
896 PlatformFile = FileList[0]
897 else:
898 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,
899 ExtraData="No active platform specified in target.txt or command line! Nothing can be built.\n")
900
901 self.PlatformFile = PathClass(NormFile(PlatformFile, self.WorkspaceDir), self.WorkspaceDir)
902
903 ## Initialize build configuration
904 #
905 # This method will parse DSC file and merge the configurations from
906 # command line and target.txt, then get the final build configurations.
907 #
908 def InitBuild(self):
909 # parse target.txt, tools_def.txt, and platform file
910 self.LoadConfiguration()
911
912 # Allow case-insensitive for those from command line or configuration file
913 ErrorCode, ErrorInfo = self.PlatformFile.Validate(".dsc", False)
914 if ErrorCode != 0:
915 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)
916
917 # create metafile database
918 if not self.Db_Flag:
919 self.Db.InitDatabase()
920
921 def InitPreBuild(self):
922 self.LoadConfiguration()
923 if self.BuildTargetList:
924 GlobalData.gGlobalDefines['TARGET'] = self.BuildTargetList[0]
925 if self.ArchList:
926 GlobalData.gGlobalDefines['ARCH'] = self.ArchList[0]
927 if self.ToolChainList:
928 GlobalData.gGlobalDefines['TOOLCHAIN'] = self.ToolChainList[0]
929 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = self.ToolChainList[0]
930 if 'PREBUILD' in GlobalData.gCommandLineDefines.keys():
931 self.Prebuild = GlobalData.gCommandLineDefines.get('PREBUILD')
932 else:
933 self.Db.InitDatabase()
934 self.Db_Flag = True
935 Platform = self.Db._MapPlatform(str(self.PlatformFile))
936 self.Prebuild = str(Platform.Prebuild)
937 if self.Prebuild:
938 PrebuildList = self.Prebuild.split()
939 if not os.path.isabs(PrebuildList[0]):
940 PrebuildList[0] = mws.join(self.WorkspaceDir, PrebuildList[0])
941 if os.path.isfile(PrebuildList[0]):
942 self.PrebuildScript = PrebuildList[0]
943 self.Prebuild = ' '.join(PrebuildList)
944 self.Prebuild += self.PassCommandOption(self.BuildTargetList, self.ArchList, self.ToolChainList)
945 #self.LaunchPrebuild()
946 else:
947 EdkLogger.error("Prebuild", PREBUILD_ERROR, "the prebuild script %s is not exist.\n If you'd like to disable the Prebuild process, please use the format: -D PREBUILD=\"\" " %(PrebuildList[0]))
948
949 def InitPostBuild(self):
950 if 'POSTBUILD' in GlobalData.gCommandLineDefines.keys():
951 self.Postbuild = GlobalData.gCommandLineDefines.get('POSTBUILD')
952 else:
953 Platform = self.Db._MapPlatform(str(self.PlatformFile))
954 self.Postbuild = str(Platform.Postbuild)
955 if self.Postbuild:
956 PostbuildList = self.Postbuild.split()
957 if not os.path.isabs(PostbuildList[0]):
958 PostbuildList[0] = mws.join(self.WorkspaceDir, PostbuildList[0])
959 if os.path.isfile(PostbuildList[0]):
960 self.PostbuildScript = PostbuildList[0]
961 self.Postbuild = ' '.join(PostbuildList)
962 self.Postbuild += self.PassCommandOption(self.BuildTargetList, self.ArchList, self.ToolChainList)
963 #self.LanuchPostbuild()
964 else:
965 EdkLogger.error("Postbuild", POSTBUILD_ERROR, "the postbuild script %s is not exist.\n If you'd like to disable the Postbuild process, please use the format: -D POSTBUILD=\"\" " %(PostbuildList[0]))
966
967 def PassCommandOption(self, BuildTarget, TargetArch, ToolChain):
968 BuildStr = ''
969 if GlobalData.gCommand and isinstance(GlobalData.gCommand, list):
970 BuildStr += ' ' + ' '.join(GlobalData.gCommand)
971 TargetFlag = False
972 ArchFlag = False
973 ToolChainFlag = False
974
975 if GlobalData.gOptions and not GlobalData.gOptions.BuildTarget:
976 TargetFlag = True
977 if GlobalData.gOptions and not GlobalData.gOptions.TargetArch:
978 ArchFlag = True
979 if GlobalData.gOptions and not GlobalData.gOptions.ToolChain:
980 ToolChainFlag = True
981
982 if TargetFlag and BuildTarget:
983 if isinstance(BuildTarget, list) or isinstance(BuildTarget, tuple):
984 BuildStr += ' -b ' + ' -b '.join(BuildTarget)
985 elif isinstance(BuildTarget, str):
986 BuildStr += ' -b ' + BuildTarget
987 if ArchFlag and TargetArch:
988 if isinstance(TargetArch, list) or isinstance(TargetArch, tuple):
989 BuildStr += ' -a ' + ' -a '.join(TargetArch)
990 elif isinstance(TargetArch, str):
991 BuildStr += ' -a ' + TargetArch
992 if ToolChainFlag and ToolChain:
993 if isinstance(ToolChain, list) or isinstance(ToolChain, tuple):
994 BuildStr += ' -t ' + ' -t '.join(ToolChain)
995 elif isinstance(ToolChain, str):
996 BuildStr += ' -t ' + ToolChain
997
998 return BuildStr
999
1000 def LaunchPrebuild(self):
1001 if self.Prebuild:
1002 EdkLogger.info("\n- Prebuild Start -\n")
1003 self.LaunchPrebuildFlag = True
1004 PrebuildEnvFile = os.path.join(GlobalData.gConfDirectory,'.cache','.PrebuildEnv')
1005 if os.path.isfile(PrebuildEnvFile):
1006 os.remove(PrebuildEnvFile)
1007 if os.path.isfile(self.PlatformBuildPath):
1008 os.remove(self.PlatformBuildPath)
1009 if sys.platform == "win32":
1010 args = ' && '.join((self.Prebuild, 'set > ' + PrebuildEnvFile))
1011 Process = Popen(args, stdout=PIPE, stderr=PIPE)
1012 else:
1013 args = ' && '.join((self.Prebuild, 'env > ' + PrebuildEnvFile))
1014 Process = Popen(args, stdout=PIPE, stderr=PIPE, shell=True, executable="/bin/bash")
1015
1016 # launch two threads to read the STDOUT and STDERR
1017 EndOfProcedure = Event()
1018 EndOfProcedure.clear()
1019 if Process.stdout:
1020 StdOutThread = Thread(target=ReadMessage, args=(Process.stdout, EdkLogger.info, EndOfProcedure))
1021 StdOutThread.setName("STDOUT-Redirector")
1022 StdOutThread.setDaemon(False)
1023 StdOutThread.start()
1024
1025 if Process.stderr:
1026 StdErrThread = Thread(target=ReadMessage, args=(Process.stderr, EdkLogger.quiet, EndOfProcedure))
1027 StdErrThread.setName("STDERR-Redirector")
1028 StdErrThread.setDaemon(False)
1029 StdErrThread.start()
1030 # waiting for program exit
1031 Process.wait()
1032
1033 if Process.stdout:
1034 StdOutThread.join()
1035 if Process.stderr:
1036 StdErrThread.join()
1037 if Process.returncode != 0 :
1038 EdkLogger.error("Prebuild", PREBUILD_ERROR, 'Prebuild process is not success!')
1039
1040 if os.path.exists(PrebuildEnvFile):
1041 f = open(PrebuildEnvFile)
1042 envs = f.readlines()
1043 f.close()
1044 envs = itertools.imap(lambda l: l.split('=',1), envs)
1045 envs = itertools.ifilter(lambda l: len(l) == 2, envs)
1046 envs = itertools.imap(lambda l: [i.strip() for i in l], envs)
1047 os.environ.update(dict(envs))
1048 EdkLogger.info("\n- Prebuild Done -\n")
1049
1050 def LanuchPostbuild(self):
1051 if self.Postbuild:
1052 EdkLogger.info("\n- Postbuild Start -\n")
1053 if sys.platform == "win32":
1054 Process = Popen(self.Postbuild, stdout=PIPE, stderr=PIPE)
1055 else:
1056 Process = Popen(self.Postbuild, stdout=PIPE, stderr=PIPE, shell=True, executable="/bin/bash")
1057 # launch two threads to read the STDOUT and STDERR
1058 EndOfProcedure = Event()
1059 EndOfProcedure.clear()
1060 if Process.stdout:
1061 StdOutThread = Thread(target=ReadMessage, args=(Process.stdout, EdkLogger.info, EndOfProcedure))
1062 StdOutThread.setName("STDOUT-Redirector")
1063 StdOutThread.setDaemon(False)
1064 StdOutThread.start()
1065
1066 if Process.stderr:
1067 StdErrThread = Thread(target=ReadMessage, args=(Process.stderr, EdkLogger.quiet, EndOfProcedure))
1068 StdErrThread.setName("STDERR-Redirector")
1069 StdErrThread.setDaemon(False)
1070 StdErrThread.start()
1071 # waiting for program exit
1072 Process.wait()
1073
1074 if Process.stdout:
1075 StdOutThread.join()
1076 if Process.stderr:
1077 StdErrThread.join()
1078 if Process.returncode != 0 :
1079 EdkLogger.error("Postbuild", POSTBUILD_ERROR, 'Postbuild process is not success!')
1080 EdkLogger.info("\n- Postbuild Done -\n")
1081 ## Build a module or platform
1082 #
1083 # Create autogen code and makefile for a module or platform, and the launch
1084 # "make" command to build it
1085 #
1086 # @param Target The target of build command
1087 # @param Platform The platform file
1088 # @param Module The module file
1089 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"
1090 # @param ToolChain The name of toolchain to build
1091 # @param Arch The arch of the module/platform
1092 # @param CreateDepModuleCodeFile Flag used to indicate creating code
1093 # for dependent modules/Libraries
1094 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile
1095 # for dependent modules/Libraries
1096 #
1097 def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False):
1098 if AutoGenObject == None:
1099 return False
1100
1101 # skip file generation for cleanxxx targets, run and fds target
1102 if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1103 # for target which must generate AutoGen code and makefile
1104 if not self.SkipAutoGen or Target == 'genc':
1105 self.Progress.Start("Generating code")
1106 AutoGenObject.CreateCodeFile(CreateDepsCodeFile)
1107 self.Progress.Stop("done!")
1108 if Target == "genc":
1109 return True
1110
1111 if not self.SkipAutoGen or Target == 'genmake':
1112 self.Progress.Start("Generating makefile")
1113 AutoGenObject.CreateMakeFile(CreateDepsMakeFile)
1114 self.Progress.Stop("done!")
1115 if Target == "genmake":
1116 return True
1117 else:
1118 # always recreate top/platform makefile when clean, just in case of inconsistency
1119 AutoGenObject.CreateCodeFile(False)
1120 AutoGenObject.CreateMakeFile(False)
1121
1122 if EdkLogger.GetLevel() == EdkLogger.QUIET:
1123 EdkLogger.quiet("Building ... %s" % repr(AutoGenObject))
1124
1125 BuildCommand = AutoGenObject.BuildCommand
1126 if BuildCommand == None or len(BuildCommand) == 0:
1127 EdkLogger.error("build", OPTION_MISSING,
1128 "No build command found for this module. "
1129 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
1130 (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch),
1131 ExtraData=str(AutoGenObject))
1132
1133 makefile = GenMake.BuildFile(AutoGenObject)._FILE_NAME_[GenMake.gMakeType]
1134
1135 # run
1136 if Target == 'run':
1137 RunDir = os.path.normpath(os.path.join(AutoGenObject.BuildDir, GlobalData.gGlobalDefines['ARCH']))
1138 Command = '.\SecMain'
1139 os.chdir(RunDir)
1140 LaunchCommand(Command, RunDir)
1141 return True
1142
1143 # build modules
1144 if BuildModule:
1145 BuildCommand = BuildCommand + [Target]
1146 LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir)
1147 self.CreateAsBuiltInf()
1148 return True
1149
1150 # build library
1151 if Target == 'libraries':
1152 for Lib in AutoGenObject.LibraryBuildDirectoryList:
1153 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, makefile)), 'pbuild']
1154 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
1155 return True
1156
1157 # build module
1158 if Target == 'modules':
1159 for Lib in AutoGenObject.LibraryBuildDirectoryList:
1160 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, makefile)), 'pbuild']
1161 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
1162 for Mod in AutoGenObject.ModuleBuildDirectoryList:
1163 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Mod, makefile)), 'pbuild']
1164 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
1165 self.CreateAsBuiltInf()
1166 return True
1167
1168 # cleanlib
1169 if Target == 'cleanlib':
1170 for Lib in AutoGenObject.LibraryBuildDirectoryList:
1171 LibMakefile = os.path.normpath(os.path.join(Lib, makefile))
1172 if os.path.exists(LibMakefile):
1173 NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall']
1174 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
1175 return True
1176
1177 # clean
1178 if Target == 'clean':
1179 for Mod in AutoGenObject.ModuleBuildDirectoryList:
1180 ModMakefile = os.path.normpath(os.path.join(Mod, makefile))
1181 if os.path.exists(ModMakefile):
1182 NewBuildCommand = BuildCommand + ['-f', ModMakefile, 'cleanall']
1183 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
1184 for Lib in AutoGenObject.LibraryBuildDirectoryList:
1185 LibMakefile = os.path.normpath(os.path.join(Lib, makefile))
1186 if os.path.exists(LibMakefile):
1187 NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall']
1188 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
1189 return True
1190
1191 # cleanall
1192 if Target == 'cleanall':
1193 try:
1194 #os.rmdir(AutoGenObject.BuildDir)
1195 RemoveDirectory(AutoGenObject.BuildDir, True)
1196 except WindowsError, X:
1197 EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X))
1198 return True
1199
1200 ## Build a module or platform
1201 #
1202 # Create autogen code and makefile for a module or platform, and the launch
1203 # "make" command to build it
1204 #
1205 # @param Target The target of build command
1206 # @param Platform The platform file
1207 # @param Module The module file
1208 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"
1209 # @param ToolChain The name of toolchain to build
1210 # @param Arch The arch of the module/platform
1211 # @param CreateDepModuleCodeFile Flag used to indicate creating code
1212 # for dependent modules/Libraries
1213 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile
1214 # for dependent modules/Libraries
1215 #
1216 def _Build(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False):
1217 if AutoGenObject == None:
1218 return False
1219
1220 # skip file generation for cleanxxx targets, run and fds target
1221 if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1222 # for target which must generate AutoGen code and makefile
1223 if not self.SkipAutoGen or Target == 'genc':
1224 self.Progress.Start("Generating code")
1225 AutoGenObject.CreateCodeFile(CreateDepsCodeFile)
1226 self.Progress.Stop("done!")
1227 if Target == "genc":
1228 return True
1229
1230 if not self.SkipAutoGen or Target == 'genmake':
1231 self.Progress.Start("Generating makefile")
1232 AutoGenObject.CreateMakeFile(CreateDepsMakeFile)
1233 #AutoGenObject.CreateAsBuiltInf()
1234 self.Progress.Stop("done!")
1235 if Target == "genmake":
1236 return True
1237 else:
1238 # always recreate top/platform makefile when clean, just in case of inconsistency
1239 AutoGenObject.CreateCodeFile(False)
1240 AutoGenObject.CreateMakeFile(False)
1241
1242 if EdkLogger.GetLevel() == EdkLogger.QUIET:
1243 EdkLogger.quiet("Building ... %s" % repr(AutoGenObject))
1244
1245 BuildCommand = AutoGenObject.BuildCommand
1246 if BuildCommand == None or len(BuildCommand) == 0:
1247 EdkLogger.error("build", OPTION_MISSING,
1248 "No build command found for this module. "
1249 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
1250 (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch),
1251 ExtraData=str(AutoGenObject))
1252
1253 # build modules
1254 if BuildModule:
1255 if Target != 'fds':
1256 BuildCommand = BuildCommand + [Target]
1257 LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir)
1258 self.CreateAsBuiltInf()
1259 return True
1260
1261 # genfds
1262 if Target == 'fds':
1263 LaunchCommand(AutoGenObject.GenFdsCommand, AutoGenObject.MakeFileDir)
1264 return True
1265
1266 # run
1267 if Target == 'run':
1268 RunDir = os.path.normpath(os.path.join(AutoGenObject.BuildDir, GlobalData.gGlobalDefines['ARCH']))
1269 Command = '.\SecMain'
1270 os.chdir(RunDir)
1271 LaunchCommand(Command, RunDir)
1272 return True
1273
1274 # build library
1275 if Target == 'libraries':
1276 pass
1277
1278 # not build modules
1279
1280
1281 # cleanall
1282 if Target == 'cleanall':
1283 try:
1284 #os.rmdir(AutoGenObject.BuildDir)
1285 RemoveDirectory(AutoGenObject.BuildDir, True)
1286 except WindowsError, X:
1287 EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X))
1288 return True
1289
1290 ## Rebase module image and Get function address for the input module list.
1291 #
1292 def _RebaseModule (self, MapBuffer, BaseAddress, ModuleList, AddrIsOffset = True, ModeIsSmm = False):
1293 if ModeIsSmm:
1294 AddrIsOffset = False
1295 InfFileNameList = ModuleList.keys()
1296 #InfFileNameList.sort()
1297 for InfFile in InfFileNameList:
1298 sys.stdout.write (".")
1299 sys.stdout.flush()
1300 ModuleInfo = ModuleList[InfFile]
1301 ModuleName = ModuleInfo.BaseName
1302 ModuleOutputImage = ModuleInfo.Image.FileName
1303 ModuleDebugImage = os.path.join(ModuleInfo.DebugDir, ModuleInfo.BaseName + '.efi')
1304 ## for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1305 if not ModeIsSmm:
1306 BaseAddress = BaseAddress - ModuleInfo.Image.Size
1307 #
1308 # Update Image to new BaseAddress by GenFw tool
1309 #
1310 LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir)
1311 LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir)
1312 else:
1313 #
1314 # Set new address to the section header only for SMM driver.
1315 #
1316 LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir)
1317 LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir)
1318 #
1319 # Collect funtion address from Map file
1320 #
1321 ImageMapTable = ModuleOutputImage.replace('.efi', '.map')
1322 FunctionList = []
1323 if os.path.exists(ImageMapTable):
1324 OrigImageBaseAddress = 0
1325 ImageMap = open(ImageMapTable, 'r')
1326 for LinStr in ImageMap:
1327 if len (LinStr.strip()) == 0:
1328 continue
1329 #
1330 # Get the preferred address set on link time.
1331 #
1332 if LinStr.find ('Preferred load address is') != -1:
1333 StrList = LinStr.split()
1334 OrigImageBaseAddress = int (StrList[len(StrList) - 1], 16)
1335
1336 StrList = LinStr.split()
1337 if len (StrList) > 4:
1338 if StrList[3] == 'f' or StrList[3] == 'F':
1339 Name = StrList[1]
1340 RelativeAddress = int (StrList[2], 16) - OrigImageBaseAddress
1341 FunctionList.append ((Name, RelativeAddress))
1342 if ModuleInfo.Arch == 'IPF' and Name.endswith('_ModuleEntryPoint'):
1343 #
1344 # Get the real entry point address for IPF image.
1345 #
1346 ModuleInfo.Image.EntryPoint = RelativeAddress
1347 ImageMap.close()
1348 #
1349 # Add general information.
1350 #
1351 if ModeIsSmm:
1352 MapBuffer.write('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint))
1353 elif AddrIsOffset:
1354 MapBuffer.write('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName, 0 - BaseAddress, 0 - (BaseAddress + ModuleInfo.Image.EntryPoint)))
1355 else:
1356 MapBuffer.write('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint))
1357 #
1358 # Add guid and general seciton section.
1359 #
1360 TextSectionAddress = 0
1361 DataSectionAddress = 0
1362 for SectionHeader in ModuleInfo.Image.SectionHeaderList:
1363 if SectionHeader[0] == '.text':
1364 TextSectionAddress = SectionHeader[1]
1365 elif SectionHeader[0] in ['.data', '.sdata']:
1366 DataSectionAddress = SectionHeader[1]
1367 if AddrIsOffset:
1368 MapBuffer.write('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + TextSectionAddress), 0 - (BaseAddress + DataSectionAddress)))
1369 else:
1370 MapBuffer.write('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo.Guid, BaseAddress + TextSectionAddress, BaseAddress + DataSectionAddress))
1371 #
1372 # Add debug image full path.
1373 #
1374 MapBuffer.write('(IMAGE=%s)\n\n' % (ModuleDebugImage))
1375 #
1376 # Add funtion address
1377 #
1378 for Function in FunctionList:
1379 if AddrIsOffset:
1380 MapBuffer.write(' -0x%010X %s\n' % (0 - (BaseAddress + Function[1]), Function[0]))
1381 else:
1382 MapBuffer.write(' 0x%010X %s\n' % (BaseAddress + Function[1], Function[0]))
1383 ImageMap.close()
1384
1385 #
1386 # for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1387 #
1388 if ModeIsSmm:
1389 BaseAddress = BaseAddress + ModuleInfo.Image.Size
1390
1391 ## Collect MAP information of all FVs
1392 #
1393 def _CollectFvMapBuffer (self, MapBuffer, Wa, ModuleList):
1394 if self.Fdf:
1395 # First get the XIP base address for FV map file.
1396 GuidPattern = re.compile("[-a-fA-F0-9]+")
1397 GuidName = re.compile("\(GUID=[-a-fA-F0-9]+")
1398 for FvName in Wa.FdfProfile.FvDict.keys():
1399 FvMapBuffer = os.path.join(Wa.FvDir, FvName + '.Fv.map')
1400 if not os.path.exists(FvMapBuffer):
1401 continue
1402 FvMap = open(FvMapBuffer, 'r')
1403 #skip FV size information
1404 FvMap.readline()
1405 FvMap.readline()
1406 FvMap.readline()
1407 FvMap.readline()
1408 for Line in FvMap:
1409 MatchGuid = GuidPattern.match(Line)
1410 if MatchGuid != None:
1411 #
1412 # Replace GUID with module name
1413 #
1414 GuidString = MatchGuid.group()
1415 if GuidString.upper() in ModuleList:
1416 Line = Line.replace(GuidString, ModuleList[GuidString.upper()].Name)
1417 MapBuffer.write('%s' % (Line))
1418 #
1419 # Add the debug image full path.
1420 #
1421 MatchGuid = GuidName.match(Line)
1422 if MatchGuid != None:
1423 GuidString = MatchGuid.group().split("=")[1]
1424 if GuidString.upper() in ModuleList:
1425 MapBuffer.write('(IMAGE=%s)\n' % (os.path.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].Name + '.efi')))
1426
1427 FvMap.close()
1428
1429 ## Collect MAP information of all modules
1430 #
1431 def _CollectModuleMapBuffer (self, MapBuffer, ModuleList):
1432 sys.stdout.write ("Generate Load Module At Fix Address Map")
1433 sys.stdout.flush()
1434 PatchEfiImageList = []
1435 PeiModuleList = {}
1436 BtModuleList = {}
1437 RtModuleList = {}
1438 SmmModuleList = {}
1439 PeiSize = 0
1440 BtSize = 0
1441 RtSize = 0
1442 # reserve 4K size in SMRAM to make SMM module address not from 0.
1443 SmmSize = 0x1000
1444 IsIpfPlatform = False
1445 if 'IPF' in self.ArchList:
1446 IsIpfPlatform = True
1447 for ModuleGuid in ModuleList:
1448 Module = ModuleList[ModuleGuid]
1449 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (Module.MetaFile, Module.Arch, Module.ToolChain, Module.BuildTarget)
1450
1451 OutputImageFile = ''
1452 for ResultFile in Module.CodaTargetList:
1453 if str(ResultFile.Target).endswith('.efi'):
1454 #
1455 # module list for PEI, DXE, RUNTIME and SMM
1456 #
1457 OutputImageFile = os.path.join(Module.OutputDir, Module.Name + '.efi')
1458 ImageClass = PeImageClass (OutputImageFile)
1459 if not ImageClass.IsValid:
1460 EdkLogger.error("build", FILE_PARSE_FAILURE, ExtraData=ImageClass.ErrorInfo)
1461 ImageInfo = PeImageInfo(Module.Name, Module.Guid, Module.Arch, Module.OutputDir, Module.DebugDir, ImageClass)
1462 if Module.ModuleType in ['PEI_CORE', 'PEIM', 'COMBINED_PEIM_DRIVER', 'PIC_PEIM', 'RELOCATABLE_PEIM', 'DXE_CORE']:
1463 PeiModuleList[Module.MetaFile] = ImageInfo
1464 PeiSize += ImageInfo.Image.Size
1465 elif Module.ModuleType in ['BS_DRIVER', 'DXE_DRIVER', 'UEFI_DRIVER']:
1466 BtModuleList[Module.MetaFile] = ImageInfo
1467 BtSize += ImageInfo.Image.Size
1468 elif Module.ModuleType in ['DXE_RUNTIME_DRIVER', 'RT_DRIVER', 'DXE_SAL_DRIVER', 'SAL_RT_DRIVER']:
1469 RtModuleList[Module.MetaFile] = ImageInfo
1470 #IPF runtime driver needs to be at 2 page alignment.
1471 if IsIpfPlatform and ImageInfo.Image.Size % 0x2000 != 0:
1472 ImageInfo.Image.Size = (ImageInfo.Image.Size / 0x2000 + 1) * 0x2000
1473 RtSize += ImageInfo.Image.Size
1474 elif Module.ModuleType in ['SMM_CORE', 'DXE_SMM_DRIVER']:
1475 SmmModuleList[Module.MetaFile] = ImageInfo
1476 SmmSize += ImageInfo.Image.Size
1477 if Module.ModuleType == 'DXE_SMM_DRIVER':
1478 PiSpecVersion = '0x00000000'
1479 if 'PI_SPECIFICATION_VERSION' in Module.Module.Specification:
1480 PiSpecVersion = Module.Module.Specification['PI_SPECIFICATION_VERSION']
1481 # for PI specification < PI1.1, DXE_SMM_DRIVER also runs as BOOT time driver.
1482 if int(PiSpecVersion, 16) < 0x0001000A:
1483 BtModuleList[Module.MetaFile] = ImageInfo
1484 BtSize += ImageInfo.Image.Size
1485 break
1486 #
1487 # EFI image is final target.
1488 # Check EFI image contains patchable FixAddress related PCDs.
1489 #
1490 if OutputImageFile != '':
1491 ModuleIsPatch = False
1492 for Pcd in Module.ModulePcdList:
1493 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_LIST:
1494 ModuleIsPatch = True
1495 break
1496 if not ModuleIsPatch:
1497 for Pcd in Module.LibraryPcdList:
1498 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_LIST:
1499 ModuleIsPatch = True
1500 break
1501
1502 if not ModuleIsPatch:
1503 continue
1504 #
1505 # Module includes the patchable load fix address PCDs.
1506 # It will be fixed up later.
1507 #
1508 PatchEfiImageList.append (OutputImageFile)
1509
1510 #
1511 # Get Top Memory address
1512 #
1513 ReservedRuntimeMemorySize = 0
1514 TopMemoryAddress = 0
1515 if self.LoadFixAddress == 0xFFFFFFFFFFFFFFFF:
1516 TopMemoryAddress = 0
1517 else:
1518 TopMemoryAddress = self.LoadFixAddress
1519 if TopMemoryAddress < RtSize + BtSize + PeiSize:
1520 EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS is too low to load driver")
1521 # Make IPF runtime driver at 2 page alignment.
1522 if IsIpfPlatform:
1523 ReservedRuntimeMemorySize = TopMemoryAddress % 0x2000
1524 RtSize = RtSize + ReservedRuntimeMemorySize
1525
1526 #
1527 # Patch FixAddress related PCDs into EFI image
1528 #
1529 for EfiImage in PatchEfiImageList:
1530 EfiImageMap = EfiImage.replace('.efi', '.map')
1531 if not os.path.exists(EfiImageMap):
1532 continue
1533 #
1534 # Get PCD offset in EFI image by GenPatchPcdTable function
1535 #
1536 PcdTable = parsePcdInfoFromMapFile(EfiImageMap, EfiImage)
1537 #
1538 # Patch real PCD value by PatchPcdValue tool
1539 #
1540 for PcdInfo in PcdTable:
1541 ReturnValue = 0
1542 if PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE:
1543 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE, str (PeiSize / 0x1000))
1544 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE:
1545 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE_DATA_TYPE, str (BtSize / 0x1000))
1546 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE:
1547 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE_DATA_TYPE, str (RtSize / 0x1000))
1548 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE and len (SmmModuleList) > 0:
1549 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE_DATA_TYPE, str (SmmSize / 0x1000))
1550 if ReturnValue != 0:
1551 EdkLogger.error("build", PARAMETER_INVALID, "Patch PCD value failed", ExtraData=ErrorInfo)
1552
1553 MapBuffer.write('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize / 0x1000))
1554 MapBuffer.write('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize / 0x1000))
1555 MapBuffer.write('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize / 0x1000))
1556 if len (SmmModuleList) > 0:
1557 MapBuffer.write('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize / 0x1000))
1558
1559 PeiBaseAddr = TopMemoryAddress - RtSize - BtSize
1560 BtBaseAddr = TopMemoryAddress - RtSize
1561 RtBaseAddr = TopMemoryAddress - ReservedRuntimeMemorySize
1562
1563 self._RebaseModule (MapBuffer, PeiBaseAddr, PeiModuleList, TopMemoryAddress == 0)
1564 self._RebaseModule (MapBuffer, BtBaseAddr, BtModuleList, TopMemoryAddress == 0)
1565 self._RebaseModule (MapBuffer, RtBaseAddr, RtModuleList, TopMemoryAddress == 0)
1566 self._RebaseModule (MapBuffer, 0x1000, SmmModuleList, AddrIsOffset=False, ModeIsSmm=True)
1567 MapBuffer.write('\n\n')
1568 sys.stdout.write ("\n")
1569 sys.stdout.flush()
1570
1571 ## Save platform Map file
1572 #
1573 def _SaveMapFile (self, MapBuffer, Wa):
1574 #
1575 # Map file path is got.
1576 #
1577 MapFilePath = os.path.join(Wa.BuildDir, Wa.Name + '.map')
1578 #
1579 # Save address map into MAP file.
1580 #
1581 SaveFileOnChange(MapFilePath, MapBuffer.getvalue(), False)
1582 MapBuffer.close()
1583 if self.LoadFixAddress != 0:
1584 sys.stdout.write ("\nLoad Module At Fix Address Map file can be found at %s\n" % (MapFilePath))
1585 sys.stdout.flush()
1586
1587 ## Build active platform for different build targets and different tool chains
1588 #
1589 def _BuildPlatform(self):
1590 SaveFileOnChange(self.PlatformBuildPath, '# DO NOT EDIT \n# FILE auto-generated\n', False)
1591 for BuildTarget in self.BuildTargetList:
1592 GlobalData.gGlobalDefines['TARGET'] = BuildTarget
1593 for ToolChain in self.ToolChainList:
1594 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain
1595 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain
1596 Wa = WorkspaceAutoGen(
1597 self.WorkspaceDir,
1598 self.PlatformFile,
1599 BuildTarget,
1600 ToolChain,
1601 self.ArchList,
1602 self.BuildDatabase,
1603 self.TargetTxt,
1604 self.ToolDef,
1605 self.Fdf,
1606 self.FdList,
1607 self.FvList,
1608 self.CapList,
1609 self.SkuId,
1610 self.UniFlag,
1611 self.Progress
1612 )
1613 self.Fdf = Wa.FdfFile
1614 self.LoadFixAddress = Wa.Platform.LoadFixAddress
1615 self.BuildReport.AddPlatformReport(Wa)
1616 self.Progress.Stop("done!")
1617 for Arch in Wa.ArchList:
1618 GlobalData.gGlobalDefines['ARCH'] = Arch
1619 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)
1620 for Module in Pa.Platform.Modules:
1621 # Get ModuleAutoGen object to generate C code file and makefile
1622 Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile)
1623 if Ma == None:
1624 continue
1625 self.BuildModules.append(Ma)
1626 self._BuildPa(self.Target, Pa)
1627
1628 # Create MAP file when Load Fix Address is enabled.
1629 if self.Target in ["", "all", "fds"]:
1630 for Arch in Wa.ArchList:
1631 GlobalData.gGlobalDefines['ARCH'] = Arch
1632 #
1633 # Check whether the set fix address is above 4G for 32bit image.
1634 #
1635 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:
1636 EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platform with IA32 or ARM arch modules")
1637 #
1638 # Get Module List
1639 #
1640 ModuleList = {}
1641 for Pa in Wa.AutoGenObjectList:
1642 for Ma in Pa.ModuleAutoGenList:
1643 if Ma == None:
1644 continue
1645 if not Ma.IsLibrary:
1646 ModuleList[Ma.Guid.upper()] = Ma
1647
1648 MapBuffer = StringIO('')
1649 if self.LoadFixAddress != 0:
1650 #
1651 # Rebase module to the preferred memory address before GenFds
1652 #
1653 self._CollectModuleMapBuffer(MapBuffer, ModuleList)
1654 if self.Fdf:
1655 #
1656 # create FDS again for the updated EFI image
1657 #
1658 self._Build("fds", Wa)
1659 #
1660 # Create MAP file for all platform FVs after GenFds.
1661 #
1662 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)
1663 #
1664 # Save MAP buffer into MAP file.
1665 #
1666 self._SaveMapFile (MapBuffer, Wa)
1667
1668 ## Build active module for different build targets, different tool chains and different archs
1669 #
1670 def _BuildModule(self):
1671 for BuildTarget in self.BuildTargetList:
1672 GlobalData.gGlobalDefines['TARGET'] = BuildTarget
1673 for ToolChain in self.ToolChainList:
1674 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain
1675 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain
1676 #
1677 # module build needs platform build information, so get platform
1678 # AutoGen first
1679 #
1680 Wa = WorkspaceAutoGen(
1681 self.WorkspaceDir,
1682 self.PlatformFile,
1683 BuildTarget,
1684 ToolChain,
1685 self.ArchList,
1686 self.BuildDatabase,
1687 self.TargetTxt,
1688 self.ToolDef,
1689 self.Fdf,
1690 self.FdList,
1691 self.FvList,
1692 self.CapList,
1693 self.SkuId,
1694 self.UniFlag,
1695 self.Progress,
1696 self.ModuleFile
1697 )
1698 self.Fdf = Wa.FdfFile
1699 self.LoadFixAddress = Wa.Platform.LoadFixAddress
1700 Wa.CreateMakeFile(False)
1701 self.Progress.Stop("done!")
1702 MaList = []
1703 for Arch in Wa.ArchList:
1704 GlobalData.gGlobalDefines['ARCH'] = Arch
1705 Ma = ModuleAutoGen(Wa, self.ModuleFile, BuildTarget, ToolChain, Arch, self.PlatformFile)
1706 if Ma == None: continue
1707 MaList.append(Ma)
1708 self.BuildModules.append(Ma)
1709 if not Ma.IsBinaryModule:
1710 self._Build(self.Target, Ma, BuildModule=True)
1711
1712 self.BuildReport.AddPlatformReport(Wa, MaList)
1713 if MaList == []:
1714 EdkLogger.error(
1715 'build',
1716 BUILD_ERROR,
1717 "Module for [%s] is not a component of active platform."\
1718 " Please make sure that the ARCH and inf file path are"\
1719 " given in the same as in [%s]" % \
1720 (', '.join(Wa.ArchList), self.PlatformFile),
1721 ExtraData=self.ModuleFile
1722 )
1723 # Create MAP file when Load Fix Address is enabled.
1724 if self.Target == "fds" and self.Fdf:
1725 for Arch in Wa.ArchList:
1726 #
1727 # Check whether the set fix address is above 4G for 32bit image.
1728 #
1729 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:
1730 EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platorm with IA32 or ARM arch modules")
1731 #
1732 # Get Module List
1733 #
1734 ModuleList = {}
1735 for Pa in Wa.AutoGenObjectList:
1736 for Ma in Pa.ModuleAutoGenList:
1737 if Ma == None:
1738 continue
1739 if not Ma.IsLibrary:
1740 ModuleList[Ma.Guid.upper()] = Ma
1741
1742 MapBuffer = StringIO('')
1743 if self.LoadFixAddress != 0:
1744 #
1745 # Rebase module to the preferred memory address before GenFds
1746 #
1747 self._CollectModuleMapBuffer(MapBuffer, ModuleList)
1748 #
1749 # create FDS again for the updated EFI image
1750 #
1751 self._Build("fds", Wa)
1752 #
1753 # Create MAP file for all platform FVs after GenFds.
1754 #
1755 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)
1756 #
1757 # Save MAP buffer into MAP file.
1758 #
1759 self._SaveMapFile (MapBuffer, Wa)
1760
1761 ## Build a platform in multi-thread mode
1762 #
1763 def _MultiThreadBuildPlatform(self):
1764 SaveFileOnChange(self.PlatformBuildPath, '# DO NOT EDIT \n# FILE auto-generated\n', False)
1765 for BuildTarget in self.BuildTargetList:
1766 GlobalData.gGlobalDefines['TARGET'] = BuildTarget
1767 for ToolChain in self.ToolChainList:
1768 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain
1769 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain
1770 Wa = WorkspaceAutoGen(
1771 self.WorkspaceDir,
1772 self.PlatformFile,
1773 BuildTarget,
1774 ToolChain,
1775 self.ArchList,
1776 self.BuildDatabase,
1777 self.TargetTxt,
1778 self.ToolDef,
1779 self.Fdf,
1780 self.FdList,
1781 self.FvList,
1782 self.CapList,
1783 self.SkuId,
1784 self.UniFlag,
1785 self.Progress
1786 )
1787 self.Fdf = Wa.FdfFile
1788 self.LoadFixAddress = Wa.Platform.LoadFixAddress
1789 self.BuildReport.AddPlatformReport(Wa)
1790 Wa.CreateMakeFile(False)
1791
1792 # multi-thread exit flag
1793 ExitFlag = threading.Event()
1794 ExitFlag.clear()
1795 for Arch in Wa.ArchList:
1796 GlobalData.gGlobalDefines['ARCH'] = Arch
1797 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)
1798 if Pa == None:
1799 continue
1800 ModuleList = []
1801 for Inf in Pa.Platform.Modules:
1802 ModuleList.append(Inf)
1803 # Add the INF only list in FDF
1804 if GlobalData.gFdfParser != None:
1805 for InfName in GlobalData.gFdfParser.Profile.InfList:
1806 Inf = PathClass(NormPath(InfName), self.WorkspaceDir, Arch)
1807 if Inf in Pa.Platform.Modules:
1808 continue
1809 ModuleList.append(Inf)
1810 for Module in ModuleList:
1811 # Get ModuleAutoGen object to generate C code file and makefile
1812 Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile)
1813
1814 if Ma == None:
1815 continue
1816 # Not to auto-gen for targets 'clean', 'cleanlib', 'cleanall', 'run', 'fds'
1817 if self.Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1818 # for target which must generate AutoGen code and makefile
1819 if not self.SkipAutoGen or self.Target == 'genc':
1820 Ma.CreateCodeFile(True)
1821 if self.Target == "genc":
1822 continue
1823
1824 if not self.SkipAutoGen or self.Target == 'genmake':
1825 Ma.CreateMakeFile(True)
1826 if self.Target == "genmake":
1827 continue
1828 self.BuildModules.append(Ma)
1829 self.Progress.Stop("done!")
1830
1831 for Ma in self.BuildModules:
1832 # Generate build task for the module
1833 if not Ma.IsBinaryModule:
1834 Bt = BuildTask.New(ModuleMakeUnit(Ma, self.Target))
1835 # Break build if any build thread has error
1836 if BuildTask.HasError():
1837 # we need a full version of makefile for platform
1838 ExitFlag.set()
1839 BuildTask.WaitForComplete()
1840 Pa.CreateMakeFile(False)
1841 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
1842 # Start task scheduler
1843 if not BuildTask.IsOnGoing():
1844 BuildTask.StartScheduler(self.ThreadNumber, ExitFlag)
1845
1846 # in case there's an interruption. we need a full version of makefile for platform
1847 Pa.CreateMakeFile(False)
1848 if BuildTask.HasError():
1849 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
1850
1851 #
1852 # Save temp tables to a TmpTableDict.
1853 #
1854 for Key in Wa.BuildDatabase._CACHE_:
1855 if Wa.BuildDatabase._CACHE_[Key]._RawData and Wa.BuildDatabase._CACHE_[Key]._RawData._Table and Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table:
1856 if TemporaryTablePattern.match(Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table):
1857 TmpTableDict[Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table] = Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Cur
1858 #
1859 #
1860 # All modules have been put in build tasks queue. Tell task scheduler
1861 # to exit if all tasks are completed
1862 #
1863 ExitFlag.set()
1864 BuildTask.WaitForComplete()
1865 self.CreateAsBuiltInf()
1866
1867 #
1868 # Check for build error, and raise exception if one
1869 # has been signaled.
1870 #
1871 if BuildTask.HasError():
1872 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
1873
1874 # Create MAP file when Load Fix Address is enabled.
1875 if self.Target in ["", "all", "fds"]:
1876 for Arch in Wa.ArchList:
1877 #
1878 # Check whether the set fix address is above 4G for 32bit image.
1879 #
1880 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:
1881 EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platorm with IA32 or ARM arch modules")
1882 #
1883 # Get Module List
1884 #
1885 ModuleList = {}
1886 for Pa in Wa.AutoGenObjectList:
1887 for Ma in Pa.ModuleAutoGenList:
1888 if Ma == None:
1889 continue
1890 if not Ma.IsLibrary:
1891 ModuleList[Ma.Guid.upper()] = Ma
1892 #
1893 # Rebase module to the preferred memory address before GenFds
1894 #
1895 MapBuffer = StringIO('')
1896 if self.LoadFixAddress != 0:
1897 self._CollectModuleMapBuffer(MapBuffer, ModuleList)
1898
1899 if self.Fdf:
1900 #
1901 # Generate FD image if there's a FDF file found
1902 #
1903 LaunchCommand(Wa.GenFdsCommand, os.getcwd())
1904
1905 #
1906 # Create MAP file for all platform FVs after GenFds.
1907 #
1908 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)
1909 #
1910 # Save MAP buffer into MAP file.
1911 #
1912 self._SaveMapFile(MapBuffer, Wa)
1913
1914 ## Generate GuidedSectionTools.txt in the FV directories.
1915 #
1916 def CreateGuidedSectionToolsFile(self):
1917 for BuildTarget in self.BuildTargetList:
1918 for ToolChain in self.ToolChainList:
1919 Wa = WorkspaceAutoGen(
1920 self.WorkspaceDir,
1921 self.PlatformFile,
1922 BuildTarget,
1923 ToolChain,
1924 self.ArchList,
1925 self.BuildDatabase,
1926 self.TargetTxt,
1927 self.ToolDef,
1928 self.Fdf,
1929 self.FdList,
1930 self.FvList,
1931 self.CapList,
1932 self.SkuId,
1933 self.UniFlag
1934 )
1935 FvDir = Wa.FvDir
1936 if not os.path.exists(FvDir):
1937 continue
1938
1939 for Arch in self.ArchList:
1940 # Build up the list of supported architectures for this build
1941 prefix = '%s_%s_%s_' % (BuildTarget, ToolChain, Arch)
1942
1943 # Look through the tool definitions for GUIDed tools
1944 guidAttribs = []
1945 for (attrib, value) in self.ToolDef.ToolsDefTxtDictionary.iteritems():
1946 if attrib.upper().endswith('_GUID'):
1947 split = attrib.split('_')
1948 thisPrefix = '_'.join(split[0:3]) + '_'
1949 if thisPrefix == prefix:
1950 guid = self.ToolDef.ToolsDefTxtDictionary[attrib]
1951 guid = guid.lower()
1952 toolName = split[3]
1953 path = '_'.join(split[0:4]) + '_PATH'
1954 path = self.ToolDef.ToolsDefTxtDictionary[path]
1955 path = self.GetFullPathOfTool(path)
1956 guidAttribs.append((guid, toolName, path))
1957
1958 # Write out GuidedSecTools.txt
1959 toolsFile = os.path.join(FvDir, 'GuidedSectionTools.txt')
1960 toolsFile = open(toolsFile, 'wt')
1961 for guidedSectionTool in guidAttribs:
1962 print >> toolsFile, ' '.join(guidedSectionTool)
1963 toolsFile.close()
1964
1965 ## Returns the full path of the tool.
1966 #
1967 def GetFullPathOfTool (self, tool):
1968 if os.path.exists(tool):
1969 return os.path.realpath(tool)
1970 else:
1971 # We need to search for the tool using the
1972 # PATH environment variable.
1973 for dirInPath in os.environ['PATH'].split(os.pathsep):
1974 foundPath = os.path.join(dirInPath, tool)
1975 if os.path.exists(foundPath):
1976 return os.path.realpath(foundPath)
1977
1978 # If the tool was not found in the path then we just return
1979 # the input tool.
1980 return tool
1981
1982 ## Launch the module or platform build
1983 #
1984 def Launch(self):
1985 if not self.ModuleFile:
1986 if not self.SpawnMode or self.Target not in ["", "all"]:
1987 self.SpawnMode = False
1988 self._BuildPlatform()
1989 else:
1990 self._MultiThreadBuildPlatform()
1991 self.CreateGuidedSectionToolsFile()
1992 else:
1993 self.SpawnMode = False
1994 self._BuildModule()
1995
1996 if self.Target == 'cleanall':
1997 self.Db.Close()
1998 RemoveDirectory(os.path.dirname(GlobalData.gDatabasePath), True)
1999
2000 def CreateAsBuiltInf(self):
2001 for Module in self.BuildModules:
2002 Module.CreateAsBuiltInf()
2003 self.BuildModules = []
2004 ## Do some clean-up works when error occurred
2005 def Relinquish(self):
2006 OldLogLevel = EdkLogger.GetLevel()
2007 EdkLogger.SetLevel(EdkLogger.ERROR)
2008 #self.DumpBuildData()
2009 Utils.Progressor.Abort()
2010 if self.SpawnMode == True:
2011 BuildTask.Abort()
2012 EdkLogger.SetLevel(OldLogLevel)
2013
2014 def DumpBuildData(self):
2015 CacheDirectory = os.path.dirname(GlobalData.gDatabasePath)
2016 Utils.CreateDirectory(CacheDirectory)
2017 Utils.DataDump(Utils.gFileTimeStampCache, os.path.join(CacheDirectory, "gFileTimeStampCache"))
2018 Utils.DataDump(Utils.gDependencyDatabase, os.path.join(CacheDirectory, "gDependencyDatabase"))
2019
2020 def RestoreBuildData(self):
2021 FilePath = os.path.join(os.path.dirname(GlobalData.gDatabasePath), "gFileTimeStampCache")
2022 if Utils.gFileTimeStampCache == {} and os.path.isfile(FilePath):
2023 Utils.gFileTimeStampCache = Utils.DataRestore(FilePath)
2024 if Utils.gFileTimeStampCache == None:
2025 Utils.gFileTimeStampCache = {}
2026
2027 FilePath = os.path.join(os.path.dirname(GlobalData.gDatabasePath), "gDependencyDatabase")
2028 if Utils.gDependencyDatabase == {} and os.path.isfile(FilePath):
2029 Utils.gDependencyDatabase = Utils.DataRestore(FilePath)
2030 if Utils.gDependencyDatabase == None:
2031 Utils.gDependencyDatabase = {}
2032
2033 def ParseDefines(DefineList=[]):
2034 DefineDict = {}
2035 if DefineList != None:
2036 for Define in DefineList:
2037 DefineTokenList = Define.split("=", 1)
2038 if not GlobalData.gMacroNamePattern.match(DefineTokenList[0]):
2039 EdkLogger.error('build', FORMAT_INVALID,
2040 "The macro name must be in the pattern [A-Z][A-Z0-9_]*",
2041 ExtraData=DefineTokenList[0])
2042
2043 if len(DefineTokenList) == 1:
2044 DefineDict[DefineTokenList[0]] = "TRUE"
2045 else:
2046 DefineDict[DefineTokenList[0]] = DefineTokenList[1].strip()
2047 return DefineDict
2048
2049 gParamCheck = []
2050 def SingleCheckCallback(option, opt_str, value, parser):
2051 if option not in gParamCheck:
2052 setattr(parser.values, option.dest, value)
2053 gParamCheck.append(option)
2054 else:
2055 parser.error("Option %s only allows one instance in command line!" % option)
2056
2057 ## Parse command line options
2058 #
2059 # Using standard Python module optparse to parse command line option of this tool.
2060 #
2061 # @retval Opt A optparse.Values object containing the parsed options
2062 # @retval Args Target of build command
2063 #
2064 def MyOptionParser():
2065 Parser = OptionParser(description=__copyright__, version=__version__, prog="build.exe", usage="%prog [options] [all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]")
2066 Parser.add_option("-a", "--arch", action="append", type="choice", choices=['IA32', 'X64', 'IPF', 'EBC', 'ARM', 'AARCH64'], dest="TargetArch",
2067 help="ARCHS is one of list: IA32, X64, IPF, ARM, AARCH64 or EBC, which overrides target.txt's TARGET_ARCH definition. To specify more archs, please repeat this option.")
2068 Parser.add_option("-p", "--platform", action="callback", type="string", dest="PlatformFile", callback=SingleCheckCallback,
2069 help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.")
2070 Parser.add_option("-m", "--module", action="callback", type="string", dest="ModuleFile", callback=SingleCheckCallback,
2071 help="Build the module specified by the INF file name argument.")
2072 Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Using the TARGET to build the platform, overriding target.txt's TARGET definition.",
2073 action="append")
2074 Parser.add_option("-t", "--tagname", action="append", type="string", dest="ToolChain",
2075 help="Using the Tool Chain Tagname to build the platform, overriding target.txt's TOOL_CHAIN_TAG definition.")
2076 Parser.add_option("-x", "--sku-id", action="callback", type="string", dest="SkuId", callback=SingleCheckCallback,
2077 help="Using this name of SKU ID to build the platform, overriding SKUID_IDENTIFIER in DSC file.")
2078
2079 Parser.add_option("-n", action="callback", type="int", dest="ThreadNumber", callback=SingleCheckCallback,
2080 help="Build the platform using multi-threaded compiler. The value overrides target.txt's MAX_CONCURRENT_THREAD_NUMBER. Less than 2 will disable multi-thread builds.")
2081
2082 Parser.add_option("-f", "--fdf", action="callback", type="string", dest="FdfFile", callback=SingleCheckCallback,
2083 help="The name of the FDF file to use, which overrides the setting in the DSC file.")
2084 Parser.add_option("-r", "--rom-image", action="append", type="string", dest="RomImage", default=[],
2085 help="The name of FD to be generated. The name must be from [FD] section in FDF file.")
2086 Parser.add_option("-i", "--fv-image", action="append", type="string", dest="FvImage", default=[],
2087 help="The name of FV to be generated. The name must be from [FV] section in FDF file.")
2088 Parser.add_option("-C", "--capsule-image", action="append", type="string", dest="CapName", default=[],
2089 help="The name of Capsule to be generated. The name must be from [Capsule] section in FDF file.")
2090 Parser.add_option("-u", "--skip-autogen", action="store_true", dest="SkipAutoGen", help="Skip AutoGen step.")
2091 Parser.add_option("-e", "--re-parse", action="store_true", dest="Reparse", help="Re-parse all meta-data files.")
2092
2093 Parser.add_option("-c", "--case-insensitive", action="store_true", dest="CaseInsensitive", default=False, help="Don't check case of file name.")
2094
2095 Parser.add_option("-w", "--warning-as-error", action="store_true", dest="WarningAsError", help="Treat warning in tools as error.")
2096 Parser.add_option("-j", "--log", action="store", dest="LogFile", help="Put log in specified file as well as on console.")
2097
2098 Parser.add_option("-s", "--silent", action="store_true", type=None, dest="SilentMode",
2099 help="Make use of silent mode of (n)make.")
2100 Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.")
2101 Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed, "\
2102 "including library instances selected, final dependency expression, "\
2103 "and warning messages, etc.")
2104 Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.")
2105 Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".")
2106
2107 Parser.add_option("-y", "--report-file", action="store", dest="ReportFile", help="Create/overwrite the report to the specified filename.")
2108 Parser.add_option("-Y", "--report-type", action="append", type="choice", choices=['PCD', 'LIBRARY', 'FLASH', 'DEPEX', 'BUILD_FLAGS', 'FIXED_ADDRESS', 'EXECUTION_ORDER'], dest="ReportType", default=[],
2109 help="Flags that control the type of build report to generate. Must be one of: [PCD, LIBRARY, FLASH, DEPEX, BUILD_FLAGS, FIXED_ADDRESS, EXECUTION_ORDER]. "\
2110 "To specify more than one flag, repeat this option on the command line and the default flag set is [PCD, LIBRARY, FLASH, DEPEX, BUILD_FLAGS, FIXED_ADDRESS]")
2111 Parser.add_option("-F", "--flag", action="store", type="string", dest="Flag",
2112 help="Specify the specific option to parse EDK UNI file. Must be one of: [-c, -s]. -c is for EDK framework UNI file, and -s is for EDK UEFI UNI file. "\
2113 "This option can also be specified by setting *_*_*_BUILD_FLAGS in [BuildOptions] section of platform DSC. If they are both specified, this value "\
2114 "will override the setting in [BuildOptions] section of platform DSC.")
2115 Parser.add_option("-N", "--no-cache", action="store_true", dest="DisableCache", default=False, help="Disable build cache mechanism")
2116 Parser.add_option("--conf", action="store", type="string", dest="ConfDirectory", help="Specify the customized Conf directory.")
2117 Parser.add_option("--check-usage", action="store_true", dest="CheckUsage", default=False, help="Check usage content of entries listed in INF file.")
2118 Parser.add_option("--ignore-sources", action="store_true", dest="IgnoreSources", default=False, help="Focus to a binary build and ignore all source files")
2119 Parser.add_option("--pcd", action="append", dest="OptionPcd", help="Set PCD value by command line. Format: \"PcdName=Value\" ")
2120 Parser.add_option("-l", "--cmd-len", action="store", type="int", dest="CommandLength", help="Specify the maximum line length of build command. Default is 4096.")
2121
2122 (Opt, Args) = Parser.parse_args()
2123 return (Opt, Args)
2124
2125 ## Tool entrance method
2126 #
2127 # This method mainly dispatch specific methods per the command line options.
2128 # If no error found, return zero value so the caller of this tool can know
2129 # if it's executed successfully or not.
2130 #
2131 # @retval 0 Tool was successful
2132 # @retval 1 Tool failed
2133 #
2134 def Main():
2135 StartTime = time.time()
2136
2137 # Initialize log system
2138 EdkLogger.Initialize()
2139 GlobalData.gCommand = sys.argv[1:]
2140 #
2141 # Parse the options and args
2142 #
2143 (Option, Target) = MyOptionParser()
2144 GlobalData.gOptions = Option
2145 GlobalData.gCaseInsensitive = Option.CaseInsensitive
2146
2147 # Set log level
2148 if Option.verbose != None:
2149 EdkLogger.SetLevel(EdkLogger.VERBOSE)
2150 elif Option.quiet != None:
2151 EdkLogger.SetLevel(EdkLogger.QUIET)
2152 elif Option.debug != None:
2153 EdkLogger.SetLevel(Option.debug + 1)
2154 else:
2155 EdkLogger.SetLevel(EdkLogger.INFO)
2156
2157 if Option.LogFile != None:
2158 EdkLogger.SetLogFile(Option.LogFile)
2159
2160 if Option.WarningAsError == True:
2161 EdkLogger.SetWarningAsError()
2162
2163 if platform.platform().find("Windows") >= 0:
2164 GlobalData.gIsWindows = True
2165 else:
2166 GlobalData.gIsWindows = False
2167
2168 EdkLogger.quiet("Build environment: %s" % platform.platform())
2169 EdkLogger.quiet(time.strftime("Build start time: %H:%M:%S, %b.%d %Y\n", time.localtime()));
2170 ReturnCode = 0
2171 MyBuild = None
2172 BuildError = True
2173 try:
2174 if len(Target) == 0:
2175 Target = "all"
2176 elif len(Target) >= 2:
2177 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "More than one targets are not supported.",
2178 ExtraData="Please select one of: %s" % (' '.join(gSupportedTarget)))
2179 else:
2180 Target = Target[0].lower()
2181
2182 if Target not in gSupportedTarget:
2183 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "Not supported target [%s]." % Target,
2184 ExtraData="Please select one of: %s" % (' '.join(gSupportedTarget)))
2185
2186 #
2187 # Check environment variable: EDK_TOOLS_PATH, WORKSPACE, PATH
2188 #
2189 CheckEnvVariable()
2190 GlobalData.gCommandLineDefines.update(ParseDefines(Option.Macros))
2191
2192 Workspace = os.getenv("WORKSPACE")
2193 #
2194 # Get files real name in workspace dir
2195 #
2196 GlobalData.gAllFiles = Utils.DirCache(Workspace)
2197
2198 WorkingDirectory = os.getcwd()
2199 if not Option.ModuleFile:
2200 FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.inf')))
2201 FileNum = len(FileList)
2202 if FileNum >= 2:
2203 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "There are %d INF files in %s." % (FileNum, WorkingDirectory),
2204 ExtraData="Please use '-m <INF_FILE_PATH>' switch to choose one.")
2205 elif FileNum == 1:
2206 Option.ModuleFile = NormFile(FileList[0], Workspace)
2207
2208 if Option.ModuleFile:
2209 if os.path.isabs (Option.ModuleFile):
2210 if os.path.normcase (os.path.normpath(Option.ModuleFile)).find (Workspace) == 0:
2211 Option.ModuleFile = NormFile(os.path.normpath(Option.ModuleFile), Workspace)
2212 Option.ModuleFile = PathClass(Option.ModuleFile, Workspace)
2213 ErrorCode, ErrorInfo = Option.ModuleFile.Validate(".inf", False)
2214 if ErrorCode != 0:
2215 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)
2216
2217 if Option.PlatformFile != None:
2218 if os.path.isabs (Option.PlatformFile):
2219 if os.path.normcase (os.path.normpath(Option.PlatformFile)).find (Workspace) == 0:
2220 Option.PlatformFile = NormFile(os.path.normpath(Option.PlatformFile), Workspace)
2221 Option.PlatformFile = PathClass(Option.PlatformFile, Workspace)
2222
2223 if Option.FdfFile != None:
2224 if os.path.isabs (Option.FdfFile):
2225 if os.path.normcase (os.path.normpath(Option.FdfFile)).find (Workspace) == 0:
2226 Option.FdfFile = NormFile(os.path.normpath(Option.FdfFile), Workspace)
2227 Option.FdfFile = PathClass(Option.FdfFile, Workspace)
2228 ErrorCode, ErrorInfo = Option.FdfFile.Validate(".fdf", False)
2229 if ErrorCode != 0:
2230 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)
2231
2232 if Option.Flag != None and Option.Flag not in ['-c', '-s']:
2233 EdkLogger.error("build", OPTION_VALUE_INVALID, "UNI flag must be one of -c or -s")
2234
2235 MyBuild = Build(Target, Workspace, Option)
2236 GlobalData.gCommandLineDefines['ARCH'] = ' '.join(MyBuild.ArchList)
2237 if not (MyBuild.LaunchPrebuildFlag and os.path.exists(MyBuild.PlatformBuildPath)):
2238 MyBuild.Launch()
2239 # Drop temp tables to avoid database locked.
2240 for TmpTableName in TmpTableDict:
2241 SqlCommand = """drop table IF EXISTS %s""" % TmpTableName
2242 TmpTableDict[TmpTableName].execute(SqlCommand)
2243 #MyBuild.DumpBuildData()
2244 #
2245 # All job done, no error found and no exception raised
2246 #
2247 BuildError = False
2248 except FatalError, X:
2249 if MyBuild != None:
2250 # for multi-thread build exits safely
2251 MyBuild.Relinquish()
2252 if Option != None and Option.debug != None:
2253 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2254 ReturnCode = X.args[0]
2255 except Warning, X:
2256 # error from Fdf parser
2257 if MyBuild != None:
2258 # for multi-thread build exits safely
2259 MyBuild.Relinquish()
2260 if Option != None and Option.debug != None:
2261 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2262 else:
2263 EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError=False)
2264 ReturnCode = FORMAT_INVALID
2265 except KeyboardInterrupt:
2266 ReturnCode = ABORT_ERROR
2267 if Option != None and Option.debug != None:
2268 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2269 except:
2270 if MyBuild != None:
2271 # for multi-thread build exits safely
2272 MyBuild.Relinquish()
2273
2274 # try to get the meta-file from the object causing exception
2275 Tb = sys.exc_info()[-1]
2276 MetaFile = GlobalData.gProcessingFile
2277 while Tb != None:
2278 if 'self' in Tb.tb_frame.f_locals and hasattr(Tb.tb_frame.f_locals['self'], 'MetaFile'):
2279 MetaFile = Tb.tb_frame.f_locals['self'].MetaFile
2280 Tb = Tb.tb_next
2281 EdkLogger.error(
2282 "\nbuild",
2283 CODE_ERROR,
2284 "Unknown fatal error when processing [%s]" % MetaFile,
2285 ExtraData="\n(Please send email to edk2-devel@lists.01.org for help, attaching following call stack trace!)\n",
2286 RaiseError=False
2287 )
2288 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2289 ReturnCode = CODE_ERROR
2290 finally:
2291 Utils.Progressor.Abort()
2292 Utils.ClearDuplicatedInf()
2293
2294 if ReturnCode == 0:
2295 try:
2296 MyBuild.LanuchPostbuild()
2297 Conclusion = "Done"
2298 except:
2299 Conclusion = "Failed"
2300 elif ReturnCode == ABORT_ERROR:
2301 Conclusion = "Aborted"
2302 else:
2303 Conclusion = "Failed"
2304 FinishTime = time.time()
2305 BuildDuration = time.gmtime(int(round(FinishTime - StartTime)))
2306 BuildDurationStr = ""
2307 if BuildDuration.tm_yday > 1:
2308 BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration) + ", %d day(s)" % (BuildDuration.tm_yday - 1)
2309 else:
2310 BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration)
2311 if MyBuild != None:
2312 if not BuildError:
2313 MyBuild.BuildReport.GenerateReport(BuildDurationStr)
2314 MyBuild.Db.Close()
2315 EdkLogger.SetLevel(EdkLogger.QUIET)
2316 EdkLogger.quiet("\n- %s -" % Conclusion)
2317 EdkLogger.quiet(time.strftime("Build end time: %H:%M:%S, %b.%d %Y", time.localtime()))
2318 EdkLogger.quiet("Build total time: %s\n" % BuildDurationStr)
2319 return ReturnCode
2320
2321 if __name__ == '__main__':
2322 r = Main()
2323 ## 0-127 is a safe return range, and 1 is a standard default error
2324 if r < 0 or r > 127: r = 1
2325 sys.exit(r)
2326