2 # build a platform or a module
4 # Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
6 # This program and the accompanying materials
7 # are licensed and made available under the terms and conditions of the BSD License
8 # which accompanies this distribution. The full text of the license may be found at
9 # http://opensource.org/licenses/bsd-license.php
11 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
18 import Common
.LongFilePathOs
as os
26 import encodings
.ascii
29 from threading
import *
30 from optparse
import OptionParser
31 from subprocess
import *
32 from Common
import Misc
as Utils
34 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
35 from Common
.LongFilePathSupport
import LongFilePath
36 from Common
.TargetTxtClassObject
import *
37 from Common
.ToolDefClassObject
import *
38 from Common
.DataType
import *
39 from Common
.BuildVersion
import gBUILD_VERSION
40 from AutoGen
.AutoGen
import *
41 from Common
.BuildToolError
import *
42 from Workspace
.WorkspaceDatabase
import *
44 from BuildReport
import BuildReport
45 from GenPatchPcdTable
.GenPatchPcdTable
import *
46 from PatchPcdValue
.PatchPcdValue
import *
48 import Common
.EdkLogger
49 import Common
.GlobalData
as GlobalData
51 # Version and Copyright
52 VersionNumber
= "0.51" + ' ' + gBUILD_VERSION
53 __version__
= "%prog Version " + VersionNumber
54 __copyright__
= "Copyright (c) 2007 - 2014, Intel Corporation All rights reserved."
56 ## standard targets of build command
57 gSupportedTarget
= ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run']
59 ## build configuration file
60 gBuildConfiguration
= "Conf/target.txt"
61 gBuildCacheDir
= "Conf/.cache"
62 gToolsDefinition
= "Conf/tools_def.txt"
64 TemporaryTablePattern
= re
.compile(r
'^_\d+_\d+_[a-fA-F0-9]+$')
67 ## Check environment PATH variable to make sure the specified tool is found
69 # If the tool is found in the PATH, then True is returned
70 # Otherwise, False is returned
72 def IsToolInPath(tool
):
73 if os
.environ
.has_key('PATHEXT'):
74 extns
= os
.environ
['PATHEXT'].split(os
.path
.pathsep
)
77 for pathDir
in os
.environ
['PATH'].split(os
.path
.pathsep
):
79 if os
.path
.exists(os
.path
.join(pathDir
, tool
+ ext
)):
83 ## Check environment variables
85 # Check environment variables that must be set for build. Currently they are
87 # WORKSPACE The directory all packages/platforms start from
88 # EDK_TOOLS_PATH The directory contains all tools needed by the build
89 # PATH $(EDK_TOOLS_PATH)/Bin/<sys> must be set in PATH
91 # If any of above environment variable is not set or has error, the build
94 def CheckEnvVariable():
96 if "WORKSPACE" not in os
.environ
:
97 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "Environment variable not found",
98 ExtraData
="WORKSPACE")
100 WorkspaceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["WORKSPACE"]))
101 if not os
.path
.exists(WorkspaceDir
):
102 EdkLogger
.error("build", FILE_NOT_FOUND
, "WORKSPACE doesn't exist", ExtraData
="%s" % WorkspaceDir
)
103 elif ' ' in WorkspaceDir
:
104 EdkLogger
.error("build", FORMAT_NOT_SUPPORTED
, "No space is allowed in WORKSPACE path",
105 ExtraData
=WorkspaceDir
)
106 os
.environ
["WORKSPACE"] = WorkspaceDir
109 # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP
111 if "ECP_SOURCE" not in os
.environ
:
112 os
.environ
["ECP_SOURCE"] = os
.path
.join(WorkspaceDir
, GlobalData
.gEdkCompatibilityPkg
)
113 if "EFI_SOURCE" not in os
.environ
:
114 os
.environ
["EFI_SOURCE"] = os
.environ
["ECP_SOURCE"]
115 if "EDK_SOURCE" not in os
.environ
:
116 os
.environ
["EDK_SOURCE"] = os
.environ
["ECP_SOURCE"]
119 # Unify case of characters on case-insensitive systems
121 EfiSourceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["EFI_SOURCE"]))
122 EdkSourceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["EDK_SOURCE"]))
123 EcpSourceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["ECP_SOURCE"]))
125 os
.environ
["EFI_SOURCE"] = EfiSourceDir
126 os
.environ
["EDK_SOURCE"] = EdkSourceDir
127 os
.environ
["ECP_SOURCE"] = EcpSourceDir
128 os
.environ
["EDK_TOOLS_PATH"] = os
.path
.normcase(os
.environ
["EDK_TOOLS_PATH"])
130 if not os
.path
.exists(EcpSourceDir
):
131 EdkLogger
.verbose("ECP_SOURCE = %s doesn't exist. Edk modules could not be built." % EcpSourceDir
)
132 elif ' ' in EcpSourceDir
:
133 EdkLogger
.error("build", FORMAT_NOT_SUPPORTED
, "No space is allowed in ECP_SOURCE path",
134 ExtraData
=EcpSourceDir
)
135 if not os
.path
.exists(EdkSourceDir
):
136 if EdkSourceDir
== EcpSourceDir
:
137 EdkLogger
.verbose("EDK_SOURCE = %s doesn't exist. Edk modules could not be built." % EdkSourceDir
)
139 EdkLogger
.error("build", PARAMETER_INVALID
, "EDK_SOURCE does not exist",
140 ExtraData
=EdkSourceDir
)
141 elif ' ' in EdkSourceDir
:
142 EdkLogger
.error("build", FORMAT_NOT_SUPPORTED
, "No space is allowed in EDK_SOURCE path",
143 ExtraData
=EdkSourceDir
)
144 if not os
.path
.exists(EfiSourceDir
):
145 if EfiSourceDir
== EcpSourceDir
:
146 EdkLogger
.verbose("EFI_SOURCE = %s doesn't exist. Edk modules could not be built." % EfiSourceDir
)
148 EdkLogger
.error("build", PARAMETER_INVALID
, "EFI_SOURCE does not exist",
149 ExtraData
=EfiSourceDir
)
150 elif ' ' in EfiSourceDir
:
151 EdkLogger
.error("build", FORMAT_NOT_SUPPORTED
, "No space is allowed in EFI_SOURCE path",
152 ExtraData
=EfiSourceDir
)
154 # change absolute path to relative path to WORKSPACE
155 if EfiSourceDir
.upper().find(WorkspaceDir
.upper()) != 0:
156 EdkLogger
.error("build", PARAMETER_INVALID
, "EFI_SOURCE is not under WORKSPACE",
157 ExtraData
="WORKSPACE = %s\n EFI_SOURCE = %s" % (WorkspaceDir
, EfiSourceDir
))
158 if EdkSourceDir
.upper().find(WorkspaceDir
.upper()) != 0:
159 EdkLogger
.error("build", PARAMETER_INVALID
, "EDK_SOURCE is not under WORKSPACE",
160 ExtraData
="WORKSPACE = %s\n EDK_SOURCE = %s" % (WorkspaceDir
, EdkSourceDir
))
161 if EcpSourceDir
.upper().find(WorkspaceDir
.upper()) != 0:
162 EdkLogger
.error("build", PARAMETER_INVALID
, "ECP_SOURCE is not under WORKSPACE",
163 ExtraData
="WORKSPACE = %s\n ECP_SOURCE = %s" % (WorkspaceDir
, EcpSourceDir
))
165 # check EDK_TOOLS_PATH
166 if "EDK_TOOLS_PATH" not in os
.environ
:
167 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "Environment variable not found",
168 ExtraData
="EDK_TOOLS_PATH")
171 if "PATH" not in os
.environ
:
172 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "Environment variable not found",
175 GlobalData
.gWorkspace
= WorkspaceDir
176 GlobalData
.gEfiSource
= EfiSourceDir
177 GlobalData
.gEdkSource
= EdkSourceDir
178 GlobalData
.gEcpSource
= EcpSourceDir
180 GlobalData
.gGlobalDefines
["WORKSPACE"] = WorkspaceDir
181 GlobalData
.gGlobalDefines
["EFI_SOURCE"] = EfiSourceDir
182 GlobalData
.gGlobalDefines
["EDK_SOURCE"] = EdkSourceDir
183 GlobalData
.gGlobalDefines
["ECP_SOURCE"] = EcpSourceDir
184 GlobalData
.gGlobalDefines
["EDK_TOOLS_PATH"] = os
.environ
["EDK_TOOLS_PATH"]
186 ## Get normalized file path
188 # Convert the path to be local format, and remove the WORKSPACE path at the
189 # beginning if the file path is given in full path.
191 # @param FilePath File path to be normalized
192 # @param Workspace Workspace path which the FilePath will be checked against
194 # @retval string The normalized file path
196 def NormFile(FilePath
, Workspace
):
197 # check if the path is absolute or relative
198 if os
.path
.isabs(FilePath
):
199 FileFullPath
= os
.path
.normpath(FilePath
)
201 FileFullPath
= os
.path
.normpath(os
.path
.join(Workspace
, FilePath
))
203 # check if the file path exists or not
204 if not os
.path
.isfile(FileFullPath
):
205 EdkLogger
.error("build", FILE_NOT_FOUND
, ExtraData
="\t%s (Please give file in absolute path or relative to WORKSPACE)" % FileFullPath
)
207 # remove workspace directory from the beginning part of the file path
208 if Workspace
[-1] in ["\\", "/"]:
209 return FileFullPath
[len(Workspace
):]
211 return FileFullPath
[(len(Workspace
) + 1):]
213 ## Get the output of an external program
215 # This is the entrance method of thread reading output of an external program and
216 # putting them in STDOUT/STDERR of current program.
218 # @param From The stream message read from
219 # @param To The stream message put on
220 # @param ExitFlag The flag used to indicate stopping reading
222 def ReadMessage(From
, To
, ExitFlag
):
224 # read one line a time
225 Line
= From
.readline()
226 # empty string means "end"
227 if Line
!= None and Line
!= "":
234 ## Launch an external program
236 # This method will call subprocess.Popen to execute an external program with
237 # given options in specified directory. Because of the dead-lock issue during
238 # redirecting output of the external program, threads are used to to do the
241 # @param Command A list or string containing the call of the program
242 # @param WorkingDir The directory in which the program will be running
244 def LaunchCommand(Command
, WorkingDir
):
245 # if working directory doesn't exist, Popen() will raise an exception
246 if not os
.path
.isdir(WorkingDir
):
247 EdkLogger
.error("build", FILE_NOT_FOUND
, ExtraData
=WorkingDir
)
249 # Command is used as the first Argument in following Popen().
250 # It could be a string or sequence. We find that if command is a string in following Popen(),
251 # ubuntu may fail with an error message that the command is not found.
252 # So here we may need convert command from string to list instance.
253 if not isinstance(Command
, list):
254 if platform
.system() != 'Windows':
255 Command
= Command
.split()
258 EndOfProcedure
= None
261 Proc
= Popen(Command
, stdout
=PIPE
, stderr
=PIPE
, env
=os
.environ
, cwd
=WorkingDir
, bufsize
=-1)
263 # launch two threads to read the STDOUT and STDERR
264 EndOfProcedure
= Event()
265 EndOfProcedure
.clear()
267 StdOutThread
= Thread(target
=ReadMessage
, args
=(Proc
.stdout
, EdkLogger
.info
, EndOfProcedure
))
268 StdOutThread
.setName("STDOUT-Redirector")
269 StdOutThread
.setDaemon(False)
273 StdErrThread
= Thread(target
=ReadMessage
, args
=(Proc
.stderr
, EdkLogger
.quiet
, EndOfProcedure
))
274 StdErrThread
.setName("STDERR-Redirector")
275 StdErrThread
.setDaemon(False)
278 # waiting for program exit
280 except: # in case of aborting
281 # terminate the threads redirecting the program output
282 if EndOfProcedure
!= None:
285 if type(Command
) != type(""):
286 Command
= " ".join(Command
)
287 EdkLogger
.error("build", COMMAND_FAILURE
, "Failed to start command", ExtraData
="%s [%s]" % (Command
, WorkingDir
))
294 # check the return code of the program
295 if Proc
.returncode
!= 0:
296 if type(Command
) != type(""):
297 Command
= " ".join(Command
)
298 EdkLogger
.error("build", COMMAND_FAILURE
, ExtraData
="%s [%s]" % (Command
, WorkingDir
))
300 ## The smallest unit that can be built in multi-thread build mode
302 # This is the base class of build unit. The "Obj" parameter must provide
303 # __str__(), __eq__() and __hash__() methods. Otherwise there could be build units
306 # Currently the "Obj" should be only ModuleAutoGen or PlatformAutoGen objects.
311 # @param self The object pointer
312 # @param Obj The object the build is working on
313 # @param Target The build target name, one of gSupportedTarget
314 # @param Dependency The BuildUnit(s) which must be completed in advance
315 # @param WorkingDir The directory build command starts in
317 def __init__(self
, Obj
, BuildCommand
, Target
, Dependency
, WorkingDir
="."):
318 self
.BuildObject
= Obj
319 self
.Dependency
= Dependency
320 self
.WorkingDir
= WorkingDir
322 self
.BuildCommand
= BuildCommand
324 EdkLogger
.error("build", OPTION_MISSING
,
325 "No build command found for this module. "
326 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
327 (Obj
.BuildTarget
, Obj
.ToolChain
, Obj
.Arch
),
333 # It just returns the string representation of self.BuildObject
335 # @param self The object pointer
338 return str(self
.BuildObject
)
340 ## "==" operator method
342 # It just compares self.BuildObject with "Other". So self.BuildObject must
343 # provide its own __eq__() method.
345 # @param self The object pointer
346 # @param Other The other BuildUnit object compared to
348 def __eq__(self
, Other
):
349 return Other
!= None and self
.BuildObject
== Other
.BuildObject \
350 and self
.BuildObject
.Arch
== Other
.BuildObject
.Arch
354 # It just returns the hash value of self.BuildObject which must be hashable.
356 # @param self The object pointer
359 return hash(self
.BuildObject
) + hash(self
.BuildObject
.Arch
)
362 return repr(self
.BuildObject
)
364 ## The smallest module unit that can be built by nmake/make command in multi-thread build mode
366 # This class is for module build by nmake/make build system. The "Obj" parameter
367 # must provide __str__(), __eq__() and __hash__() methods. Otherwise there could
368 # be make units missing build.
370 # Currently the "Obj" should be only ModuleAutoGen object.
372 class ModuleMakeUnit(BuildUnit
):
375 # @param self The object pointer
376 # @param Obj The ModuleAutoGen object the build is working on
377 # @param Target The build target name, one of gSupportedTarget
379 def __init__(self
, Obj
, Target
):
380 Dependency
= [ModuleMakeUnit(La
, Target
) for La
in Obj
.LibraryAutoGenList
]
381 BuildUnit
.__init
__(self
, Obj
, Obj
.BuildCommand
, Target
, Dependency
, Obj
.MakeFileDir
)
382 if Target
in [None, "", "all"]:
383 self
.Target
= "tbuild"
385 ## The smallest platform unit that can be built by nmake/make command in multi-thread build mode
387 # This class is for platform build by nmake/make build system. The "Obj" parameter
388 # must provide __str__(), __eq__() and __hash__() methods. Otherwise there could
389 # be make units missing build.
391 # Currently the "Obj" should be only PlatformAutoGen object.
393 class PlatformMakeUnit(BuildUnit
):
396 # @param self The object pointer
397 # @param Obj The PlatformAutoGen object the build is working on
398 # @param Target The build target name, one of gSupportedTarget
400 def __init__(self
, Obj
, Target
):
401 Dependency
= [ModuleMakeUnit(Lib
, Target
) for Lib
in self
.BuildObject
.LibraryAutoGenList
]
402 Dependency
.extend([ModuleMakeUnit(Mod
, Target
) for Mod
in self
.BuildObject
.ModuleAutoGenList
])
403 BuildUnit
.__init
__(self
, Obj
, Obj
.BuildCommand
, Target
, Dependency
, Obj
.MakeFileDir
)
405 ## The class representing the task of a module build or platform build
407 # This class manages the build tasks in multi-thread build mode. Its jobs include
408 # scheduling thread running, catching thread error, monitor the thread status, etc.
411 # queue for tasks waiting for schedule
412 _PendingQueue
= sdict()
413 _PendingQueueLock
= threading
.Lock()
415 # queue for tasks ready for running
416 _ReadyQueue
= sdict()
417 _ReadyQueueLock
= threading
.Lock()
419 # queue for run tasks
420 _RunningQueue
= sdict()
421 _RunningQueueLock
= threading
.Lock()
423 # queue containing all build tasks, in case duplicate build
426 # flag indicating error occurs in a running thread
427 _ErrorFlag
= threading
.Event()
431 # BoundedSemaphore object used to control the number of running threads
434 # flag indicating if the scheduler is started or not
435 _SchedulerStopped
= threading
.Event()
436 _SchedulerStopped
.set()
438 ## Start the task scheduler thread
440 # @param MaxThreadNumber The maximum thread number
441 # @param ExitFlag Flag used to end the scheduler
444 def StartScheduler(MaxThreadNumber
, ExitFlag
):
445 SchedulerThread
= Thread(target
=BuildTask
.Scheduler
, args
=(MaxThreadNumber
, ExitFlag
))
446 SchedulerThread
.setName("Build-Task-Scheduler")
447 SchedulerThread
.setDaemon(False)
448 SchedulerThread
.start()
449 # wait for the scheduler to be started, especially useful in Linux
450 while not BuildTask
.IsOnGoing():
455 # @param MaxThreadNumber The maximum thread number
456 # @param ExitFlag Flag used to end the scheduler
459 def Scheduler(MaxThreadNumber
, ExitFlag
):
460 BuildTask
._SchedulerStopped
.clear()
462 # use BoundedSemaphore to control the maximum running threads
463 BuildTask
._Thread
= BoundedSemaphore(MaxThreadNumber
)
465 # scheduling loop, which will exits when no pending/ready task and
466 # indicated to do so, or there's error in running thread
468 while (len(BuildTask
._PendingQueue
) > 0 or len(BuildTask
._ReadyQueue
) > 0 \
469 or not ExitFlag
.isSet()) and not BuildTask
._ErrorFlag
.isSet():
470 EdkLogger
.debug(EdkLogger
.DEBUG_8
, "Pending Queue (%d), Ready Queue (%d)"
471 % (len(BuildTask
._PendingQueue
), len(BuildTask
._ReadyQueue
)))
473 # get all pending tasks
474 BuildTask
._PendingQueueLock
.acquire()
475 BuildObjectList
= BuildTask
._PendingQueue
.keys()
477 # check if their dependency is resolved, and if true, move them
480 for BuildObject
in BuildObjectList
:
481 Bt
= BuildTask
._PendingQueue
[BuildObject
]
483 BuildTask
._ReadyQueue
[BuildObject
] = BuildTask
._PendingQueue
.pop(BuildObject
)
484 BuildTask
._PendingQueueLock
.release()
486 # launch build thread until the maximum number of threads is reached
487 while not BuildTask
._ErrorFlag
.isSet():
488 # empty ready queue, do nothing further
489 if len(BuildTask
._ReadyQueue
) == 0:
492 # wait for active thread(s) exit
493 BuildTask
._Thread
.acquire(True)
495 # start a new build thread
496 Bo
= BuildTask
._ReadyQueue
.keys()[0]
497 Bt
= BuildTask
._ReadyQueue
.pop(Bo
)
499 # move into running queue
500 BuildTask
._RunningQueueLock
.acquire()
501 BuildTask
._RunningQueue
[Bo
] = Bt
502 BuildTask
._RunningQueueLock
.release()
511 # wait for all running threads exit
512 if BuildTask
._ErrorFlag
.isSet():
513 EdkLogger
.quiet("\nWaiting for all build threads exit...")
514 # while not BuildTask._ErrorFlag.isSet() and \
515 while len(BuildTask
._RunningQueue
) > 0:
516 EdkLogger
.verbose("Waiting for thread ending...(%d)" % len(BuildTask
._RunningQueue
))
517 EdkLogger
.debug(EdkLogger
.DEBUG_8
, "Threads [%s]" % ", ".join([Th
.getName() for Th
in threading
.enumerate()]))
520 except BaseException
, X
:
522 # TRICK: hide the output of threads left runing, so that the user can
523 # catch the error message easily
525 EdkLogger
.SetLevel(EdkLogger
.ERROR
)
526 BuildTask
._ErrorFlag
.set()
527 BuildTask
._ErrorMessage
= "build thread scheduler error\n\t%s" % str(X
)
529 BuildTask
._PendingQueue
.clear()
530 BuildTask
._ReadyQueue
.clear()
531 BuildTask
._RunningQueue
.clear()
532 BuildTask
._TaskQueue
.clear()
533 BuildTask
._SchedulerStopped
.set()
535 ## Wait for all running method exit
538 def WaitForComplete():
539 BuildTask
._SchedulerStopped
.wait()
541 ## Check if the scheduler is running or not
545 return not BuildTask
._SchedulerStopped
.isSet()
550 if BuildTask
.IsOnGoing():
551 BuildTask
._ErrorFlag
.set()
552 BuildTask
.WaitForComplete()
554 ## Check if there's error in running thread
556 # Since the main thread cannot catch exceptions in other thread, we have to
557 # use threading.Event to communicate this formation to main thread.
561 return BuildTask
._ErrorFlag
.isSet()
563 ## Get error message in running thread
565 # Since the main thread cannot catch exceptions in other thread, we have to
566 # use a static variable to communicate this message to main thread.
569 def GetErrorMessage():
570 return BuildTask
._ErrorMessage
572 ## Factory method to create a BuildTask object
574 # This method will check if a module is building or has been built. And if
575 # true, just return the associated BuildTask object in the _TaskQueue. If
576 # not, create and return a new BuildTask object. The new BuildTask object
577 # will be appended to the _PendingQueue for scheduling later.
579 # @param BuildItem A BuildUnit object representing a build object
580 # @param Dependency The dependent build object of BuildItem
583 def New(BuildItem
, Dependency
=None):
584 if BuildItem
in BuildTask
._TaskQueue
:
585 Bt
= BuildTask
._TaskQueue
[BuildItem
]
589 Bt
._Init
(BuildItem
, Dependency
)
590 BuildTask
._TaskQueue
[BuildItem
] = Bt
592 BuildTask
._PendingQueueLock
.acquire()
593 BuildTask
._PendingQueue
[BuildItem
] = Bt
594 BuildTask
._PendingQueueLock
.release()
598 ## The real constructor of BuildTask
600 # @param BuildItem A BuildUnit object representing a build object
601 # @param Dependency The dependent build object of BuildItem
603 def _Init(self
, BuildItem
, Dependency
=None):
604 self
.BuildItem
= BuildItem
606 self
.DependencyList
= []
607 if Dependency
== None:
608 Dependency
= BuildItem
.Dependency
610 Dependency
.extend(BuildItem
.Dependency
)
611 self
.AddDependency(Dependency
)
612 # flag indicating build completes, used to avoid unnecessary re-build
613 self
.CompleteFlag
= False
615 ## Check if all dependent build tasks are completed or not
619 for Dep
in self
.DependencyList
:
620 if Dep
.CompleteFlag
== True:
627 ## Add dependent build task
629 # @param Dependency The list of dependent build objects
631 def AddDependency(self
, Dependency
):
632 for Dep
in Dependency
:
633 self
.DependencyList
.append(BuildTask
.New(Dep
)) # BuildTask list
635 ## The thread wrapper of LaunchCommand function
637 # @param Command A list or string contains the call of the command
638 # @param WorkingDir The directory in which the program will be running
640 def _CommandThread(self
, Command
, WorkingDir
):
642 LaunchCommand(Command
, WorkingDir
)
643 self
.CompleteFlag
= True
646 # TRICK: hide the output of threads left runing, so that the user can
647 # catch the error message easily
649 if not BuildTask
._ErrorFlag
.isSet():
650 GlobalData
.gBuildingModule
= "%s [%s, %s, %s]" % (str(self
.BuildItem
.BuildObject
),
651 self
.BuildItem
.BuildObject
.Arch
,
652 self
.BuildItem
.BuildObject
.ToolChain
,
653 self
.BuildItem
.BuildObject
.BuildTarget
655 EdkLogger
.SetLevel(EdkLogger
.ERROR
)
656 BuildTask
._ErrorFlag
.set()
657 BuildTask
._ErrorMessage
= "%s broken\n %s [%s]" % \
658 (threading
.currentThread().getName(), Command
, WorkingDir
)
659 # indicate there's a thread is available for another build task
660 BuildTask
._RunningQueueLock
.acquire()
661 BuildTask
._RunningQueue
.pop(self
.BuildItem
)
662 BuildTask
._RunningQueueLock
.release()
663 BuildTask
._Thread
.release()
665 ## Start build task thread
668 EdkLogger
.quiet("Building ... %s" % repr(self
.BuildItem
))
669 Command
= self
.BuildItem
.BuildCommand
+ [self
.BuildItem
.Target
]
670 self
.BuildTread
= Thread(target
=self
._CommandThread
, args
=(Command
, self
.BuildItem
.WorkingDir
))
671 self
.BuildTread
.setName("build thread")
672 self
.BuildTread
.setDaemon(False)
673 self
.BuildTread
.start()
675 ## The class contains the information related to EFI image
680 # Constructor will load all required image information.
682 # @param BaseName The full file path of image.
683 # @param Guid The GUID for image.
684 # @param Arch Arch of this image.
685 # @param OutputDir The output directory for image.
686 # @param DebugDir The debug directory for image.
687 # @param ImageClass PeImage Information
689 def __init__(self
, BaseName
, Guid
, Arch
, OutputDir
, DebugDir
, ImageClass
):
690 self
.BaseName
= BaseName
693 self
.OutputDir
= OutputDir
694 self
.DebugDir
= DebugDir
695 self
.Image
= ImageClass
696 self
.Image
.Size
= (self
.Image
.Size
/ 0x1000 + 1) * 0x1000
698 ## The class implementing the EDK2 build process
700 # The build process includes:
701 # 1. Load configuration from target.txt and tools_def.txt in $(WORKSPACE)/Conf
702 # 2. Parse DSC file of active platform
703 # 3. Parse FDF file if any
704 # 4. Establish build database, including parse all other files (module, package)
705 # 5. Create AutoGen files (C code file, depex file, makefile) if necessary
706 # 6. Call build command
711 # Constructor will load all necessary configurations, parse platform, modules
712 # and packages and the establish a database for AutoGen.
714 # @param Target The build command target, one of gSupportedTarget
715 # @param WorkspaceDir The directory of workspace
716 # @param BuildOptions Build options passed from command line
718 def __init__(self
, Target
, WorkspaceDir
, BuildOptions
):
719 self
.WorkspaceDir
= WorkspaceDir
721 self
.PlatformFile
= BuildOptions
.PlatformFile
722 self
.ModuleFile
= BuildOptions
.ModuleFile
723 self
.ArchList
= BuildOptions
.TargetArch
724 self
.ToolChainList
= BuildOptions
.ToolChain
725 self
.BuildTargetList
= BuildOptions
.BuildTarget
726 self
.Fdf
= BuildOptions
.FdfFile
727 self
.FdList
= BuildOptions
.RomImage
728 self
.FvList
= BuildOptions
.FvImage
729 self
.CapList
= BuildOptions
.CapName
730 self
.SilentMode
= BuildOptions
.SilentMode
731 self
.ThreadNumber
= BuildOptions
.ThreadNumber
732 self
.SkipAutoGen
= BuildOptions
.SkipAutoGen
733 self
.Reparse
= BuildOptions
.Reparse
734 self
.SkuId
= BuildOptions
.SkuId
735 self
.SpawnMode
= True
736 self
.BuildReport
= BuildReport(BuildOptions
.ReportFile
, BuildOptions
.ReportType
)
737 self
.TargetTxt
= TargetTxtClassObject()
738 self
.ToolDef
= ToolDefClassObject()
739 #Set global flag for build mode
740 GlobalData
.gIgnoreSource
= BuildOptions
.IgnoreSources
741 if BuildOptions
.DisableCache
:
742 self
.Db
= WorkspaceDatabase(":memory:")
744 self
.Db
= WorkspaceDatabase(None, self
.Reparse
)
745 self
.BuildDatabase
= self
.Db
.BuildObject
747 self
.LoadFixAddress
= 0
748 self
.UniFlag
= BuildOptions
.Flag
749 self
.BuildModules
= []
751 # print dot character during doing some time-consuming work
752 self
.Progress
= Utils
.Progressor()
756 # print current build environment and configuration
757 EdkLogger
.quiet("%-16s = %s" % ("WORKSPACE", os
.environ
["WORKSPACE"]))
758 EdkLogger
.quiet("%-16s = %s" % ("ECP_SOURCE", os
.environ
["ECP_SOURCE"]))
759 EdkLogger
.quiet("%-16s = %s" % ("EDK_SOURCE", os
.environ
["EDK_SOURCE"]))
760 EdkLogger
.quiet("%-16s = %s" % ("EFI_SOURCE", os
.environ
["EFI_SOURCE"]))
761 EdkLogger
.quiet("%-16s = %s" % ("EDK_TOOLS_PATH", os
.environ
["EDK_TOOLS_PATH"]))
765 os
.chdir(self
.WorkspaceDir
)
767 ## Load configuration
769 # This method will parse target.txt and get the build configurations.
771 def LoadConfiguration(self
):
773 # Check target.txt and tools_def.txt and Init them
775 BuildConfigurationFile
= os
.path
.normpath(os
.path
.join(self
.WorkspaceDir
, gBuildConfiguration
))
776 if os
.path
.isfile(BuildConfigurationFile
) == True:
777 StatusCode
= self
.TargetTxt
.LoadTargetTxtFile(BuildConfigurationFile
)
779 ToolDefinitionFile
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_TOOL_CHAIN_CONF
]
780 if ToolDefinitionFile
== '':
781 ToolDefinitionFile
= gToolsDefinition
782 ToolDefinitionFile
= os
.path
.normpath(os
.path
.join(self
.WorkspaceDir
, ToolDefinitionFile
))
783 if os
.path
.isfile(ToolDefinitionFile
) == True:
784 StatusCode
= self
.ToolDef
.LoadToolDefFile(ToolDefinitionFile
)
786 EdkLogger
.error("build", FILE_NOT_FOUND
, ExtraData
=ToolDefinitionFile
)
788 EdkLogger
.error("build", FILE_NOT_FOUND
, ExtraData
=BuildConfigurationFile
)
790 # if no ARCH given in command line, get it from target.txt
791 if not self
.ArchList
:
792 self
.ArchList
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_TARGET_ARCH
]
793 self
.ArchList
= tuple(self
.ArchList
)
795 # if no build target given in command line, get it from target.txt
796 if not self
.BuildTargetList
:
797 self
.BuildTargetList
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_TARGET
]
799 # if no tool chain given in command line, get it from target.txt
800 if not self
.ToolChainList
:
801 self
.ToolChainList
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_TOOL_CHAIN_TAG
]
802 if self
.ToolChainList
== None or len(self
.ToolChainList
) == 0:
803 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
, ExtraData
="No toolchain given. Don't know how to build.\n")
805 # check if the tool chains are defined or not
806 NewToolChainList
= []
807 for ToolChain
in self
.ToolChainList
:
808 if ToolChain
not in self
.ToolDef
.ToolsDefTxtDatabase
[TAB_TOD_DEFINES_TOOL_CHAIN_TAG
]:
809 EdkLogger
.warn("build", "Tool chain [%s] is not defined" % ToolChain
)
811 NewToolChainList
.append(ToolChain
)
812 # if no tool chain available, break the build
813 if len(NewToolChainList
) == 0:
814 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
,
815 ExtraData
="[%s] not defined. No toolchain available for build!\n" % ", ".join(self
.ToolChainList
))
817 self
.ToolChainList
= NewToolChainList
819 if self
.ThreadNumber
== None:
820 self
.ThreadNumber
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER
]
821 if self
.ThreadNumber
== '':
822 self
.ThreadNumber
= 0
824 self
.ThreadNumber
= int(self
.ThreadNumber
, 0)
826 if self
.ThreadNumber
== 0:
827 self
.ThreadNumber
= 1
829 if not self
.PlatformFile
:
830 PlatformFile
= self
.TargetTxt
.TargetTxtDictionary
[DataType
.TAB_TAT_DEFINES_ACTIVE_PLATFORM
]
832 # Try to find one in current directory
833 WorkingDirectory
= os
.getcwd()
834 FileList
= glob
.glob(os
.path
.normpath(os
.path
.join(WorkingDirectory
, '*.dsc')))
835 FileNum
= len(FileList
)
837 EdkLogger
.error("build", OPTION_MISSING
,
838 ExtraData
="There are %d DSC files in %s. Use '-p' to specify one.\n" % (FileNum
, WorkingDirectory
))
840 PlatformFile
= FileList
[0]
842 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
,
843 ExtraData
="No active platform specified in target.txt or command line! Nothing can be built.\n")
845 self
.PlatformFile
= PathClass(NormFile(PlatformFile
, self
.WorkspaceDir
), self
.WorkspaceDir
)
847 ## Initialize build configuration
849 # This method will parse DSC file and merge the configurations from
850 # command line and target.txt, then get the final build configurations.
853 # parse target.txt, tools_def.txt, and platform file
854 self
.LoadConfiguration()
856 # Allow case-insensitive for those from command line or configuration file
857 ErrorCode
, ErrorInfo
= self
.PlatformFile
.Validate(".dsc", False)
859 EdkLogger
.error("build", ErrorCode
, ExtraData
=ErrorInfo
)
861 # create metafile database
862 self
.Db
.InitDatabase()
864 ## Build a module or platform
866 # Create autogen code and makefile for a module or platform, and the launch
867 # "make" command to build it
869 # @param Target The target of build command
870 # @param Platform The platform file
871 # @param Module The module file
872 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"
873 # @param ToolChain The name of toolchain to build
874 # @param Arch The arch of the module/platform
875 # @param CreateDepModuleCodeFile Flag used to indicate creating code
876 # for dependent modules/Libraries
877 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile
878 # for dependent modules/Libraries
880 def _BuildPa(self
, Target
, AutoGenObject
, CreateDepsCodeFile
=True, CreateDepsMakeFile
=True, BuildModule
=False):
881 if AutoGenObject
== None:
884 # skip file generation for cleanxxx targets, run and fds target
885 if Target
not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
886 # for target which must generate AutoGen code and makefile
887 if not self
.SkipAutoGen
or Target
== 'genc':
888 self
.Progress
.Start("Generating code")
889 AutoGenObject
.CreateCodeFile(CreateDepsCodeFile
)
890 self
.Progress
.Stop("done!")
894 if not self
.SkipAutoGen
or Target
== 'genmake':
895 self
.Progress
.Start("Generating makefile")
896 AutoGenObject
.CreateMakeFile(CreateDepsMakeFile
)
897 self
.Progress
.Stop("done!")
898 if Target
== "genmake":
901 # always recreate top/platform makefile when clean, just in case of inconsistency
902 AutoGenObject
.CreateCodeFile(False)
903 AutoGenObject
.CreateMakeFile(False)
905 if EdkLogger
.GetLevel() == EdkLogger
.QUIET
:
906 EdkLogger
.quiet("Building ... %s" % repr(AutoGenObject
))
908 BuildCommand
= AutoGenObject
.BuildCommand
909 if BuildCommand
== None or len(BuildCommand
) == 0:
910 EdkLogger
.error("build", OPTION_MISSING
,
911 "No build command found for this module. "
912 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
913 (AutoGenObject
.BuildTarget
, AutoGenObject
.ToolChain
, AutoGenObject
.Arch
),
914 ExtraData
=str(AutoGenObject
))
916 makefile
= GenMake
.BuildFile(AutoGenObject
)._FILE
_NAME
_[GenMake
.gMakeType
]
920 LaunchCommand(AutoGenObject
.GenFdsCommand
, AutoGenObject
.MakeFileDir
)
925 RunDir
= os
.path
.normpath(os
.path
.join(AutoGenObject
.BuildDir
, 'IA32'))
926 Command
= '.\SecMain'
928 LaunchCommand(Command
, RunDir
)
933 BuildCommand
= BuildCommand
+ [Target
]
934 LaunchCommand(BuildCommand
, AutoGenObject
.MakeFileDir
)
935 self
.CreateAsBuiltInf()
939 if Target
== 'libraries':
940 for Lib
in AutoGenObject
.LibraryBuildDirectoryList
:
941 NewBuildCommand
= BuildCommand
+ ['-f', os
.path
.normpath(os
.path
.join(Lib
, makefile
)), 'pbuild']
942 LaunchCommand(NewBuildCommand
, AutoGenObject
.MakeFileDir
)
946 if Target
== 'modules':
947 for Lib
in AutoGenObject
.LibraryBuildDirectoryList
:
948 NewBuildCommand
= BuildCommand
+ ['-f', os
.path
.normpath(os
.path
.join(Lib
, makefile
)), 'pbuild']
949 LaunchCommand(NewBuildCommand
, AutoGenObject
.MakeFileDir
)
950 for Mod
in AutoGenObject
.ModuleBuildDirectoryList
:
951 NewBuildCommand
= BuildCommand
+ ['-f', os
.path
.normpath(os
.path
.join(Mod
, makefile
)), 'pbuild']
952 LaunchCommand(NewBuildCommand
, AutoGenObject
.MakeFileDir
)
953 self
.CreateAsBuiltInf()
957 if Target
== 'cleanlib':
958 for Lib
in AutoGenObject
.LibraryBuildDirectoryList
:
959 LibMakefile
= os
.path
.normpath(os
.path
.join(Lib
, makefile
))
960 if os
.path
.exists(LibMakefile
):
961 NewBuildCommand
= BuildCommand
+ ['-f', LibMakefile
, 'cleanall']
962 LaunchCommand(NewBuildCommand
, AutoGenObject
.MakeFileDir
)
966 if Target
== 'clean':
967 for Mod
in AutoGenObject
.ModuleBuildDirectoryList
:
968 ModMakefile
= os
.path
.normpath(os
.path
.join(Mod
, makefile
))
969 if os
.path
.exists(ModMakefile
):
970 NewBuildCommand
= BuildCommand
+ ['-f', ModMakefile
, 'cleanall']
971 LaunchCommand(NewBuildCommand
, AutoGenObject
.MakeFileDir
)
972 for Lib
in AutoGenObject
.LibraryBuildDirectoryList
:
973 LibMakefile
= os
.path
.normpath(os
.path
.join(Lib
, makefile
))
974 if os
.path
.exists(LibMakefile
):
975 NewBuildCommand
= BuildCommand
+ ['-f', LibMakefile
, 'cleanall']
976 LaunchCommand(NewBuildCommand
, AutoGenObject
.MakeFileDir
)
980 if Target
== 'cleanall':
982 #os.rmdir(AutoGenObject.BuildDir)
983 RemoveDirectory(AutoGenObject
.BuildDir
, True)
985 # First should close DB.
988 RemoveDirectory(os
.path
.dirname(GlobalData
.gDatabasePath
), True)
989 except WindowsError, X
:
990 EdkLogger
.error("build", FILE_DELETE_FAILURE
, ExtraData
=str(X
))
993 ## Build a module or platform
995 # Create autogen code and makefile for a module or platform, and the launch
996 # "make" command to build it
998 # @param Target The target of build command
999 # @param Platform The platform file
1000 # @param Module The module file
1001 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"
1002 # @param ToolChain The name of toolchain to build
1003 # @param Arch The arch of the module/platform
1004 # @param CreateDepModuleCodeFile Flag used to indicate creating code
1005 # for dependent modules/Libraries
1006 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile
1007 # for dependent modules/Libraries
1009 def _Build(self
, Target
, AutoGenObject
, CreateDepsCodeFile
=True, CreateDepsMakeFile
=True, BuildModule
=False):
1010 if AutoGenObject
== None:
1013 # skip file generation for cleanxxx targets, run and fds target
1014 if Target
not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1015 # for target which must generate AutoGen code and makefile
1016 if not self
.SkipAutoGen
or Target
== 'genc':
1017 self
.Progress
.Start("Generating code")
1018 AutoGenObject
.CreateCodeFile(CreateDepsCodeFile
)
1019 self
.Progress
.Stop("done!")
1020 if Target
== "genc":
1023 if not self
.SkipAutoGen
or Target
== 'genmake':
1024 self
.Progress
.Start("Generating makefile")
1025 AutoGenObject
.CreateMakeFile(CreateDepsMakeFile
)
1026 #AutoGenObject.CreateAsBuiltInf()
1027 self
.Progress
.Stop("done!")
1028 if Target
== "genmake":
1031 # always recreate top/platform makefile when clean, just in case of inconsistency
1032 AutoGenObject
.CreateCodeFile(False)
1033 AutoGenObject
.CreateMakeFile(False)
1035 if EdkLogger
.GetLevel() == EdkLogger
.QUIET
:
1036 EdkLogger
.quiet("Building ... %s" % repr(AutoGenObject
))
1038 BuildCommand
= AutoGenObject
.BuildCommand
1039 if BuildCommand
== None or len(BuildCommand
) == 0:
1040 EdkLogger
.error("build", OPTION_MISSING
,
1041 "No build command found for this module. "
1042 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
1043 (AutoGenObject
.BuildTarget
, AutoGenObject
.ToolChain
, AutoGenObject
.Arch
),
1044 ExtraData
=str(AutoGenObject
))
1048 LaunchCommand(AutoGenObject
.GenFdsCommand
, AutoGenObject
.MakeFileDir
)
1053 RunDir
= os
.path
.normpath(os
.path
.join(AutoGenObject
.BuildDir
, 'IA32'))
1054 Command
= '.\SecMain'
1056 LaunchCommand(Command
, RunDir
)
1060 BuildCommand
= BuildCommand
+ [Target
]
1062 LaunchCommand(BuildCommand
, AutoGenObject
.MakeFileDir
)
1063 self
.CreateAsBuiltInf()
1067 if Target
== 'libraries':
1074 if Target
== 'cleanall':
1076 #os.rmdir(AutoGenObject.BuildDir)
1077 RemoveDirectory(AutoGenObject
.BuildDir
, True)
1079 # First should close DB.
1082 RemoveDirectory(gBuildCacheDir
, True)
1083 except WindowsError, X
:
1084 EdkLogger
.error("build", FILE_DELETE_FAILURE
, ExtraData
=str(X
))
1087 ## Rebase module image and Get function address for the input module list.
1089 def _RebaseModule (self
, MapBuffer
, BaseAddress
, ModuleList
, AddrIsOffset
= True, ModeIsSmm
= False):
1091 AddrIsOffset
= False
1092 InfFileNameList
= ModuleList
.keys()
1093 #InfFileNameList.sort()
1094 for InfFile
in InfFileNameList
:
1095 sys
.stdout
.write (".")
1097 ModuleInfo
= ModuleList
[InfFile
]
1098 ModuleName
= ModuleInfo
.BaseName
1099 ModuleOutputImage
= ModuleInfo
.Image
.FileName
1100 ModuleDebugImage
= os
.path
.join(ModuleInfo
.DebugDir
, ModuleInfo
.BaseName
+ '.efi')
1101 ## for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1103 BaseAddress
= BaseAddress
- ModuleInfo
.Image
.Size
1105 # Update Image to new BaseAddress by GenFw tool
1107 LaunchCommand(["GenFw", "--rebase", str(BaseAddress
), "-r", ModuleOutputImage
], ModuleInfo
.OutputDir
)
1108 LaunchCommand(["GenFw", "--rebase", str(BaseAddress
), "-r", ModuleDebugImage
], ModuleInfo
.DebugDir
)
1111 # Set new address to the section header only for SMM driver.
1113 LaunchCommand(["GenFw", "--address", str(BaseAddress
), "-r", ModuleOutputImage
], ModuleInfo
.OutputDir
)
1114 LaunchCommand(["GenFw", "--address", str(BaseAddress
), "-r", ModuleDebugImage
], ModuleInfo
.DebugDir
)
1116 # Collect funtion address from Map file
1118 ImageMapTable
= ModuleOutputImage
.replace('.efi', '.map')
1120 if os
.path
.exists(ImageMapTable
):
1121 OrigImageBaseAddress
= 0
1122 ImageMap
= open (ImageMapTable
, 'r')
1123 for LinStr
in ImageMap
:
1124 if len (LinStr
.strip()) == 0:
1127 # Get the preferred address set on link time.
1129 if LinStr
.find ('Preferred load address is') != -1:
1130 StrList
= LinStr
.split()
1131 OrigImageBaseAddress
= int (StrList
[len(StrList
) - 1], 16)
1133 StrList
= LinStr
.split()
1134 if len (StrList
) > 4:
1135 if StrList
[3] == 'f' or StrList
[3] =='F':
1137 RelativeAddress
= int (StrList
[2], 16) - OrigImageBaseAddress
1138 FunctionList
.append ((Name
, RelativeAddress
))
1139 if ModuleInfo
.Arch
== 'IPF' and Name
.endswith('_ModuleEntryPoint'):
1141 # Get the real entry point address for IPF image.
1143 ModuleInfo
.Image
.EntryPoint
= RelativeAddress
1146 # Add general information.
1149 MapBuffer
.write('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName
, BaseAddress
, BaseAddress
+ ModuleInfo
.Image
.EntryPoint
))
1151 MapBuffer
.write('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName
, 0 - BaseAddress
, 0 - (BaseAddress
+ ModuleInfo
.Image
.EntryPoint
)))
1153 MapBuffer
.write('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName
, BaseAddress
, BaseAddress
+ ModuleInfo
.Image
.EntryPoint
))
1155 # Add guid and general seciton section.
1157 TextSectionAddress
= 0
1158 DataSectionAddress
= 0
1159 for SectionHeader
in ModuleInfo
.Image
.SectionHeaderList
:
1160 if SectionHeader
[0] == '.text':
1161 TextSectionAddress
= SectionHeader
[1]
1162 elif SectionHeader
[0] in ['.data', '.sdata']:
1163 DataSectionAddress
= SectionHeader
[1]
1165 MapBuffer
.write('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo
.Guid
, 0 - (BaseAddress
+ TextSectionAddress
), 0 - (BaseAddress
+ DataSectionAddress
)))
1167 MapBuffer
.write('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo
.Guid
, BaseAddress
+ TextSectionAddress
, BaseAddress
+ DataSectionAddress
))
1169 # Add debug image full path.
1171 MapBuffer
.write('(IMAGE=%s)\n\n' % (ModuleDebugImage
))
1173 # Add funtion address
1175 for Function
in FunctionList
:
1177 MapBuffer
.write(' -0x%010X %s\n' % (0 - (BaseAddress
+ Function
[1]), Function
[0]))
1179 MapBuffer
.write(' 0x%010X %s\n' % (BaseAddress
+ Function
[1], Function
[0]))
1183 # for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1186 BaseAddress
= BaseAddress
+ ModuleInfo
.Image
.Size
1188 ## Collect MAP information of all FVs
1190 def _CollectFvMapBuffer (self
, MapBuffer
, Wa
, ModuleList
):
1192 # First get the XIP base address for FV map file.
1193 GuidPattern
= re
.compile("[-a-fA-F0-9]+")
1194 GuidName
= re
.compile("\(GUID=[-a-fA-F0-9]+")
1195 for FvName
in Wa
.FdfProfile
.FvDict
.keys():
1196 FvMapBuffer
= os
.path
.join(Wa
.FvDir
, FvName
+ '.Fv.map')
1197 if not os
.path
.exists(FvMapBuffer
):
1199 FvMap
= open(FvMapBuffer
, 'r')
1200 #skip FV size information
1206 MatchGuid
= GuidPattern
.match(Line
)
1207 if MatchGuid
!= None:
1209 # Replace GUID with module name
1211 GuidString
= MatchGuid
.group()
1212 if GuidString
.upper() in ModuleList
:
1213 Line
= Line
.replace(GuidString
, ModuleList
[GuidString
.upper()].Name
)
1214 MapBuffer
.write('%s' % (Line
))
1216 # Add the debug image full path.
1218 MatchGuid
= GuidName
.match(Line
)
1219 if MatchGuid
!= None:
1220 GuidString
= MatchGuid
.group().split("=")[1]
1221 if GuidString
.upper() in ModuleList
:
1222 MapBuffer
.write('(IMAGE=%s)\n' % (os
.path
.join(ModuleList
[GuidString
.upper()].DebugDir
, ModuleList
[GuidString
.upper()].Name
+ '.efi')))
1226 ## Collect MAP information of all modules
1228 def _CollectModuleMapBuffer (self
, MapBuffer
, ModuleList
):
1229 sys
.stdout
.write ("Generate Load Module At Fix Address Map")
1231 PatchEfiImageList
= []
1239 # reserve 4K size in SMRAM to make SMM module address not from 0.
1241 IsIpfPlatform
= False
1242 if 'IPF' in self
.ArchList
:
1243 IsIpfPlatform
= True
1244 for ModuleGuid
in ModuleList
:
1245 Module
= ModuleList
[ModuleGuid
]
1246 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (Module
.MetaFile
, Module
.Arch
, Module
.ToolChain
, Module
.BuildTarget
)
1248 OutputImageFile
= ''
1249 for ResultFile
in Module
.CodaTargetList
:
1250 if str(ResultFile
.Target
).endswith('.efi'):
1252 # module list for PEI, DXE, RUNTIME and SMM
1254 OutputImageFile
= os
.path
.join(Module
.OutputDir
, Module
.Name
+ '.efi')
1255 ImageClass
= PeImageClass (OutputImageFile
)
1256 if not ImageClass
.IsValid
:
1257 EdkLogger
.error("build", FILE_PARSE_FAILURE
, ExtraData
=ImageClass
.ErrorInfo
)
1258 ImageInfo
= PeImageInfo(Module
.Name
, Module
.Guid
, Module
.Arch
, Module
.OutputDir
, Module
.DebugDir
, ImageClass
)
1259 if Module
.ModuleType
in ['PEI_CORE', 'PEIM', 'COMBINED_PEIM_DRIVER','PIC_PEIM', 'RELOCATABLE_PEIM', 'DXE_CORE']:
1260 PeiModuleList
[Module
.MetaFile
] = ImageInfo
1261 PeiSize
+= ImageInfo
.Image
.Size
1262 elif Module
.ModuleType
in ['BS_DRIVER', 'DXE_DRIVER', 'UEFI_DRIVER']:
1263 BtModuleList
[Module
.MetaFile
] = ImageInfo
1264 BtSize
+= ImageInfo
.Image
.Size
1265 elif Module
.ModuleType
in ['DXE_RUNTIME_DRIVER', 'RT_DRIVER', 'DXE_SAL_DRIVER', 'SAL_RT_DRIVER']:
1266 RtModuleList
[Module
.MetaFile
] = ImageInfo
1267 #IPF runtime driver needs to be at 2 page alignment.
1268 if IsIpfPlatform
and ImageInfo
.Image
.Size
% 0x2000 != 0:
1269 ImageInfo
.Image
.Size
= (ImageInfo
.Image
.Size
/ 0x2000 + 1) * 0x2000
1270 RtSize
+= ImageInfo
.Image
.Size
1271 elif Module
.ModuleType
in ['SMM_CORE', 'DXE_SMM_DRIVER']:
1272 SmmModuleList
[Module
.MetaFile
] = ImageInfo
1273 SmmSize
+= ImageInfo
.Image
.Size
1274 if Module
.ModuleType
== 'DXE_SMM_DRIVER':
1275 PiSpecVersion
= '0x00000000'
1276 if 'PI_SPECIFICATION_VERSION' in Module
.Module
.Specification
:
1277 PiSpecVersion
= Module
.Module
.Specification
['PI_SPECIFICATION_VERSION']
1278 # for PI specification < PI1.1, DXE_SMM_DRIVER also runs as BOOT time driver.
1279 if int(PiSpecVersion
, 16) < 0x0001000A:
1280 BtModuleList
[Module
.MetaFile
] = ImageInfo
1281 BtSize
+= ImageInfo
.Image
.Size
1284 # EFI image is final target.
1285 # Check EFI image contains patchable FixAddress related PCDs.
1287 if OutputImageFile
!= '':
1288 ModuleIsPatch
= False
1289 for Pcd
in Module
.ModulePcdList
:
1290 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
and Pcd
.TokenCName
in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_LIST
:
1291 ModuleIsPatch
= True
1293 if not ModuleIsPatch
:
1294 for Pcd
in Module
.LibraryPcdList
:
1295 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
and Pcd
.TokenCName
in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_LIST
:
1296 ModuleIsPatch
= True
1299 if not ModuleIsPatch
:
1302 # Module includes the patchable load fix address PCDs.
1303 # It will be fixed up later.
1305 PatchEfiImageList
.append (OutputImageFile
)
1308 # Get Top Memory address
1310 ReservedRuntimeMemorySize
= 0
1311 TopMemoryAddress
= 0
1312 if self
.LoadFixAddress
== 0xFFFFFFFFFFFFFFFF:
1313 TopMemoryAddress
= 0
1315 TopMemoryAddress
= self
.LoadFixAddress
1316 if TopMemoryAddress
< RtSize
+ BtSize
+ PeiSize
:
1317 EdkLogger
.error("build", PARAMETER_INVALID
, "FIX_LOAD_TOP_MEMORY_ADDRESS is too low to load driver")
1318 # Make IPF runtime driver at 2 page alignment.
1320 ReservedRuntimeMemorySize
= TopMemoryAddress
% 0x2000
1321 RtSize
= RtSize
+ ReservedRuntimeMemorySize
1324 # Patch FixAddress related PCDs into EFI image
1326 for EfiImage
in PatchEfiImageList
:
1327 EfiImageMap
= EfiImage
.replace('.efi', '.map')
1328 if not os
.path
.exists(EfiImageMap
):
1331 # Get PCD offset in EFI image by GenPatchPcdTable function
1333 PcdTable
= parsePcdInfoFromMapFile(EfiImageMap
, EfiImage
)
1335 # Patch real PCD value by PatchPcdValue tool
1337 for PcdInfo
in PcdTable
:
1339 if PcdInfo
[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE
:
1340 ReturnValue
, ErrorInfo
= PatchBinaryFile (EfiImage
, PcdInfo
[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE
, str (PeiSize
/0x1000))
1341 elif PcdInfo
[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE
:
1342 ReturnValue
, ErrorInfo
= PatchBinaryFile (EfiImage
, PcdInfo
[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE_DATA_TYPE
, str (BtSize
/0x1000))
1343 elif PcdInfo
[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE
:
1344 ReturnValue
, ErrorInfo
= PatchBinaryFile (EfiImage
, PcdInfo
[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE_DATA_TYPE
, str (RtSize
/0x1000))
1345 elif PcdInfo
[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE
and len (SmmModuleList
) > 0:
1346 ReturnValue
, ErrorInfo
= PatchBinaryFile (EfiImage
, PcdInfo
[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE_DATA_TYPE
, str (SmmSize
/0x1000))
1347 if ReturnValue
!= 0:
1348 EdkLogger
.error("build", PARAMETER_INVALID
, "Patch PCD value failed", ExtraData
=ErrorInfo
)
1350 MapBuffer
.write('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize
/0x1000))
1351 MapBuffer
.write('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize
/0x1000))
1352 MapBuffer
.write('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize
/0x1000))
1353 if len (SmmModuleList
) > 0:
1354 MapBuffer
.write('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize
/0x1000))
1356 PeiBaseAddr
= TopMemoryAddress
- RtSize
- BtSize
1357 BtBaseAddr
= TopMemoryAddress
- RtSize
1358 RtBaseAddr
= TopMemoryAddress
- ReservedRuntimeMemorySize
1360 self
._RebaseModule
(MapBuffer
, PeiBaseAddr
, PeiModuleList
, TopMemoryAddress
== 0)
1361 self
._RebaseModule
(MapBuffer
, BtBaseAddr
, BtModuleList
, TopMemoryAddress
== 0)
1362 self
._RebaseModule
(MapBuffer
, RtBaseAddr
, RtModuleList
, TopMemoryAddress
== 0)
1363 self
._RebaseModule
(MapBuffer
, 0x1000, SmmModuleList
, AddrIsOffset
= False, ModeIsSmm
= True)
1364 MapBuffer
.write('\n\n')
1365 sys
.stdout
.write ("\n")
1368 ## Save platform Map file
1370 def _SaveMapFile (self
, MapBuffer
, Wa
):
1372 # Map file path is got.
1374 MapFilePath
= os
.path
.join(Wa
.BuildDir
, Wa
.Name
+ '.map')
1376 # Save address map into MAP file.
1378 SaveFileOnChange(MapFilePath
, MapBuffer
.getvalue(), False)
1380 if self
.LoadFixAddress
!= 0:
1381 sys
.stdout
.write ("\nLoad Module At Fix Address Map file can be found at %s\n" %(MapFilePath))
1384 ## Build active platform for different build targets and different tool chains
1386 def _BuildPlatform(self
):
1387 for BuildTarget
in self
.BuildTargetList
:
1388 GlobalData
.gGlobalDefines
['TARGET'] = BuildTarget
1389 for ToolChain
in self
.ToolChainList
:
1390 GlobalData
.gGlobalDefines
['TOOLCHAIN'] = ToolChain
1391 GlobalData
.gGlobalDefines
['TOOL_CHAIN_TAG'] = ToolChain
1392 Wa
= WorkspaceAutoGen(
1409 self
.Fdf
= Wa
.FdfFile
1410 self
.LoadFixAddress
= Wa
.Platform
.LoadFixAddress
1411 self
.BuildReport
.AddPlatformReport(Wa
)
1412 self
.Progress
.Stop("done!")
1413 for Arch
in Wa
.ArchList
:
1414 GlobalData
.gGlobalDefines
['ARCH'] = Arch
1415 Pa
= PlatformAutoGen(Wa
, self
.PlatformFile
, BuildTarget
, ToolChain
, Arch
)
1416 for Module
in Pa
.Platform
.Modules
:
1417 # Get ModuleAutoGen object to generate C code file and makefile
1418 Ma
= ModuleAutoGen(Wa
, Module
, BuildTarget
, ToolChain
, Arch
, self
.PlatformFile
)
1421 self
.BuildModules
.append(Ma
)
1422 self
._BuildPa
(self
.Target
, Pa
)
1424 # Create MAP file when Load Fix Address is enabled.
1425 if self
.Target
in ["", "all", "fds"]:
1426 for Arch
in Wa
.ArchList
:
1427 GlobalData
.gGlobalDefines
['ARCH'] = Arch
1429 # Check whether the set fix address is above 4G for 32bit image.
1431 if (Arch
== 'IA32' or Arch
== 'ARM') and self
.LoadFixAddress
!= 0xFFFFFFFFFFFFFFFF and self
.LoadFixAddress
>= 0x100000000:
1432 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")
1437 for Pa
in Wa
.AutoGenObjectList
:
1438 for Ma
in Pa
.ModuleAutoGenList
:
1441 if not Ma
.IsLibrary
:
1442 ModuleList
[Ma
.Guid
.upper()] = Ma
1444 MapBuffer
= StringIO('')
1445 if self
.LoadFixAddress
!= 0:
1447 # Rebase module to the preferred memory address before GenFds
1449 self
._CollectModuleMapBuffer
(MapBuffer
, ModuleList
)
1452 # create FDS again for the updated EFI image
1454 self
._Build
("fds", Wa
)
1457 # Create MAP file for all platform FVs after GenFds.
1459 self
._CollectFvMapBuffer
(MapBuffer
, Wa
, ModuleList
)
1461 # Save MAP buffer into MAP file.
1463 self
._SaveMapFile
(MapBuffer
, Wa
)
1465 ## Build active module for different build targets, different tool chains and different archs
1467 def _BuildModule(self
):
1468 for BuildTarget
in self
.BuildTargetList
:
1469 GlobalData
.gGlobalDefines
['TARGET'] = BuildTarget
1470 for ToolChain
in self
.ToolChainList
:
1471 GlobalData
.gGlobalDefines
['TOOLCHAIN'] = ToolChain
1472 GlobalData
.gGlobalDefines
['TOOL_CHAIN_TAG'] = ToolChain
1474 # module build needs platform build information, so get platform
1477 Wa
= WorkspaceAutoGen(
1495 self
.Fdf
= Wa
.FdfFile
1496 self
.LoadFixAddress
= Wa
.Platform
.LoadFixAddress
1497 Wa
.CreateMakeFile(False)
1498 self
.Progress
.Stop("done!")
1500 for Arch
in Wa
.ArchList
:
1501 GlobalData
.gGlobalDefines
['ARCH'] = Arch
1502 Ma
= ModuleAutoGen(Wa
, self
.ModuleFile
, BuildTarget
, ToolChain
, Arch
, self
.PlatformFile
)
1503 if Ma
== None: continue
1505 self
.BuildModules
.append(Ma
)
1506 if not Ma
.IsBinaryModule
:
1507 self
._Build
(self
.Target
, Ma
, BuildModule
=True)
1509 self
.BuildReport
.AddPlatformReport(Wa
, MaList
)
1514 "Module for [%s] is not a component of active platform."\
1515 " Please make sure that the ARCH and inf file path are"\
1516 " given in the same as in [%s]" %\
1517 (', '.join(Wa
.ArchList
), self
.PlatformFile
),
1518 ExtraData
=self
.ModuleFile
1520 # Create MAP file when Load Fix Address is enabled.
1521 if self
.Target
== "fds" and self
.Fdf
:
1522 for Arch
in Wa
.ArchList
:
1524 # Check whether the set fix address is above 4G for 32bit image.
1526 if (Arch
== 'IA32' or Arch
== 'ARM') and self
.LoadFixAddress
!= 0xFFFFFFFFFFFFFFFF and self
.LoadFixAddress
>= 0x100000000:
1527 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")
1532 for Pa
in Wa
.AutoGenObjectList
:
1533 for Ma
in Pa
.ModuleAutoGenList
:
1536 if not Ma
.IsLibrary
:
1537 ModuleList
[Ma
.Guid
.upper()] = Ma
1539 MapBuffer
= StringIO('')
1540 if self
.LoadFixAddress
!= 0:
1542 # Rebase module to the preferred memory address before GenFds
1544 self
._CollectModuleMapBuffer
(MapBuffer
, ModuleList
)
1546 # create FDS again for the updated EFI image
1548 self
._Build
("fds", Wa
)
1550 # Create MAP file for all platform FVs after GenFds.
1552 self
._CollectFvMapBuffer
(MapBuffer
, Wa
, ModuleList
)
1554 # Save MAP buffer into MAP file.
1556 self
._SaveMapFile
(MapBuffer
, Wa
)
1558 ## Build a platform in multi-thread mode
1560 def _MultiThreadBuildPlatform(self
):
1561 for BuildTarget
in self
.BuildTargetList
:
1562 GlobalData
.gGlobalDefines
['TARGET'] = BuildTarget
1563 for ToolChain
in self
.ToolChainList
:
1564 GlobalData
.gGlobalDefines
['TOOLCHAIN'] = ToolChain
1565 GlobalData
.gGlobalDefines
['TOOL_CHAIN_TAG'] = ToolChain
1566 Wa
= WorkspaceAutoGen(
1583 self
.Fdf
= Wa
.FdfFile
1584 self
.LoadFixAddress
= Wa
.Platform
.LoadFixAddress
1585 self
.BuildReport
.AddPlatformReport(Wa
)
1586 Wa
.CreateMakeFile(False)
1588 # multi-thread exit flag
1589 ExitFlag
= threading
.Event()
1591 for Arch
in Wa
.ArchList
:
1592 GlobalData
.gGlobalDefines
['ARCH'] = Arch
1593 Pa
= PlatformAutoGen(Wa
, self
.PlatformFile
, BuildTarget
, ToolChain
, Arch
)
1597 for Inf
in Pa
.Platform
.Modules
:
1598 ModuleList
.append(Inf
)
1599 # Add the INF only list in FDF
1600 if GlobalData
.gFdfParser
!= None:
1601 for InfName
in GlobalData
.gFdfParser
.Profile
.InfList
:
1602 Inf
= PathClass(NormPath(InfName
), self
.WorkspaceDir
, Arch
)
1603 if Inf
in Pa
.Platform
.Modules
:
1605 ModuleList
.append(Inf
)
1606 for Module
in ModuleList
:
1607 # Get ModuleAutoGen object to generate C code file and makefile
1608 Ma
= ModuleAutoGen(Wa
, Module
, BuildTarget
, ToolChain
, Arch
, self
.PlatformFile
)
1612 # Not to auto-gen for targets 'clean', 'cleanlib', 'cleanall', 'run', 'fds'
1613 if self
.Target
not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1614 # for target which must generate AutoGen code and makefile
1615 if not self
.SkipAutoGen
or self
.Target
== 'genc':
1616 Ma
.CreateCodeFile(True)
1617 if self
.Target
== "genc":
1620 if not self
.SkipAutoGen
or self
.Target
== 'genmake':
1621 Ma
.CreateMakeFile(True)
1622 if self
.Target
== "genmake":
1624 self
.BuildModules
.append(Ma
)
1625 self
.Progress
.Stop("done!")
1627 for Ma
in self
.BuildModules
:
1628 # Generate build task for the module
1629 if not Ma
.IsBinaryModule
:
1630 Bt
= BuildTask
.New(ModuleMakeUnit(Ma
, self
.Target
))
1631 # Break build if any build thread has error
1632 if BuildTask
.HasError():
1633 # we need a full version of makefile for platform
1635 BuildTask
.WaitForComplete()
1636 Pa
.CreateMakeFile(False)
1637 EdkLogger
.error("build", BUILD_ERROR
, "Failed to build module", ExtraData
=GlobalData
.gBuildingModule
)
1638 # Start task scheduler
1639 if not BuildTask
.IsOnGoing():
1640 BuildTask
.StartScheduler(self
.ThreadNumber
, ExitFlag
)
1642 # in case there's an interruption. we need a full version of makefile for platform
1643 Pa
.CreateMakeFile(False)
1644 if BuildTask
.HasError():
1645 EdkLogger
.error("build", BUILD_ERROR
, "Failed to build module", ExtraData
=GlobalData
.gBuildingModule
)
1648 # Save temp tables to a TmpTableDict.
1650 for Key
in Wa
.BuildDatabase
._CACHE
_:
1651 if Wa
.BuildDatabase
._CACHE
_[Key
]._RawData
and Wa
.BuildDatabase
._CACHE
_[Key
]._RawData
._Table
and Wa
.BuildDatabase
._CACHE
_[Key
]._RawData
._Table
.Table
:
1652 if TemporaryTablePattern
.match(Wa
.BuildDatabase
._CACHE
_[Key
]._RawData
._Table
.Table
):
1653 TmpTableDict
[Wa
.BuildDatabase
._CACHE
_[Key
]._RawData
._Table
.Table
] = Wa
.BuildDatabase
._CACHE
_[Key
]._RawData
._Table
.Cur
1656 # All modules have been put in build tasks queue. Tell task scheduler
1657 # to exit if all tasks are completed
1660 BuildTask
.WaitForComplete()
1661 self
.CreateAsBuiltInf()
1664 # Check for build error, and raise exception if one
1665 # has been signaled.
1667 if BuildTask
.HasError():
1668 EdkLogger
.error("build", BUILD_ERROR
, "Failed to build module", ExtraData
=GlobalData
.gBuildingModule
)
1670 # Create MAP file when Load Fix Address is enabled.
1671 if self
.Target
in ["", "all", "fds"]:
1672 for Arch
in Wa
.ArchList
:
1674 # Check whether the set fix address is above 4G for 32bit image.
1676 if (Arch
== 'IA32' or Arch
== 'ARM') and self
.LoadFixAddress
!= 0xFFFFFFFFFFFFFFFF and self
.LoadFixAddress
>= 0x100000000:
1677 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")
1682 for Pa
in Wa
.AutoGenObjectList
:
1683 for Ma
in Pa
.ModuleAutoGenList
:
1686 if not Ma
.IsLibrary
:
1687 ModuleList
[Ma
.Guid
.upper()] = Ma
1689 # Rebase module to the preferred memory address before GenFds
1691 MapBuffer
= StringIO('')
1692 if self
.LoadFixAddress
!= 0:
1693 self
._CollectModuleMapBuffer
(MapBuffer
, ModuleList
)
1697 # Generate FD image if there's a FDF file found
1699 LaunchCommand(Wa
.GenFdsCommand
, os
.getcwd())
1702 # Create MAP file for all platform FVs after GenFds.
1704 self
._CollectFvMapBuffer
(MapBuffer
, Wa
, ModuleList
)
1706 # Save MAP buffer into MAP file.
1708 self
._SaveMapFile
(MapBuffer
, Wa
)
1710 ## Generate GuidedSectionTools.txt in the FV directories.
1712 def CreateGuidedSectionToolsFile(self
):
1713 for BuildTarget
in self
.BuildTargetList
:
1714 for ToolChain
in self
.ToolChainList
:
1715 Wa
= WorkspaceAutoGen(
1732 if not os
.path
.exists(FvDir
):
1735 for Arch
in self
.ArchList
:
1736 # Build up the list of supported architectures for this build
1737 prefix
= '%s_%s_%s_' % (BuildTarget
, ToolChain
, Arch
)
1739 # Look through the tool definitions for GUIDed tools
1741 for (attrib
, value
) in self
.ToolDef
.ToolsDefTxtDictionary
.iteritems():
1742 if attrib
.upper().endswith('_GUID'):
1743 split
= attrib
.split('_')
1744 thisPrefix
= '_'.join(split
[0:3]) + '_'
1745 if thisPrefix
== prefix
:
1746 guid
= self
.ToolDef
.ToolsDefTxtDictionary
[attrib
]
1749 path
= '_'.join(split
[0:4]) + '_PATH'
1750 path
= self
.ToolDef
.ToolsDefTxtDictionary
[path
]
1751 path
= self
.GetFullPathOfTool(path
)
1752 guidAttribs
.append((guid
, toolName
, path
))
1754 # Write out GuidedSecTools.txt
1755 toolsFile
= os
.path
.join(FvDir
, 'GuidedSectionTools.txt')
1756 toolsFile
= open(toolsFile
, 'wt')
1757 for guidedSectionTool
in guidAttribs
:
1758 print >> toolsFile
, ' '.join(guidedSectionTool
)
1761 ## Returns the full path of the tool.
1763 def GetFullPathOfTool (self
, tool
):
1764 if os
.path
.exists(tool
):
1765 return os
.path
.realpath(tool
)
1767 # We need to search for the tool using the
1768 # PATH environment variable.
1769 for dirInPath
in os
.environ
['PATH'].split(os
.pathsep
):
1770 foundPath
= os
.path
.join(dirInPath
, tool
)
1771 if os
.path
.exists(foundPath
):
1772 return os
.path
.realpath(foundPath
)
1774 # If the tool was not found in the path then we just return
1778 ## Launch the module or platform build
1781 if not self
.ModuleFile
:
1782 if not self
.SpawnMode
or self
.Target
not in ["", "all"]:
1783 self
.SpawnMode
= False
1784 self
._BuildPlatform
()
1786 self
._MultiThreadBuildPlatform
()
1787 self
.CreateGuidedSectionToolsFile()
1789 self
.SpawnMode
= False
1792 def CreateAsBuiltInf(self
):
1793 for Module
in self
.BuildModules
:
1794 Module
.CreateAsBuiltInf()
1795 self
.BuildModules
= []
1796 ## Do some clean-up works when error occurred
1797 def Relinquish(self
):
1798 OldLogLevel
= EdkLogger
.GetLevel()
1799 EdkLogger
.SetLevel(EdkLogger
.ERROR
)
1800 #self.DumpBuildData()
1801 Utils
.Progressor
.Abort()
1802 if self
.SpawnMode
== True:
1804 EdkLogger
.SetLevel(OldLogLevel
)
1806 def DumpBuildData(self
):
1807 CacheDirectory
= os
.path
.join(self
.WorkspaceDir
, gBuildCacheDir
)
1808 Utils
.CreateDirectory(CacheDirectory
)
1809 Utils
.DataDump(Utils
.gFileTimeStampCache
, os
.path
.join(CacheDirectory
, "gFileTimeStampCache"))
1810 Utils
.DataDump(Utils
.gDependencyDatabase
, os
.path
.join(CacheDirectory
, "gDependencyDatabase"))
1812 def RestoreBuildData(self
):
1813 FilePath
= os
.path
.join(self
.WorkspaceDir
, gBuildCacheDir
, "gFileTimeStampCache")
1814 if Utils
.gFileTimeStampCache
== {} and os
.path
.isfile(FilePath
):
1815 Utils
.gFileTimeStampCache
= Utils
.DataRestore(FilePath
)
1816 if Utils
.gFileTimeStampCache
== None:
1817 Utils
.gFileTimeStampCache
= {}
1819 FilePath
= os
.path
.join(self
.WorkspaceDir
, gBuildCacheDir
, "gDependencyDatabase")
1820 if Utils
.gDependencyDatabase
== {} and os
.path
.isfile(FilePath
):
1821 Utils
.gDependencyDatabase
= Utils
.DataRestore(FilePath
)
1822 if Utils
.gDependencyDatabase
== None:
1823 Utils
.gDependencyDatabase
= {}
1825 def ParseDefines(DefineList
=[]):
1827 if DefineList
!= None:
1828 for Define
in DefineList
:
1829 DefineTokenList
= Define
.split("=", 1)
1830 if not GlobalData
.gMacroNamePattern
.match(DefineTokenList
[0]):
1831 EdkLogger
.error('build', FORMAT_INVALID
,
1832 "The macro name must be in the pattern [A-Z][A-Z0-9_]*",
1833 ExtraData
=DefineTokenList
[0])
1835 if len(DefineTokenList
) == 1:
1836 DefineDict
[DefineTokenList
[0]] = "TRUE"
1838 DefineDict
[DefineTokenList
[0]] = DefineTokenList
[1].strip()
1842 def SingleCheckCallback(option
, opt_str
, value
, parser
):
1843 if option
not in gParamCheck
:
1844 setattr(parser
.values
, option
.dest
, value
)
1845 gParamCheck
.append(option
)
1847 parser
.error("Option %s only allows one instance in command line!" % option
)
1849 ## Parse command line options
1851 # Using standard Python module optparse to parse command line option of this tool.
1853 # @retval Opt A optparse.Values object containing the parsed options
1854 # @retval Args Target of build command
1856 def MyOptionParser():
1857 Parser
= OptionParser(description
=__copyright__
,version
=__version__
,prog
="build.exe",usage
="%prog [options] [all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]")
1858 Parser
.add_option("-a", "--arch", action
="append", type="choice", choices
=['IA32','X64','IPF','EBC','ARM', 'AARCH64'], dest
="TargetArch",
1859 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.")
1860 Parser
.add_option("-p", "--platform", action
="callback", type="string", dest
="PlatformFile", callback
=SingleCheckCallback
,
1861 help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.")
1862 Parser
.add_option("-m", "--module", action
="callback", type="string", dest
="ModuleFile", callback
=SingleCheckCallback
,
1863 help="Build the module specified by the INF file name argument.")
1864 Parser
.add_option("-b", "--buildtarget", type="string", dest
="BuildTarget", help="Using the TARGET to build the platform, overriding target.txt's TARGET definition.",
1866 Parser
.add_option("-t", "--tagname", action
="append", type="string", dest
="ToolChain",
1867 help="Using the Tool Chain Tagname to build the platform, overriding target.txt's TOOL_CHAIN_TAG definition.")
1868 Parser
.add_option("-x", "--sku-id", action
="callback", type="string", dest
="SkuId", callback
=SingleCheckCallback
,
1869 help="Using this name of SKU ID to build the platform, overriding SKUID_IDENTIFIER in DSC file.")
1871 Parser
.add_option("-n", action
="callback", type="int", dest
="ThreadNumber", callback
=SingleCheckCallback
,
1872 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.")
1874 Parser
.add_option("-f", "--fdf", action
="callback", type="string", dest
="FdfFile", callback
=SingleCheckCallback
,
1875 help="The name of the FDF file to use, which overrides the setting in the DSC file.")
1876 Parser
.add_option("-r", "--rom-image", action
="append", type="string", dest
="RomImage", default
=[],
1877 help="The name of FD to be generated. The name must be from [FD] section in FDF file.")
1878 Parser
.add_option("-i", "--fv-image", action
="append", type="string", dest
="FvImage", default
=[],
1879 help="The name of FV to be generated. The name must be from [FV] section in FDF file.")
1880 Parser
.add_option("-C", "--capsule-image", action
="append", type="string", dest
="CapName", default
=[],
1881 help="The name of Capsule to be generated. The name must be from [Capsule] section in FDF file.")
1882 Parser
.add_option("-u", "--skip-autogen", action
="store_true", dest
="SkipAutoGen", help="Skip AutoGen step.")
1883 Parser
.add_option("-e", "--re-parse", action
="store_true", dest
="Reparse", help="Re-parse all meta-data files.")
1885 Parser
.add_option("-c", "--case-insensitive", action
="store_true", dest
="CaseInsensitive", default
=False, help="Don't check case of file name.")
1887 Parser
.add_option("-w", "--warning-as-error", action
="store_true", dest
="WarningAsError", help="Treat warning in tools as error.")
1888 Parser
.add_option("-j", "--log", action
="store", dest
="LogFile", help="Put log in specified file as well as on console.")
1890 Parser
.add_option("-s", "--silent", action
="store_true", type=None, dest
="SilentMode",
1891 help="Make use of silent mode of (n)make.")
1892 Parser
.add_option("-q", "--quiet", action
="store_true", type=None, help="Disable all messages except FATAL ERRORS.")
1893 Parser
.add_option("-v", "--verbose", action
="store_true", type=None, help="Turn on verbose output with informational messages printed, "\
1894 "including library instances selected, final dependency expression, "\
1895 "and warning messages, etc.")
1896 Parser
.add_option("-d", "--debug", action
="store", type="int", help="Enable debug messages at specified level.")
1897 Parser
.add_option("-D", "--define", action
="append", type="string", dest
="Macros", help="Macro: \"Name [= Value]\".")
1899 Parser
.add_option("-y", "--report-file", action
="store", dest
="ReportFile", help="Create/overwrite the report to the specified filename.")
1900 Parser
.add_option("-Y", "--report-type", action
="append", type="choice", choices
=['PCD','LIBRARY','FLASH','DEPEX','BUILD_FLAGS','FIXED_ADDRESS', 'EXECUTION_ORDER'], dest
="ReportType", default
=[],
1901 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]. "\
1902 "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]")
1903 Parser
.add_option("-F", "--flag", action
="store", type="string", dest
="Flag",
1904 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. "\
1905 "This option can also be specified by setting *_*_*_BUILD_FLAGS in [BuildOptions] section of platform DSC. If they are both specified, this value "\
1906 "will override the setting in [BuildOptions] section of platform DSC.")
1907 Parser
.add_option("-N", "--no-cache", action
="store_true", dest
="DisableCache", default
=False, help="Disable build cache mechanism")
1908 Parser
.add_option("--ignore-sources", action
="store_true", dest
="IgnoreSources", default
=False, help="Focus to a binary build and ignore all source files")
1910 (Opt
, Args
)=Parser
.parse_args()
1913 ## Tool entrance method
1915 # This method mainly dispatch specific methods per the command line options.
1916 # If no error found, return zero value so the caller of this tool can know
1917 # if it's executed successfully or not.
1919 # @retval 0 Tool was successful
1920 # @retval 1 Tool failed
1923 StartTime
= time
.time()
1925 # Initialize log system
1926 EdkLogger
.Initialize()
1929 # Parse the options and args
1931 (Option
, Target
) = MyOptionParser()
1932 GlobalData
.gOptions
= Option
1933 GlobalData
.gCaseInsensitive
= Option
.CaseInsensitive
1936 if Option
.verbose
!= None:
1937 EdkLogger
.SetLevel(EdkLogger
.VERBOSE
)
1938 elif Option
.quiet
!= None:
1939 EdkLogger
.SetLevel(EdkLogger
.QUIET
)
1940 elif Option
.debug
!= None:
1941 EdkLogger
.SetLevel(Option
.debug
+ 1)
1943 EdkLogger
.SetLevel(EdkLogger
.INFO
)
1945 if Option
.LogFile
!= None:
1946 EdkLogger
.SetLogFile(Option
.LogFile
)
1948 if Option
.WarningAsError
== True:
1949 EdkLogger
.SetWarningAsError()
1951 if platform
.platform().find("Windows") >= 0:
1952 GlobalData
.gIsWindows
= True
1954 GlobalData
.gIsWindows
= False
1956 EdkLogger
.quiet("Build environment: %s" % platform
.platform())
1957 EdkLogger
.quiet(time
.strftime("Build start time: %H:%M:%S, %b.%d %Y\n", time
.localtime()));
1961 if len(Target
) == 0:
1963 elif len(Target
) >= 2:
1964 EdkLogger
.error("build", OPTION_NOT_SUPPORTED
, "More than one targets are not supported.",
1965 ExtraData
="Please select one of: %s" %(' '.join(gSupportedTarget
)))
1967 Target
= Target
[0].lower()
1969 if Target
not in gSupportedTarget
:
1970 EdkLogger
.error("build", OPTION_NOT_SUPPORTED
, "Not supported target [%s]." % Target
,
1971 ExtraData
="Please select one of: %s" %(' '.join(gSupportedTarget
)))
1974 # Check environment variable: EDK_TOOLS_PATH, WORKSPACE, PATH
1977 GlobalData
.gCommandLineDefines
.update(ParseDefines(Option
.Macros
))
1979 Workspace
= os
.getenv("WORKSPACE")
1981 # Get files real name in workspace dir
1983 GlobalData
.gAllFiles
= Utils
.DirCache(Workspace
)
1985 WorkingDirectory
= os
.getcwd()
1986 if not Option
.ModuleFile
:
1987 FileList
= glob
.glob(os
.path
.normpath(os
.path
.join(WorkingDirectory
, '*.inf')))
1988 FileNum
= len(FileList
)
1990 EdkLogger
.error("build", OPTION_NOT_SUPPORTED
, "There are %d INF files in %s." % (FileNum
, WorkingDirectory
),
1991 ExtraData
="Please use '-m <INF_FILE_PATH>' switch to choose one.")
1993 Option
.ModuleFile
= NormFile(FileList
[0], Workspace
)
1995 if Option
.ModuleFile
:
1996 if os
.path
.isabs (Option
.ModuleFile
):
1997 if os
.path
.normcase (os
.path
.normpath(Option
.ModuleFile
)).find (Workspace
) == 0:
1998 Option
.ModuleFile
= NormFile(os
.path
.normpath(Option
.ModuleFile
), Workspace
)
1999 Option
.ModuleFile
= PathClass(Option
.ModuleFile
, Workspace
)
2000 ErrorCode
, ErrorInfo
= Option
.ModuleFile
.Validate(".inf", False)
2002 EdkLogger
.error("build", ErrorCode
, ExtraData
=ErrorInfo
)
2004 if Option
.PlatformFile
!= None:
2005 if os
.path
.isabs (Option
.PlatformFile
):
2006 if os
.path
.normcase (os
.path
.normpath(Option
.PlatformFile
)).find (Workspace
) == 0:
2007 Option
.PlatformFile
= NormFile(os
.path
.normpath(Option
.PlatformFile
), Workspace
)
2008 Option
.PlatformFile
= PathClass(Option
.PlatformFile
, Workspace
)
2010 if Option
.FdfFile
!= None:
2011 if os
.path
.isabs (Option
.FdfFile
):
2012 if os
.path
.normcase (os
.path
.normpath(Option
.FdfFile
)).find (Workspace
) == 0:
2013 Option
.FdfFile
= NormFile(os
.path
.normpath(Option
.FdfFile
), Workspace
)
2014 Option
.FdfFile
= PathClass(Option
.FdfFile
, Workspace
)
2015 ErrorCode
, ErrorInfo
= Option
.FdfFile
.Validate(".fdf", False)
2017 EdkLogger
.error("build", ErrorCode
, ExtraData
=ErrorInfo
)
2019 if Option
.Flag
!= None and Option
.Flag
not in ['-c', '-s']:
2020 EdkLogger
.error("build", OPTION_VALUE_INVALID
, "UNI flag must be one of -c or -s")
2022 MyBuild
= Build(Target
, Workspace
, Option
)
2023 GlobalData
.gCommandLineDefines
['ARCH'] = ' '.join(MyBuild
.ArchList
)
2025 # Drop temp tables to avoid database locked.
2026 for TmpTableName
in TmpTableDict
:
2027 SqlCommand
= """drop table IF EXISTS %s""" % TmpTableName
2028 TmpTableDict
[TmpTableName
].execute(SqlCommand
)
2029 #MyBuild.DumpBuildData()
2030 except FatalError
, X
:
2032 # for multi-thread build exits safely
2033 MyBuild
.Relinquish()
2034 if Option
!= None and Option
.debug
!= None:
2035 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
2036 ReturnCode
= X
.args
[0]
2038 # error from Fdf parser
2040 # for multi-thread build exits safely
2041 MyBuild
.Relinquish()
2042 if Option
!= None and Option
.debug
!= None:
2043 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
2045 EdkLogger
.error(X
.ToolName
, FORMAT_INVALID
, File
=X
.FileName
, Line
=X
.LineNumber
, ExtraData
=X
.Message
, RaiseError
= False)
2046 ReturnCode
= FORMAT_INVALID
2047 except KeyboardInterrupt:
2048 ReturnCode
= ABORT_ERROR
2049 if Option
!= None and Option
.debug
!= None:
2050 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
2053 # for multi-thread build exits safely
2054 MyBuild
.Relinquish()
2056 # try to get the meta-file from the object causing exception
2057 Tb
= sys
.exc_info()[-1]
2058 MetaFile
= GlobalData
.gProcessingFile
2060 if 'self' in Tb
.tb_frame
.f_locals
and hasattr(Tb
.tb_frame
.f_locals
['self'], 'MetaFile'):
2061 MetaFile
= Tb
.tb_frame
.f_locals
['self'].MetaFile
2066 "Unknown fatal error when processing [%s]" % MetaFile
,
2067 ExtraData
="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
2070 EdkLogger
.quiet("(Python %s on %s) " % (platform
.python_version(), sys
.platform
) + traceback
.format_exc())
2071 ReturnCode
= CODE_ERROR
2073 Utils
.Progressor
.Abort()
2077 elif ReturnCode
== ABORT_ERROR
:
2078 Conclusion
= "Aborted"
2080 Conclusion
= "Failed"
2081 FinishTime
= time
.time()
2082 BuildDuration
= time
.gmtime(int(round(FinishTime
- StartTime
)))
2083 BuildDurationStr
= ""
2084 if BuildDuration
.tm_yday
> 1:
2085 BuildDurationStr
= time
.strftime("%H:%M:%S", BuildDuration
) + ", %d day(s)"%(BuildDuration
.tm_yday
- 1)
2087 BuildDurationStr
= time
.strftime("%H:%M:%S", BuildDuration
)
2089 MyBuild
.BuildReport
.GenerateReport(BuildDurationStr
)
2091 EdkLogger
.SetLevel(EdkLogger
.QUIET
)
2092 EdkLogger
.quiet("\n- %s -" % Conclusion
)
2093 EdkLogger
.quiet(time
.strftime("Build end time: %H:%M:%S, %b.%d %Y", time
.localtime()))
2094 EdkLogger
.quiet("Build total time: %s\n" % BuildDurationStr
)
2097 if __name__
== '__main__':
2099 ## 0-127 is a safe return range, and 1 is a standard default error
2100 if r
< 0 or r
> 127: r
= 1