2 # build a platform or a module
4 # Copyright (c) 2014, Hewlett-Packard Development Company, L.P.<BR>
5 # Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
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
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.
19 import Common
.LongFilePathOs
as os
27 import encodings
.ascii
31 from threading
import *
32 from optparse
import OptionParser
33 from subprocess
import *
34 from Common
import Misc
as Utils
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
47 from BuildReport
import BuildReport
48 from GenPatchPcdTable
.GenPatchPcdTable
import *
49 from PatchPcdValue
.PatchPcdValue
import *
51 import Common
.EdkLogger
52 import Common
.GlobalData
as GlobalData
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."
59 ## standard targets of build command
60 gSupportedTarget
= ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run']
62 ## build configuration file
63 gBuildConfiguration
= "target.txt"
64 gToolsDefinition
= "tools_def.txt"
66 TemporaryTablePattern
= re
.compile(r
'^_\d+_\d+_[a-fA-F0-9]+$')
69 ## Check environment PATH variable to make sure the specified tool is found
71 # If the tool is found in the PATH, then True is returned
72 # Otherwise, False is returned
74 def IsToolInPath(tool
):
75 if os
.environ
.has_key('PATHEXT'):
76 extns
= os
.environ
['PATHEXT'].split(os
.path
.pathsep
)
79 for pathDir
in os
.environ
['PATH'].split(os
.path
.pathsep
):
81 if os
.path
.exists(os
.path
.join(pathDir
, tool
+ ext
)):
85 ## Check environment variables
87 # Check environment variables that must be set for build. Currently they are
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
93 # If any of above environment variable is not set or has error, the build
96 def CheckEnvVariable():
98 if "WORKSPACE" not in os
.environ
:
99 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "Environment variable not found",
100 ExtraData
="WORKSPACE")
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
110 # set multiple workspace
111 PackagesPath
= os
.getenv("PACKAGES_PATH")
112 mws
.setWs(WorkspaceDir
, PackagesPath
)
115 # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP
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"]
125 # Unify case of characters on case-insensitive systems
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"]))
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"])
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
)
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
)
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
)
160 # check those variables on single workspace case
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
))
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")
179 if "PATH" not in os
.environ
:
180 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "Environment variable not found",
183 GlobalData
.gWorkspace
= WorkspaceDir
184 GlobalData
.gEfiSource
= EfiSourceDir
185 GlobalData
.gEdkSource
= EdkSourceDir
186 GlobalData
.gEcpSource
= EcpSourceDir
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"]
194 ## Get normalized file path
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.
199 # @param FilePath File path to be normalized
200 # @param Workspace Workspace path which the FilePath will be checked against
202 # @retval string The normalized file path
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
)
209 FileFullPath
= os
.path
.normpath(mws
.join(Workspace
, FilePath
))
210 Workspace
= mws
.getWs(Workspace
, FilePath
)
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
)
216 # remove workspace directory from the beginning part of the file path
217 if Workspace
[-1] in ["\\", "/"]:
218 return FileFullPath
[len(Workspace
):]
220 return FileFullPath
[(len(Workspace
) + 1):]
222 ## Get the output of an external program
224 # This is the entrance method of thread reading output of an external program and
225 # putting them in STDOUT/STDERR of current program.
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
231 def ReadMessage(From
, To
, ExitFlag
):
233 # read one line a time
234 Line
= From
.readline()
235 # empty string means "end"
236 if Line
!= None and Line
!= "":
243 ## Launch an external program
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
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
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
)
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()
267 EndOfProcedure
= None
270 Proc
= Popen(Command
, stdout
=PIPE
, stderr
=PIPE
, env
=os
.environ
, cwd
=WorkingDir
, bufsize
=-1)
272 # launch two threads to read the STDOUT and STDERR
273 EndOfProcedure
= Event()
274 EndOfProcedure
.clear()
276 StdOutThread
= Thread(target
=ReadMessage
, args
=(Proc
.stdout
, EdkLogger
.info
, EndOfProcedure
))
277 StdOutThread
.setName("STDOUT-Redirector")
278 StdOutThread
.setDaemon(False)
282 StdErrThread
= Thread(target
=ReadMessage
, args
=(Proc
.stderr
, EdkLogger
.quiet
, EndOfProcedure
))
283 StdErrThread
.setName("STDERR-Redirector")
284 StdErrThread
.setDaemon(False)
287 # waiting for program exit
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:
295 if type(Command
) != type(""):
296 Command
= " ".join(Command
)
297 EdkLogger
.error("build", COMMAND_FAILURE
, "Failed to start command", ExtraData
="%s [%s]" % (Command
, WorkingDir
))
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
):
312 RespContent
= f
.read()
314 EdkLogger
.info(RespContent
)
316 EdkLogger
.error("build", COMMAND_FAILURE
, ExtraData
="%s [%s]" % (Command
, WorkingDir
))
318 ## The smallest unit that can be built in multi-thread build mode
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
324 # Currently the "Obj" should be only ModuleAutoGen or PlatformAutoGen objects.
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
335 def __init__(self
, Obj
, BuildCommand
, Target
, Dependency
, WorkingDir
="."):
336 self
.BuildObject
= Obj
337 self
.Dependency
= Dependency
338 self
.WorkingDir
= WorkingDir
340 self
.BuildCommand
= 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
),
351 # It just returns the string representation of self.BuildObject
353 # @param self The object pointer
356 return str(self
.BuildObject
)
358 ## "==" operator method
360 # It just compares self.BuildObject with "Other". So self.BuildObject must
361 # provide its own __eq__() method.
363 # @param self The object pointer
364 # @param Other The other BuildUnit object compared to
366 def __eq__(self
, Other
):
367 return Other
!= None and self
.BuildObject
== Other
.BuildObject \
368 and self
.BuildObject
.Arch
== Other
.BuildObject
.Arch
372 # It just returns the hash value of self.BuildObject which must be hashable.
374 # @param self The object pointer
377 return hash(self
.BuildObject
) + hash(self
.BuildObject
.Arch
)
380 return repr(self
.BuildObject
)
382 ## The smallest module unit that can be built by nmake/make command in multi-thread build mode
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.
388 # Currently the "Obj" should be only ModuleAutoGen object.
390 class ModuleMakeUnit(BuildUnit
):
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
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"
403 ## The smallest platform unit that can be built by nmake/make command in multi-thread build mode
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.
409 # Currently the "Obj" should be only PlatformAutoGen object.
411 class PlatformMakeUnit(BuildUnit
):
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
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
)
423 ## The class representing the task of a module build or platform build
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.
429 # queue for tasks waiting for schedule
430 _PendingQueue
= sdict()
431 _PendingQueueLock
= threading
.Lock()
433 # queue for tasks ready for running
434 _ReadyQueue
= sdict()
435 _ReadyQueueLock
= threading
.Lock()
437 # queue for run tasks
438 _RunningQueue
= sdict()
439 _RunningQueueLock
= threading
.Lock()
441 # queue containing all build tasks, in case duplicate build
444 # flag indicating error occurs in a running thread
445 _ErrorFlag
= threading
.Event()
449 # BoundedSemaphore object used to control the number of running threads
452 # flag indicating if the scheduler is started or not
453 _SchedulerStopped
= threading
.Event()
454 _SchedulerStopped
.set()
456 ## Start the task scheduler thread
458 # @param MaxThreadNumber The maximum thread number
459 # @param ExitFlag Flag used to end the scheduler
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():
473 # @param MaxThreadNumber The maximum thread number
474 # @param ExitFlag Flag used to end the scheduler
477 def Scheduler(MaxThreadNumber
, ExitFlag
):
478 BuildTask
._SchedulerStopped
.clear()
480 # use BoundedSemaphore to control the maximum running threads
481 BuildTask
._Thread
= BoundedSemaphore(MaxThreadNumber
)
483 # scheduling loop, which will exits when no pending/ready task and
484 # indicated to do so, or there's error in running thread
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
)))
491 # get all pending tasks
492 BuildTask
._PendingQueueLock
.acquire()
493 BuildObjectList
= BuildTask
._PendingQueue
.keys()
495 # check if their dependency is resolved, and if true, move them
498 for BuildObject
in BuildObjectList
:
499 Bt
= BuildTask
._PendingQueue
[BuildObject
]
501 BuildTask
._ReadyQueue
[BuildObject
] = BuildTask
._PendingQueue
.pop(BuildObject
)
502 BuildTask
._PendingQueueLock
.release()
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:
510 # wait for active thread(s) exit
511 BuildTask
._Thread
.acquire(True)
513 # start a new build thread
514 Bo
= BuildTask
._ReadyQueue
.keys()[0]
515 Bt
= BuildTask
._ReadyQueue
.pop(Bo
)
517 # move into running queue
518 BuildTask
._RunningQueueLock
.acquire()
519 BuildTask
._RunningQueue
[Bo
] = Bt
520 BuildTask
._RunningQueueLock
.release()
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()]))
538 except BaseException
, X
:
540 # TRICK: hide the output of threads left runing, so that the user can
541 # catch the error message easily
543 EdkLogger
.SetLevel(EdkLogger
.ERROR
)
544 BuildTask
._ErrorFlag
.set()
545 BuildTask
._ErrorMessage
= "build thread scheduler error\n\t%s" % str(X
)
547 BuildTask
._PendingQueue
.clear()
548 BuildTask
._ReadyQueue
.clear()
549 BuildTask
._RunningQueue
.clear()
550 BuildTask
._TaskQueue
.clear()
551 BuildTask
._SchedulerStopped
.set()
553 ## Wait for all running method exit
556 def WaitForComplete():
557 BuildTask
._SchedulerStopped
.wait()
559 ## Check if the scheduler is running or not
563 return not BuildTask
._SchedulerStopped
.isSet()
568 if BuildTask
.IsOnGoing():
569 BuildTask
._ErrorFlag
.set()
570 BuildTask
.WaitForComplete()
572 ## Check if there's error in running thread
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.
579 return BuildTask
._ErrorFlag
.isSet()
581 ## Get error message in running thread
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.
587 def GetErrorMessage():
588 return BuildTask
._ErrorMessage
590 ## Factory method to create a BuildTask object
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.
597 # @param BuildItem A BuildUnit object representing a build object
598 # @param Dependency The dependent build object of BuildItem
601 def New(BuildItem
, Dependency
=None):
602 if BuildItem
in BuildTask
._TaskQueue
:
603 Bt
= BuildTask
._TaskQueue
[BuildItem
]
607 Bt
._Init
(BuildItem
, Dependency
)
608 BuildTask
._TaskQueue
[BuildItem
] = Bt
610 BuildTask
._PendingQueueLock
.acquire()
611 BuildTask
._PendingQueue
[BuildItem
] = Bt
612 BuildTask
._PendingQueueLock
.release()
616 ## The real constructor of BuildTask
618 # @param BuildItem A BuildUnit object representing a build object
619 # @param Dependency The dependent build object of BuildItem
621 def _Init(self
, BuildItem
, Dependency
=None):
622 self
.BuildItem
= BuildItem
624 self
.DependencyList
= []
625 if Dependency
== None:
626 Dependency
= BuildItem
.Dependency
628 Dependency
.extend(BuildItem
.Dependency
)
629 self
.AddDependency(Dependency
)
630 # flag indicating build completes, used to avoid unnecessary re-build
631 self
.CompleteFlag
= False
633 ## Check if all dependent build tasks are completed or not
637 for Dep
in self
.DependencyList
:
638 if Dep
.CompleteFlag
== True:
645 ## Add dependent build task
647 # @param Dependency The list of dependent build objects
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
654 ## The thread wrapper of LaunchCommand function
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
659 def _CommandThread(self
, Command
, WorkingDir
):
661 LaunchCommand(Command
, WorkingDir
)
662 self
.CompleteFlag
= True
665 # TRICK: hide the output of threads left runing, so that the user can
666 # catch the error message easily
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
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()
684 ## Start build task thread
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()
694 ## The class contains the information related to EFI image
699 # Constructor will load all required image information.
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
708 def __init__(self
, BaseName
, Guid
, Arch
, OutputDir
, DebugDir
, ImageClass
):
709 self
.BaseName
= BaseName
712 self
.OutputDir
= OutputDir
713 self
.DebugDir
= DebugDir
714 self
.Image
= ImageClass
715 self
.Image
.Size
= (self
.Image
.Size
/ 0x1000 + 1) * 0x1000
717 ## The class implementing the EDK2 build process
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
730 # Constructor will load all necessary configurations, parse platform, modules
731 # and packages and the establish a database for AutoGen.
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
737 def __init__(self
, Target
, WorkspaceDir
, BuildOptions
):
738 self
.WorkspaceDir
= WorkspaceDir
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
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
)
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
)
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
))
777 if BuildOptions
.DisableCache
:
778 self
.Db
= WorkspaceDatabase(":memory:")
780 self
.Db
= WorkspaceDatabase(GlobalData
.gDatabasePath
, self
.Reparse
)
781 self
.BuildDatabase
= self
.Db
.BuildObject
783 self
.LoadFixAddress
= 0
784 self
.UniFlag
= BuildOptions
.Flag
785 self
.BuildModules
= []
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
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"]))))
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
)):
821 os
.chdir(self
.WorkspaceDir
)
823 ## Load configuration
825 # This method will parse target.txt and get the build configurations.
827 def LoadConfiguration(self
):
829 # Check target.txt and tools_def.txt and Init them
831 BuildConfigurationFile
= os
.path
.normpath(os
.path
.join(GlobalData
.gConfDirectory
, gBuildConfiguration
))
832 if os
.path
.isfile(BuildConfigurationFile
) == True:
833 StatusCode
= self
.TargetTxt
.LoadTargetTxtFile(BuildConfigurationFile
)
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
)
842 EdkLogger
.error("build", FILE_NOT_FOUND
, ExtraData
=ToolDefinitionFile
)
844 EdkLogger
.error("build", FILE_NOT_FOUND
, ExtraData
=BuildConfigurationFile
)
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
)
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
]
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")
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
)
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
))
873 self
.ToolChainList
= NewToolChainList
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
880 self
.ThreadNumber
= int(self
.ThreadNumber
, 0)
882 if self
.ThreadNumber
== 0:
883 self
.ThreadNumber
= 1
885 if not self
.PlatformFile
:
886 PlatformFile
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_ACTIVE_PLATFORM
]
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
)
893 EdkLogger
.error("build", OPTION_MISSING
,
894 ExtraData
="There are %d DSC files in %s. Use '-p' to specify one.\n" % (FileNum
, WorkingDirectory
))
896 PlatformFile
= FileList
[0]
898 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
,
899 ExtraData
="No active platform specified in target.txt or command line! Nothing can be built.\n")
901 self
.PlatformFile
= PathClass(NormFile(PlatformFile
, self
.WorkspaceDir
), self
.WorkspaceDir
)
903 ## Initialize build configuration
905 # This method will parse DSC file and merge the configurations from
906 # command line and target.txt, then get the final build configurations.
909 # parse target.txt, tools_def.txt, and platform file
910 self
.LoadConfiguration()
912 # Allow case-insensitive for those from command line or configuration file
913 ErrorCode
, ErrorInfo
= self
.PlatformFile
.Validate(".dsc", False)
915 EdkLogger
.error("build", ErrorCode
, ExtraData
=ErrorInfo
)
917 # create metafile database
919 self
.Db
.InitDatabase()
921 def InitPreBuild(self
):
922 self
.LoadConfiguration()
923 if self
.BuildTargetList
:
924 GlobalData
.gGlobalDefines
['TARGET'] = self
.BuildTargetList
[0]
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')
933 self
.Db
.InitDatabase()
935 Platform
= self
.Db
._MapPlatform
(str(self
.PlatformFile
))
936 self
.Prebuild
= str(Platform
.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()
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]))
949 def InitPostBuild(self
):
950 if 'POSTBUILD' in GlobalData
.gCommandLineDefines
.keys():
951 self
.Postbuild
= GlobalData
.gCommandLineDefines
.get('POSTBUILD')
953 Platform
= self
.Db
._MapPlatform
(str(self
.PlatformFile
))
954 self
.Postbuild
= str(Platform
.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()
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]))
967 def PassCommandOption(self
, BuildTarget
, TargetArch
, ToolChain
):
969 if GlobalData
.gCommand
and isinstance(GlobalData
.gCommand
, list):
970 BuildStr
+= ' ' + ' '.join(GlobalData
.gCommand
)
973 ToolChainFlag
= False
975 if GlobalData
.gOptions
and not GlobalData
.gOptions
.BuildTarget
:
977 if GlobalData
.gOptions
and not GlobalData
.gOptions
.TargetArch
:
979 if GlobalData
.gOptions
and not GlobalData
.gOptions
.ToolChain
:
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
1000 def LaunchPrebuild(self
):
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
)
1013 args
= ' && '.join((self
.Prebuild
, 'env > ' + PrebuildEnvFile
))
1014 Process
= Popen(args
, stdout
=PIPE
, stderr
=PIPE
, shell
=True, executable
="/bin/bash")
1016 # launch two threads to read the STDOUT and STDERR
1017 EndOfProcedure
= Event()
1018 EndOfProcedure
.clear()
1020 StdOutThread
= Thread(target
=ReadMessage
, args
=(Process
.stdout
, EdkLogger
.info
, EndOfProcedure
))
1021 StdOutThread
.setName("STDOUT-Redirector")
1022 StdOutThread
.setDaemon(False)
1023 StdOutThread
.start()
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
1037 if Process
.returncode
!= 0 :
1038 EdkLogger
.error("Prebuild", PREBUILD_ERROR
, 'Prebuild process is not success!')
1040 if os
.path
.exists(PrebuildEnvFile
):
1041 f
= open(PrebuildEnvFile
)
1042 envs
= f
.readlines()
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")
1050 def LanuchPostbuild(self
):
1052 EdkLogger
.info("\n- Postbuild Start -\n")
1053 if sys
.platform
== "win32":
1054 Process
= Popen(self
.Postbuild
, stdout
=PIPE
, stderr
=PIPE
)
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()
1061 StdOutThread
= Thread(target
=ReadMessage
, args
=(Process
.stdout
, EdkLogger
.info
, EndOfProcedure
))
1062 StdOutThread
.setName("STDOUT-Redirector")
1063 StdOutThread
.setDaemon(False)
1064 StdOutThread
.start()
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
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
1083 # Create autogen code and makefile for a module or platform, and the launch
1084 # "make" command to build it
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
1097 def _BuildPa(self
, Target
, AutoGenObject
, CreateDepsCodeFile
=True, CreateDepsMakeFile
=True, BuildModule
=False):
1098 if AutoGenObject
== None:
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":
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":
1118 # always recreate top/platform makefile when clean, just in case of inconsistency
1119 AutoGenObject
.CreateCodeFile(False)
1120 AutoGenObject
.CreateMakeFile(False)
1122 if EdkLogger
.GetLevel() == EdkLogger
.QUIET
:
1123 EdkLogger
.quiet("Building ... %s" % repr(AutoGenObject
))
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
))
1133 makefile
= GenMake
.BuildFile(AutoGenObject
)._FILE
_NAME
_[GenMake
.gMakeType
]
1137 RunDir
= os
.path
.normpath(os
.path
.join(AutoGenObject
.BuildDir
, GlobalData
.gGlobalDefines
['ARCH']))
1138 Command
= '.\SecMain'
1140 LaunchCommand(Command
, RunDir
)
1145 BuildCommand
= BuildCommand
+ [Target
]
1146 LaunchCommand(BuildCommand
, AutoGenObject
.MakeFileDir
)
1147 self
.CreateAsBuiltInf()
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
)
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()
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
)
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
)
1192 if Target
== 'cleanall':
1194 #os.rmdir(AutoGenObject.BuildDir)
1195 RemoveDirectory(AutoGenObject
.BuildDir
, True)
1196 except WindowsError, X
:
1197 EdkLogger
.error("build", FILE_DELETE_FAILURE
, ExtraData
=str(X
))
1200 ## Build a module or platform
1202 # Create autogen code and makefile for a module or platform, and the launch
1203 # "make" command to build it
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
1216 def _Build(self
, Target
, AutoGenObject
, CreateDepsCodeFile
=True, CreateDepsMakeFile
=True, BuildModule
=False):
1217 if AutoGenObject
== None:
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":
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":
1238 # always recreate top/platform makefile when clean, just in case of inconsistency
1239 AutoGenObject
.CreateCodeFile(False)
1240 AutoGenObject
.CreateMakeFile(False)
1242 if EdkLogger
.GetLevel() == EdkLogger
.QUIET
:
1243 EdkLogger
.quiet("Building ... %s" % repr(AutoGenObject
))
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
))
1256 BuildCommand
= BuildCommand
+ [Target
]
1257 LaunchCommand(BuildCommand
, AutoGenObject
.MakeFileDir
)
1258 self
.CreateAsBuiltInf()
1263 LaunchCommand(AutoGenObject
.GenFdsCommand
, AutoGenObject
.MakeFileDir
)
1268 RunDir
= os
.path
.normpath(os
.path
.join(AutoGenObject
.BuildDir
, GlobalData
.gGlobalDefines
['ARCH']))
1269 Command
= '.\SecMain'
1271 LaunchCommand(Command
, RunDir
)
1275 if Target
== 'libraries':
1282 if Target
== 'cleanall':
1284 #os.rmdir(AutoGenObject.BuildDir)
1285 RemoveDirectory(AutoGenObject
.BuildDir
, True)
1286 except WindowsError, X
:
1287 EdkLogger
.error("build", FILE_DELETE_FAILURE
, ExtraData
=str(X
))
1290 ## Rebase module image and Get function address for the input module list.
1292 def _RebaseModule (self
, MapBuffer
, BaseAddress
, ModuleList
, AddrIsOffset
= True, ModeIsSmm
= False):
1294 AddrIsOffset
= False
1295 InfFileNameList
= ModuleList
.keys()
1296 #InfFileNameList.sort()
1297 for InfFile
in InfFileNameList
:
1298 sys
.stdout
.write (".")
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.
1306 BaseAddress
= BaseAddress
- ModuleInfo
.Image
.Size
1308 # Update Image to new BaseAddress by GenFw tool
1310 LaunchCommand(["GenFw", "--rebase", str(BaseAddress
), "-r", ModuleOutputImage
], ModuleInfo
.OutputDir
)
1311 LaunchCommand(["GenFw", "--rebase", str(BaseAddress
), "-r", ModuleDebugImage
], ModuleInfo
.DebugDir
)
1314 # Set new address to the section header only for SMM driver.
1316 LaunchCommand(["GenFw", "--address", str(BaseAddress
), "-r", ModuleOutputImage
], ModuleInfo
.OutputDir
)
1317 LaunchCommand(["GenFw", "--address", str(BaseAddress
), "-r", ModuleDebugImage
], ModuleInfo
.DebugDir
)
1319 # Collect funtion address from Map file
1321 ImageMapTable
= ModuleOutputImage
.replace('.efi', '.map')
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:
1330 # Get the preferred address set on link time.
1332 if LinStr
.find ('Preferred load address is') != -1:
1333 StrList
= LinStr
.split()
1334 OrigImageBaseAddress
= int (StrList
[len(StrList
) - 1], 16)
1336 StrList
= LinStr
.split()
1337 if len (StrList
) > 4:
1338 if StrList
[3] == 'f' or StrList
[3] == 'F':
1340 RelativeAddress
= int (StrList
[2], 16) - OrigImageBaseAddress
1341 FunctionList
.append ((Name
, RelativeAddress
))
1342 if ModuleInfo
.Arch
== 'IPF' and Name
.endswith('_ModuleEntryPoint'):
1344 # Get the real entry point address for IPF image.
1346 ModuleInfo
.Image
.EntryPoint
= RelativeAddress
1349 # Add general information.
1352 MapBuffer
.write('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName
, BaseAddress
, BaseAddress
+ ModuleInfo
.Image
.EntryPoint
))
1354 MapBuffer
.write('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName
, 0 - BaseAddress
, 0 - (BaseAddress
+ ModuleInfo
.Image
.EntryPoint
)))
1356 MapBuffer
.write('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName
, BaseAddress
, BaseAddress
+ ModuleInfo
.Image
.EntryPoint
))
1358 # Add guid and general seciton section.
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]
1368 MapBuffer
.write('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo
.Guid
, 0 - (BaseAddress
+ TextSectionAddress
), 0 - (BaseAddress
+ DataSectionAddress
)))
1370 MapBuffer
.write('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo
.Guid
, BaseAddress
+ TextSectionAddress
, BaseAddress
+ DataSectionAddress
))
1372 # Add debug image full path.
1374 MapBuffer
.write('(IMAGE=%s)\n\n' % (ModuleDebugImage
))
1376 # Add funtion address
1378 for Function
in FunctionList
:
1380 MapBuffer
.write(' -0x%010X %s\n' % (0 - (BaseAddress
+ Function
[1]), Function
[0]))
1382 MapBuffer
.write(' 0x%010X %s\n' % (BaseAddress
+ Function
[1], Function
[0]))
1386 # for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1389 BaseAddress
= BaseAddress
+ ModuleInfo
.Image
.Size
1391 ## Collect MAP information of all FVs
1393 def _CollectFvMapBuffer (self
, MapBuffer
, Wa
, ModuleList
):
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
):
1402 FvMap
= open(FvMapBuffer
, 'r')
1403 #skip FV size information
1409 MatchGuid
= GuidPattern
.match(Line
)
1410 if MatchGuid
!= None:
1412 # Replace GUID with module name
1414 GuidString
= MatchGuid
.group()
1415 if GuidString
.upper() in ModuleList
:
1416 Line
= Line
.replace(GuidString
, ModuleList
[GuidString
.upper()].Name
)
1417 MapBuffer
.write('%s' % (Line
))
1419 # Add the debug image full path.
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')))
1429 ## Collect MAP information of all modules
1431 def _CollectModuleMapBuffer (self
, MapBuffer
, ModuleList
):
1432 sys
.stdout
.write ("Generate Load Module At Fix Address Map")
1434 PatchEfiImageList
= []
1442 # reserve 4K size in SMRAM to make SMM module address not from 0.
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
)
1451 OutputImageFile
= ''
1452 for ResultFile
in Module
.CodaTargetList
:
1453 if str(ResultFile
.Target
).endswith('.efi'):
1455 # module list for PEI, DXE, RUNTIME and SMM
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
1487 # EFI image is final target.
1488 # Check EFI image contains patchable FixAddress related PCDs.
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
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
1502 if not ModuleIsPatch
:
1505 # Module includes the patchable load fix address PCDs.
1506 # It will be fixed up later.
1508 PatchEfiImageList
.append (OutputImageFile
)
1511 # Get Top Memory address
1513 ReservedRuntimeMemorySize
= 0
1514 TopMemoryAddress
= 0
1515 if self
.LoadFixAddress
== 0xFFFFFFFFFFFFFFFF:
1516 TopMemoryAddress
= 0
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.
1523 ReservedRuntimeMemorySize
= TopMemoryAddress
% 0x2000
1524 RtSize
= RtSize
+ ReservedRuntimeMemorySize
1527 # Patch FixAddress related PCDs into EFI image
1529 for EfiImage
in PatchEfiImageList
:
1530 EfiImageMap
= EfiImage
.replace('.efi', '.map')
1531 if not os
.path
.exists(EfiImageMap
):
1534 # Get PCD offset in EFI image by GenPatchPcdTable function
1536 PcdTable
= parsePcdInfoFromMapFile(EfiImageMap
, EfiImage
)
1538 # Patch real PCD value by PatchPcdValue tool
1540 for PcdInfo
in PcdTable
:
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
)
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))
1559 PeiBaseAddr
= TopMemoryAddress
- RtSize
- BtSize
1560 BtBaseAddr
= TopMemoryAddress
- RtSize
1561 RtBaseAddr
= TopMemoryAddress
- ReservedRuntimeMemorySize
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")
1571 ## Save platform Map file
1573 def _SaveMapFile (self
, MapBuffer
, Wa
):
1575 # Map file path is got.
1577 MapFilePath
= os
.path
.join(Wa
.BuildDir
, Wa
.Name
+ '.map')
1579 # Save address map into MAP file.
1581 SaveFileOnChange(MapFilePath
, MapBuffer
.getvalue(), False)
1583 if self
.LoadFixAddress
!= 0:
1584 sys
.stdout
.write ("\nLoad Module At Fix Address Map file can be found at %s\n" % (MapFilePath
))
1587 ## Build active platform for different build targets and different tool chains
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(
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
)
1625 self
.BuildModules
.append(Ma
)
1626 self
._BuildPa
(self
.Target
, Pa
)
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
1633 # Check whether the set fix address is above 4G for 32bit image.
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")
1641 for Pa
in Wa
.AutoGenObjectList
:
1642 for Ma
in Pa
.ModuleAutoGenList
:
1645 if not Ma
.IsLibrary
:
1646 ModuleList
[Ma
.Guid
.upper()] = Ma
1648 MapBuffer
= StringIO('')
1649 if self
.LoadFixAddress
!= 0:
1651 # Rebase module to the preferred memory address before GenFds
1653 self
._CollectModuleMapBuffer
(MapBuffer
, ModuleList
)
1656 # create FDS again for the updated EFI image
1658 self
._Build
("fds", Wa
)
1660 # Create MAP file for all platform FVs after GenFds.
1662 self
._CollectFvMapBuffer
(MapBuffer
, Wa
, ModuleList
)
1664 # Save MAP buffer into MAP file.
1666 self
._SaveMapFile
(MapBuffer
, Wa
)
1668 ## Build active module for different build targets, different tool chains and different archs
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
1677 # module build needs platform build information, so get platform
1680 Wa
= WorkspaceAutoGen(
1698 self
.Fdf
= Wa
.FdfFile
1699 self
.LoadFixAddress
= Wa
.Platform
.LoadFixAddress
1700 Wa
.CreateMakeFile(False)
1701 self
.Progress
.Stop("done!")
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
1708 self
.BuildModules
.append(Ma
)
1709 if not Ma
.IsBinaryModule
:
1710 self
._Build
(self
.Target
, Ma
, BuildModule
=True)
1712 self
.BuildReport
.AddPlatformReport(Wa
, MaList
)
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
1723 # Create MAP file when Load Fix Address is enabled.
1724 if self
.Target
== "fds" and self
.Fdf
:
1725 for Arch
in Wa
.ArchList
:
1727 # Check whether the set fix address is above 4G for 32bit image.
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")
1735 for Pa
in Wa
.AutoGenObjectList
:
1736 for Ma
in Pa
.ModuleAutoGenList
:
1739 if not Ma
.IsLibrary
:
1740 ModuleList
[Ma
.Guid
.upper()] = Ma
1742 MapBuffer
= StringIO('')
1743 if self
.LoadFixAddress
!= 0:
1745 # Rebase module to the preferred memory address before GenFds
1747 self
._CollectModuleMapBuffer
(MapBuffer
, ModuleList
)
1749 # create FDS again for the updated EFI image
1751 self
._Build
("fds", Wa
)
1753 # Create MAP file for all platform FVs after GenFds.
1755 self
._CollectFvMapBuffer
(MapBuffer
, Wa
, ModuleList
)
1757 # Save MAP buffer into MAP file.
1759 self
._SaveMapFile
(MapBuffer
, Wa
)
1761 ## Build a platform in multi-thread mode
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(
1787 self
.Fdf
= Wa
.FdfFile
1788 self
.LoadFixAddress
= Wa
.Platform
.LoadFixAddress
1789 self
.BuildReport
.AddPlatformReport(Wa
)
1790 Wa
.CreateMakeFile(False)
1792 # multi-thread exit flag
1793 ExitFlag
= threading
.Event()
1795 for Arch
in Wa
.ArchList
:
1796 GlobalData
.gGlobalDefines
['ARCH'] = Arch
1797 Pa
= PlatformAutoGen(Wa
, self
.PlatformFile
, BuildTarget
, ToolChain
, Arch
)
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
:
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
)
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":
1824 if not self
.SkipAutoGen
or self
.Target
== 'genmake':
1825 Ma
.CreateMakeFile(True)
1826 if self
.Target
== "genmake":
1828 self
.BuildModules
.append(Ma
)
1829 self
.Progress
.Stop("done!")
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
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
)
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
)
1852 # Save temp tables to a TmpTableDict.
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
1860 # All modules have been put in build tasks queue. Tell task scheduler
1861 # to exit if all tasks are completed
1864 BuildTask
.WaitForComplete()
1865 self
.CreateAsBuiltInf()
1868 # Check for build error, and raise exception if one
1869 # has been signaled.
1871 if BuildTask
.HasError():
1872 EdkLogger
.error("build", BUILD_ERROR
, "Failed to build module", ExtraData
=GlobalData
.gBuildingModule
)
1874 # Create MAP file when Load Fix Address is enabled.
1875 if self
.Target
in ["", "all", "fds"]:
1876 for Arch
in Wa
.ArchList
:
1878 # Check whether the set fix address is above 4G for 32bit image.
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")
1886 for Pa
in Wa
.AutoGenObjectList
:
1887 for Ma
in Pa
.ModuleAutoGenList
:
1890 if not Ma
.IsLibrary
:
1891 ModuleList
[Ma
.Guid
.upper()] = Ma
1893 # Rebase module to the preferred memory address before GenFds
1895 MapBuffer
= StringIO('')
1896 if self
.LoadFixAddress
!= 0:
1897 self
._CollectModuleMapBuffer
(MapBuffer
, ModuleList
)
1901 # Generate FD image if there's a FDF file found
1903 LaunchCommand(Wa
.GenFdsCommand
, os
.getcwd())
1906 # Create MAP file for all platform FVs after GenFds.
1908 self
._CollectFvMapBuffer
(MapBuffer
, Wa
, ModuleList
)
1910 # Save MAP buffer into MAP file.
1912 self
._SaveMapFile
(MapBuffer
, Wa
)
1914 ## Generate GuidedSectionTools.txt in the FV directories.
1916 def CreateGuidedSectionToolsFile(self
):
1917 for BuildTarget
in self
.BuildTargetList
:
1918 for ToolChain
in self
.ToolChainList
:
1919 Wa
= WorkspaceAutoGen(
1936 if not os
.path
.exists(FvDir
):
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
)
1943 # Look through the tool definitions for GUIDed tools
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
]
1953 path
= '_'.join(split
[0:4]) + '_PATH'
1954 path
= self
.ToolDef
.ToolsDefTxtDictionary
[path
]
1955 path
= self
.GetFullPathOfTool(path
)
1956 guidAttribs
.append((guid
, toolName
, path
))
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
)
1965 ## Returns the full path of the tool.
1967 def GetFullPathOfTool (self
, tool
):
1968 if os
.path
.exists(tool
):
1969 return os
.path
.realpath(tool
)
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
)
1978 # If the tool was not found in the path then we just return
1982 ## Launch the module or platform build
1985 if not self
.ModuleFile
:
1986 if not self
.SpawnMode
or self
.Target
not in ["", "all"]:
1987 self
.SpawnMode
= False
1988 self
._BuildPlatform
()
1990 self
._MultiThreadBuildPlatform
()
1991 self
.CreateGuidedSectionToolsFile()
1993 self
.SpawnMode
= False
1996 if self
.Target
== 'cleanall':
1998 RemoveDirectory(os
.path
.dirname(GlobalData
.gDatabasePath
), True)
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:
2012 EdkLogger
.SetLevel(OldLogLevel
)
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"))
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
= {}
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
= {}
2033 def ParseDefines(DefineList
=[]):
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])
2043 if len(DefineTokenList
) == 1:
2044 DefineDict
[DefineTokenList
[0]] = "TRUE"
2046 DefineDict
[DefineTokenList
[0]] = DefineTokenList
[1].strip()
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
)
2055 parser
.error("Option %s only allows one instance in command line!" % option
)
2057 ## Parse command line options
2059 # Using standard Python module optparse to parse command line option of this tool.
2061 # @retval Opt A optparse.Values object containing the parsed options
2062 # @retval Args Target of build command
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.",
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.")
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.")
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.")
2093 Parser
.add_option("-c", "--case-insensitive", action
="store_true", dest
="CaseInsensitive", default
=False, help="Don't check case of file name.")
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.")
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]\".")
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','HASH','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, HASH, 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.")
2122 (Opt
, Args
) = Parser
.parse_args()
2125 ## Tool entrance method
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.
2131 # @retval 0 Tool was successful
2132 # @retval 1 Tool failed
2135 StartTime
= time
.time()
2137 # Initialize log system
2138 EdkLogger
.Initialize()
2139 GlobalData
.gCommand
= sys
.argv
[1:]
2141 # Parse the options and args
2143 (Option
, Target
) = MyOptionParser()
2144 GlobalData
.gOptions
= Option
2145 GlobalData
.gCaseInsensitive
= Option
.CaseInsensitive
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)
2155 EdkLogger
.SetLevel(EdkLogger
.INFO
)
2157 if Option
.LogFile
!= None:
2158 EdkLogger
.SetLogFile(Option
.LogFile
)
2160 if Option
.WarningAsError
== True:
2161 EdkLogger
.SetWarningAsError()
2163 if platform
.platform().find("Windows") >= 0:
2164 GlobalData
.gIsWindows
= True
2166 GlobalData
.gIsWindows
= False
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()));
2174 if len(Target
) == 0:
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
)))
2180 Target
= Target
[0].lower()
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
)))
2187 # Check environment variable: EDK_TOOLS_PATH, WORKSPACE, PATH
2190 GlobalData
.gCommandLineDefines
.update(ParseDefines(Option
.Macros
))
2192 Workspace
= os
.getenv("WORKSPACE")
2194 # Get files real name in workspace dir
2196 GlobalData
.gAllFiles
= Utils
.DirCache(Workspace
)
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
)
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.")
2206 Option
.ModuleFile
= NormFile(FileList
[0], Workspace
)
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)
2215 EdkLogger
.error("build", ErrorCode
, ExtraData
=ErrorInfo
)
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
)
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)
2230 EdkLogger
.error("build", ErrorCode
, ExtraData
=ErrorInfo
)
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")
2235 MyBuild
= Build(Target
, Workspace
, Option
)
2236 GlobalData
.gCommandLineDefines
['ARCH'] = ' '.join(MyBuild
.ArchList
)
2237 if not (MyBuild
.LaunchPrebuildFlag
and os
.path
.exists(MyBuild
.PlatformBuildPath
)):
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()
2245 # All job done, no error found and no exception raised
2248 except FatalError
, X
:
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]
2256 # error from Fdf parser
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())
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())
2271 # for multi-thread build exits safely
2272 MyBuild
.Relinquish()
2274 # try to get the meta-file from the object causing exception
2275 Tb
= sys
.exc_info()[-1]
2276 MetaFile
= GlobalData
.gProcessingFile
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
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",
2288 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
2289 ReturnCode
= CODE_ERROR
2291 Utils
.Progressor
.Abort()
2292 Utils
.ClearDuplicatedInf()
2296 MyBuild
.LanuchPostbuild()
2299 Conclusion
= "Failed"
2300 elif ReturnCode
== ABORT_ERROR
:
2301 Conclusion
= "Aborted"
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)
2310 BuildDurationStr
= time
.strftime("%H:%M:%S", BuildDuration
)
2313 MyBuild
.BuildReport
.GenerateReport(BuildDurationStr
)
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
)
2321 if __name__
== '__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