]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/build/build.py
This patch is going to:
[mirror_edk2.git] / BaseTools / Source / Python / build / build.py
1 ## @file
2 # build a platform or a module
3 #
4 # Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
5 #
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
10 #
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.
13 #
14
15 ##
16 # Import Modules
17 #
18 import Common.LongFilePathOs as os
19 import re
20 import StringIO
21 import sys
22 import glob
23 import time
24 import platform
25 import traceback
26 import encodings.ascii
27
28 from struct import *
29 from threading import *
30 from optparse import OptionParser
31 from subprocess import *
32 from Common import Misc as Utils
33
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 *
43
44 from BuildReport import BuildReport
45 from GenPatchPcdTable.GenPatchPcdTable import *
46 from PatchPcdValue.PatchPcdValue import *
47
48 import Common.EdkLogger
49 import Common.GlobalData as GlobalData
50
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."
55
56 ## standard targets of build command
57 gSupportedTarget = ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run']
58
59 ## build configuration file
60 gBuildConfiguration = "Conf/target.txt"
61 gBuildCacheDir = "Conf/.cache"
62 gToolsDefinition = "Conf/tools_def.txt"
63
64 TemporaryTablePattern = re.compile(r'^_\d+_\d+_[a-fA-F0-9]+$')
65 TmpTableDict = {}
66
67 ## Check environment PATH variable to make sure the specified tool is found
68 #
69 # If the tool is found in the PATH, then True is returned
70 # Otherwise, False is returned
71 #
72 def IsToolInPath(tool):
73 if os.environ.has_key('PATHEXT'):
74 extns = os.environ['PATHEXT'].split(os.path.pathsep)
75 else:
76 extns = ('',)
77 for pathDir in os.environ['PATH'].split(os.path.pathsep):
78 for ext in extns:
79 if os.path.exists(os.path.join(pathDir, tool + ext)):
80 return True
81 return False
82
83 ## Check environment variables
84 #
85 # Check environment variables that must be set for build. Currently they are
86 #
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
90 #
91 # If any of above environment variable is not set or has error, the build
92 # will be broken.
93 #
94 def CheckEnvVariable():
95 # check WORKSPACE
96 if "WORKSPACE" not in os.environ:
97 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",
98 ExtraData="WORKSPACE")
99
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
107
108 #
109 # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP
110 #
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"]
117
118 #
119 # Unify case of characters on case-insensitive systems
120 #
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"]))
124
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"])
129
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)
138 else:
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)
147 else:
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)
153
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))
164
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")
169
170 # check PATH
171 if "PATH" not in os.environ:
172 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",
173 ExtraData="PATH")
174
175 GlobalData.gWorkspace = WorkspaceDir
176 GlobalData.gEfiSource = EfiSourceDir
177 GlobalData.gEdkSource = EdkSourceDir
178 GlobalData.gEcpSource = EcpSourceDir
179
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"]
185
186 ## Get normalized file path
187 #
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.
190 #
191 # @param FilePath File path to be normalized
192 # @param Workspace Workspace path which the FilePath will be checked against
193 #
194 # @retval string The normalized file path
195 #
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)
200 else:
201 FileFullPath = os.path.normpath(os.path.join(Workspace, FilePath))
202
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)
206
207 # remove workspace directory from the beginning part of the file path
208 if Workspace[-1] in ["\\", "/"]:
209 return FileFullPath[len(Workspace):]
210 else:
211 return FileFullPath[(len(Workspace) + 1):]
212
213 ## Get the output of an external program
214 #
215 # This is the entrance method of thread reading output of an external program and
216 # putting them in STDOUT/STDERR of current program.
217 #
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
221 #
222 def ReadMessage(From, To, ExitFlag):
223 while True:
224 # read one line a time
225 Line = From.readline()
226 # empty string means "end"
227 if Line != None and Line != "":
228 To(Line.rstrip())
229 else:
230 break
231 if ExitFlag.isSet():
232 break
233
234 ## Launch an external program
235 #
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
239 # redirection work.
240 #
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
243 #
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)
248
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()
256
257 Proc = None
258 EndOfProcedure = None
259 try:
260 # launch the command
261 Proc = Popen(Command, stdout=PIPE, stderr=PIPE, env=os.environ, cwd=WorkingDir, bufsize=-1)
262
263 # launch two threads to read the STDOUT and STDERR
264 EndOfProcedure = Event()
265 EndOfProcedure.clear()
266 if Proc.stdout:
267 StdOutThread = Thread(target=ReadMessage, args=(Proc.stdout, EdkLogger.info, EndOfProcedure))
268 StdOutThread.setName("STDOUT-Redirector")
269 StdOutThread.setDaemon(False)
270 StdOutThread.start()
271
272 if Proc.stderr:
273 StdErrThread = Thread(target=ReadMessage, args=(Proc.stderr, EdkLogger.quiet, EndOfProcedure))
274 StdErrThread.setName("STDERR-Redirector")
275 StdErrThread.setDaemon(False)
276 StdErrThread.start()
277
278 # waiting for program exit
279 Proc.wait()
280 except: # in case of aborting
281 # terminate the threads redirecting the program output
282 if EndOfProcedure != None:
283 EndOfProcedure.set()
284 if Proc == 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))
288
289 if Proc.stdout:
290 StdOutThread.join()
291 if Proc.stderr:
292 StdErrThread.join()
293
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))
299
300 ## The smallest unit that can be built in multi-thread build mode
301 #
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
304 # missing build.
305 #
306 # Currently the "Obj" should be only ModuleAutoGen or PlatformAutoGen objects.
307 #
308 class BuildUnit:
309 ## The constructor
310 #
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
316 #
317 def __init__(self, Obj, BuildCommand, Target, Dependency, WorkingDir="."):
318 self.BuildObject = Obj
319 self.Dependency = Dependency
320 self.WorkingDir = WorkingDir
321 self.Target = Target
322 self.BuildCommand = BuildCommand
323 if not 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),
328 ExtraData=str(Obj))
329
330
331 ## str() method
332 #
333 # It just returns the string representation of self.BuildObject
334 #
335 # @param self The object pointer
336 #
337 def __str__(self):
338 return str(self.BuildObject)
339
340 ## "==" operator method
341 #
342 # It just compares self.BuildObject with "Other". So self.BuildObject must
343 # provide its own __eq__() method.
344 #
345 # @param self The object pointer
346 # @param Other The other BuildUnit object compared to
347 #
348 def __eq__(self, Other):
349 return Other != None and self.BuildObject == Other.BuildObject \
350 and self.BuildObject.Arch == Other.BuildObject.Arch
351
352 ## hash() method
353 #
354 # It just returns the hash value of self.BuildObject which must be hashable.
355 #
356 # @param self The object pointer
357 #
358 def __hash__(self):
359 return hash(self.BuildObject) + hash(self.BuildObject.Arch)
360
361 def __repr__(self):
362 return repr(self.BuildObject)
363
364 ## The smallest module unit that can be built by nmake/make command in multi-thread build mode
365 #
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.
369 #
370 # Currently the "Obj" should be only ModuleAutoGen object.
371 #
372 class ModuleMakeUnit(BuildUnit):
373 ## The constructor
374 #
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
378 #
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"
384
385 ## The smallest platform unit that can be built by nmake/make command in multi-thread build mode
386 #
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.
390 #
391 # Currently the "Obj" should be only PlatformAutoGen object.
392 #
393 class PlatformMakeUnit(BuildUnit):
394 ## The constructor
395 #
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
399 #
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)
404
405 ## The class representing the task of a module build or platform build
406 #
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.
409 #
410 class BuildTask:
411 # queue for tasks waiting for schedule
412 _PendingQueue = sdict()
413 _PendingQueueLock = threading.Lock()
414
415 # queue for tasks ready for running
416 _ReadyQueue = sdict()
417 _ReadyQueueLock = threading.Lock()
418
419 # queue for run tasks
420 _RunningQueue = sdict()
421 _RunningQueueLock = threading.Lock()
422
423 # queue containing all build tasks, in case duplicate build
424 _TaskQueue = sdict()
425
426 # flag indicating error occurs in a running thread
427 _ErrorFlag = threading.Event()
428 _ErrorFlag.clear()
429 _ErrorMessage = ""
430
431 # BoundedSemaphore object used to control the number of running threads
432 _Thread = None
433
434 # flag indicating if the scheduler is started or not
435 _SchedulerStopped = threading.Event()
436 _SchedulerStopped.set()
437
438 ## Start the task scheduler thread
439 #
440 # @param MaxThreadNumber The maximum thread number
441 # @param ExitFlag Flag used to end the scheduler
442 #
443 @staticmethod
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():
451 time.sleep(0.01)
452
453 ## Scheduler method
454 #
455 # @param MaxThreadNumber The maximum thread number
456 # @param ExitFlag Flag used to end the scheduler
457 #
458 @staticmethod
459 def Scheduler(MaxThreadNumber, ExitFlag):
460 BuildTask._SchedulerStopped.clear()
461 try:
462 # use BoundedSemaphore to control the maximum running threads
463 BuildTask._Thread = BoundedSemaphore(MaxThreadNumber)
464 #
465 # scheduling loop, which will exits when no pending/ready task and
466 # indicated to do so, or there's error in running thread
467 #
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)))
472
473 # get all pending tasks
474 BuildTask._PendingQueueLock.acquire()
475 BuildObjectList = BuildTask._PendingQueue.keys()
476 #
477 # check if their dependency is resolved, and if true, move them
478 # into ready queue
479 #
480 for BuildObject in BuildObjectList:
481 Bt = BuildTask._PendingQueue[BuildObject]
482 if Bt.IsReady():
483 BuildTask._ReadyQueue[BuildObject] = BuildTask._PendingQueue.pop(BuildObject)
484 BuildTask._PendingQueueLock.release()
485
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:
490 break
491
492 # wait for active thread(s) exit
493 BuildTask._Thread.acquire(True)
494
495 # start a new build thread
496 Bo = BuildTask._ReadyQueue.keys()[0]
497 Bt = BuildTask._ReadyQueue.pop(Bo)
498
499 # move into running queue
500 BuildTask._RunningQueueLock.acquire()
501 BuildTask._RunningQueue[Bo] = Bt
502 BuildTask._RunningQueueLock.release()
503
504 Bt.Start()
505 # avoid tense loop
506 time.sleep(0.01)
507
508 # avoid tense loop
509 time.sleep(0.01)
510
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()]))
518 # avoid tense loop
519 time.sleep(0.1)
520 except BaseException, X:
521 #
522 # TRICK: hide the output of threads left runing, so that the user can
523 # catch the error message easily
524 #
525 EdkLogger.SetLevel(EdkLogger.ERROR)
526 BuildTask._ErrorFlag.set()
527 BuildTask._ErrorMessage = "build thread scheduler error\n\t%s" % str(X)
528
529 BuildTask._PendingQueue.clear()
530 BuildTask._ReadyQueue.clear()
531 BuildTask._RunningQueue.clear()
532 BuildTask._TaskQueue.clear()
533 BuildTask._SchedulerStopped.set()
534
535 ## Wait for all running method exit
536 #
537 @staticmethod
538 def WaitForComplete():
539 BuildTask._SchedulerStopped.wait()
540
541 ## Check if the scheduler is running or not
542 #
543 @staticmethod
544 def IsOnGoing():
545 return not BuildTask._SchedulerStopped.isSet()
546
547 ## Abort the build
548 @staticmethod
549 def Abort():
550 if BuildTask.IsOnGoing():
551 BuildTask._ErrorFlag.set()
552 BuildTask.WaitForComplete()
553
554 ## Check if there's error in running thread
555 #
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.
558 #
559 @staticmethod
560 def HasError():
561 return BuildTask._ErrorFlag.isSet()
562
563 ## Get error message in running thread
564 #
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.
567 #
568 @staticmethod
569 def GetErrorMessage():
570 return BuildTask._ErrorMessage
571
572 ## Factory method to create a BuildTask object
573 #
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.
578 #
579 # @param BuildItem A BuildUnit object representing a build object
580 # @param Dependency The dependent build object of BuildItem
581 #
582 @staticmethod
583 def New(BuildItem, Dependency=None):
584 if BuildItem in BuildTask._TaskQueue:
585 Bt = BuildTask._TaskQueue[BuildItem]
586 return Bt
587
588 Bt = BuildTask()
589 Bt._Init(BuildItem, Dependency)
590 BuildTask._TaskQueue[BuildItem] = Bt
591
592 BuildTask._PendingQueueLock.acquire()
593 BuildTask._PendingQueue[BuildItem] = Bt
594 BuildTask._PendingQueueLock.release()
595
596 return Bt
597
598 ## The real constructor of BuildTask
599 #
600 # @param BuildItem A BuildUnit object representing a build object
601 # @param Dependency The dependent build object of BuildItem
602 #
603 def _Init(self, BuildItem, Dependency=None):
604 self.BuildItem = BuildItem
605
606 self.DependencyList = []
607 if Dependency == None:
608 Dependency = BuildItem.Dependency
609 else:
610 Dependency.extend(BuildItem.Dependency)
611 self.AddDependency(Dependency)
612 # flag indicating build completes, used to avoid unnecessary re-build
613 self.CompleteFlag = False
614
615 ## Check if all dependent build tasks are completed or not
616 #
617 def IsReady(self):
618 ReadyFlag = True
619 for Dep in self.DependencyList:
620 if Dep.CompleteFlag == True:
621 continue
622 ReadyFlag = False
623 break
624
625 return ReadyFlag
626
627 ## Add dependent build task
628 #
629 # @param Dependency The list of dependent build objects
630 #
631 def AddDependency(self, Dependency):
632 for Dep in Dependency:
633 self.DependencyList.append(BuildTask.New(Dep)) # BuildTask list
634
635 ## The thread wrapper of LaunchCommand function
636 #
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
639 #
640 def _CommandThread(self, Command, WorkingDir):
641 try:
642 LaunchCommand(Command, WorkingDir)
643 self.CompleteFlag = True
644 except:
645 #
646 # TRICK: hide the output of threads left runing, so that the user can
647 # catch the error message easily
648 #
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
654 )
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()
664
665 ## Start build task thread
666 #
667 def Start(self):
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()
674
675 ## The class contains the information related to EFI image
676 #
677 class PeImageInfo():
678 ## Constructor
679 #
680 # Constructor will load all required image information.
681 #
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
688 #
689 def __init__(self, BaseName, Guid, Arch, OutputDir, DebugDir, ImageClass):
690 self.BaseName = BaseName
691 self.Guid = Guid
692 self.Arch = Arch
693 self.OutputDir = OutputDir
694 self.DebugDir = DebugDir
695 self.Image = ImageClass
696 self.Image.Size = (self.Image.Size / 0x1000 + 1) * 0x1000
697
698 ## The class implementing the EDK2 build process
699 #
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
707 #
708 class Build():
709 ## Constructor
710 #
711 # Constructor will load all necessary configurations, parse platform, modules
712 # and packages and the establish a database for AutoGen.
713 #
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
717 #
718 def __init__(self, Target, WorkspaceDir, BuildOptions):
719 self.WorkspaceDir = WorkspaceDir
720 self.Target = Target
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 if BuildOptions.DisableCache:
740 self.Db = WorkspaceDatabase(":memory:")
741 else:
742 self.Db = WorkspaceDatabase(None, self.Reparse)
743 self.BuildDatabase = self.Db.BuildObject
744 self.Platform = None
745 self.LoadFixAddress = 0
746 self.UniFlag = BuildOptions.Flag
747
748 # print dot character during doing some time-consuming work
749 self.Progress = Utils.Progressor()
750
751 self.InitBuild()
752
753 # print current build environment and configuration
754 EdkLogger.quiet("%-16s = %s" % ("WORKSPACE", os.environ["WORKSPACE"]))
755 EdkLogger.quiet("%-16s = %s" % ("ECP_SOURCE", os.environ["ECP_SOURCE"]))
756 EdkLogger.quiet("%-16s = %s" % ("EDK_SOURCE", os.environ["EDK_SOURCE"]))
757 EdkLogger.quiet("%-16s = %s" % ("EFI_SOURCE", os.environ["EFI_SOURCE"]))
758 EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_PATH", os.environ["EDK_TOOLS_PATH"]))
759
760 EdkLogger.info("")
761
762 os.chdir(self.WorkspaceDir)
763
764 ## Load configuration
765 #
766 # This method will parse target.txt and get the build configurations.
767 #
768 def LoadConfiguration(self):
769 #
770 # Check target.txt and tools_def.txt and Init them
771 #
772 BuildConfigurationFile = os.path.normpath(os.path.join(self.WorkspaceDir, gBuildConfiguration))
773 if os.path.isfile(BuildConfigurationFile) == True:
774 StatusCode = self.TargetTxt.LoadTargetTxtFile(BuildConfigurationFile)
775
776 ToolDefinitionFile = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF]
777 if ToolDefinitionFile == '':
778 ToolDefinitionFile = gToolsDefinition
779 ToolDefinitionFile = os.path.normpath(os.path.join(self.WorkspaceDir, ToolDefinitionFile))
780 if os.path.isfile(ToolDefinitionFile) == True:
781 StatusCode = self.ToolDef.LoadToolDefFile(ToolDefinitionFile)
782 else:
783 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=ToolDefinitionFile)
784 else:
785 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile)
786
787 # if no ARCH given in command line, get it from target.txt
788 if not self.ArchList:
789 self.ArchList = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TARGET_ARCH]
790 self.ArchList = tuple(self.ArchList)
791
792 # if no build target given in command line, get it from target.txt
793 if not self.BuildTargetList:
794 self.BuildTargetList = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TARGET]
795
796 # if no tool chain given in command line, get it from target.txt
797 if not self.ToolChainList:
798 self.ToolChainList = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_TAG]
799 if self.ToolChainList == None or len(self.ToolChainList) == 0:
800 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE, ExtraData="No toolchain given. Don't know how to build.\n")
801
802 # check if the tool chains are defined or not
803 NewToolChainList = []
804 for ToolChain in self.ToolChainList:
805 if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG]:
806 EdkLogger.warn("build", "Tool chain [%s] is not defined" % ToolChain)
807 else:
808 NewToolChainList.append(ToolChain)
809 # if no tool chain available, break the build
810 if len(NewToolChainList) == 0:
811 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,
812 ExtraData="[%s] not defined. No toolchain available for build!\n" % ", ".join(self.ToolChainList))
813 else:
814 self.ToolChainList = NewToolChainList
815
816 if self.ThreadNumber == None:
817 self.ThreadNumber = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER]
818 if self.ThreadNumber == '':
819 self.ThreadNumber = 0
820 else:
821 self.ThreadNumber = int(self.ThreadNumber, 0)
822
823 if self.ThreadNumber == 0:
824 self.ThreadNumber = 1
825
826 if not self.PlatformFile:
827 PlatformFile = self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_ACTIVE_PLATFORM]
828 if not PlatformFile:
829 # Try to find one in current directory
830 WorkingDirectory = os.getcwd()
831 FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.dsc')))
832 FileNum = len(FileList)
833 if FileNum >= 2:
834 EdkLogger.error("build", OPTION_MISSING,
835 ExtraData="There are %d DSC files in %s. Use '-p' to specify one.\n" % (FileNum, WorkingDirectory))
836 elif FileNum == 1:
837 PlatformFile = FileList[0]
838 else:
839 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,
840 ExtraData="No active platform specified in target.txt or command line! Nothing can be built.\n")
841
842 self.PlatformFile = PathClass(NormFile(PlatformFile, self.WorkspaceDir), self.WorkspaceDir)
843
844 ## Initialize build configuration
845 #
846 # This method will parse DSC file and merge the configurations from
847 # command line and target.txt, then get the final build configurations.
848 #
849 def InitBuild(self):
850 # parse target.txt, tools_def.txt, and platform file
851 self.LoadConfiguration()
852
853 # Allow case-insensitive for those from command line or configuration file
854 ErrorCode, ErrorInfo = self.PlatformFile.Validate(".dsc", False)
855 if ErrorCode != 0:
856 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)
857
858 # create metafile database
859 self.Db.InitDatabase()
860
861 ## Build a module or platform
862 #
863 # Create autogen code and makefile for a module or platform, and the launch
864 # "make" command to build it
865 #
866 # @param Target The target of build command
867 # @param Platform The platform file
868 # @param Module The module file
869 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"
870 # @param ToolChain The name of toolchain to build
871 # @param Arch The arch of the module/platform
872 # @param CreateDepModuleCodeFile Flag used to indicate creating code
873 # for dependent modules/Libraries
874 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile
875 # for dependent modules/Libraries
876 #
877 def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False):
878 if AutoGenObject == None:
879 return False
880
881 # skip file generation for cleanxxx targets, run and fds target
882 if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
883 # for target which must generate AutoGen code and makefile
884 if not self.SkipAutoGen or Target == 'genc':
885 self.Progress.Start("Generating code")
886 AutoGenObject.CreateCodeFile(CreateDepsCodeFile)
887 self.Progress.Stop("done!")
888 if Target == "genc":
889 return True
890
891 if not self.SkipAutoGen or Target == 'genmake':
892 self.Progress.Start("Generating makefile")
893 AutoGenObject.CreateMakeFile(CreateDepsMakeFile)
894 self.Progress.Stop("done!")
895 if Target == "genmake":
896 return True
897 else:
898 # always recreate top/platform makefile when clean, just in case of inconsistency
899 AutoGenObject.CreateCodeFile(False)
900 AutoGenObject.CreateMakeFile(False)
901
902 if EdkLogger.GetLevel() == EdkLogger.QUIET:
903 EdkLogger.quiet("Building ... %s" % repr(AutoGenObject))
904
905 BuildCommand = AutoGenObject.BuildCommand
906 if BuildCommand == None or len(BuildCommand) == 0:
907 EdkLogger.error("build", OPTION_MISSING,
908 "No build command found for this module. "
909 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
910 (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch),
911 ExtraData=str(AutoGenObject))
912
913 makefile = GenMake.BuildFile(AutoGenObject)._FILE_NAME_[GenMake.gMakeType]
914
915 # genfds
916 if Target == 'fds':
917 LaunchCommand(AutoGenObject.GenFdsCommand, AutoGenObject.MakeFileDir)
918 return True
919
920 # run
921 if Target == 'run':
922 RunDir = os.path.normpath(os.path.join(AutoGenObject.BuildDir, 'IA32'))
923 Command = '.\SecMain'
924 os.chdir(RunDir)
925 LaunchCommand(Command, RunDir)
926 return True
927
928 # build modules
929 if BuildModule:
930 BuildCommand = BuildCommand + [Target]
931 LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir)
932 return True
933
934 # build library
935 if Target == 'libraries':
936 for Lib in AutoGenObject.LibraryBuildDirectoryList:
937 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, makefile)), 'pbuild']
938 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
939 return True
940
941 # build module
942 if Target == 'modules':
943 for Lib in AutoGenObject.LibraryBuildDirectoryList:
944 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, makefile)), 'pbuild']
945 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
946 for Mod in AutoGenObject.ModuleBuildDirectoryList:
947 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Mod, makefile)), 'pbuild']
948 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
949 return True
950
951 # cleanlib
952 if Target == 'cleanlib':
953 for Lib in AutoGenObject.LibraryBuildDirectoryList:
954 LibMakefile = os.path.normpath(os.path.join(Lib, makefile))
955 if os.path.exists(LibMakefile):
956 NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall']
957 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
958 return True
959
960 # clean
961 if Target == 'clean':
962 for Mod in AutoGenObject.ModuleBuildDirectoryList:
963 ModMakefile = os.path.normpath(os.path.join(Mod, makefile))
964 if os.path.exists(ModMakefile):
965 NewBuildCommand = BuildCommand + ['-f', ModMakefile, 'cleanall']
966 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
967 for Lib in AutoGenObject.LibraryBuildDirectoryList:
968 LibMakefile = os.path.normpath(os.path.join(Lib, makefile))
969 if os.path.exists(LibMakefile):
970 NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall']
971 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)
972 return True
973
974 # cleanall
975 if Target == 'cleanall':
976 try:
977 #os.rmdir(AutoGenObject.BuildDir)
978 RemoveDirectory(AutoGenObject.BuildDir, True)
979 #
980 # First should close DB.
981 #
982 self.Db.Close()
983 RemoveDirectory(os.path.dirname(GlobalData.gDatabasePath), True)
984 except WindowsError, X:
985 EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X))
986 return True
987
988 ## Build a module or platform
989 #
990 # Create autogen code and makefile for a module or platform, and the launch
991 # "make" command to build it
992 #
993 # @param Target The target of build command
994 # @param Platform The platform file
995 # @param Module The module file
996 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"
997 # @param ToolChain The name of toolchain to build
998 # @param Arch The arch of the module/platform
999 # @param CreateDepModuleCodeFile Flag used to indicate creating code
1000 # for dependent modules/Libraries
1001 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile
1002 # for dependent modules/Libraries
1003 #
1004 def _Build(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False):
1005 if AutoGenObject == None:
1006 return False
1007
1008 # skip file generation for cleanxxx targets, run and fds target
1009 if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1010 # for target which must generate AutoGen code and makefile
1011 if not self.SkipAutoGen or Target == 'genc':
1012 self.Progress.Start("Generating code")
1013 AutoGenObject.CreateCodeFile(CreateDepsCodeFile)
1014 self.Progress.Stop("done!")
1015 if Target == "genc":
1016 return True
1017
1018 if not self.SkipAutoGen or Target == 'genmake':
1019 self.Progress.Start("Generating makefile")
1020 AutoGenObject.CreateMakeFile(CreateDepsMakeFile)
1021 #AutoGenObject.CreateAsBuiltInf()
1022 self.Progress.Stop("done!")
1023 if Target == "genmake":
1024 return True
1025 else:
1026 # always recreate top/platform makefile when clean, just in case of inconsistency
1027 AutoGenObject.CreateCodeFile(False)
1028 AutoGenObject.CreateMakeFile(False)
1029
1030 if EdkLogger.GetLevel() == EdkLogger.QUIET:
1031 EdkLogger.quiet("Building ... %s" % repr(AutoGenObject))
1032
1033 BuildCommand = AutoGenObject.BuildCommand
1034 if BuildCommand == None or len(BuildCommand) == 0:
1035 EdkLogger.error("build", OPTION_MISSING,
1036 "No build command found for this module. "
1037 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %
1038 (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch),
1039 ExtraData=str(AutoGenObject))
1040
1041 # genfds
1042 if Target == 'fds':
1043 LaunchCommand(AutoGenObject.GenFdsCommand, AutoGenObject.MakeFileDir)
1044 return True
1045
1046 # run
1047 if Target == 'run':
1048 RunDir = os.path.normpath(os.path.join(AutoGenObject.BuildDir, 'IA32'))
1049 Command = '.\SecMain'
1050 os.chdir(RunDir)
1051 LaunchCommand(Command, RunDir)
1052 return True
1053
1054 # build modules
1055 BuildCommand = BuildCommand + [Target]
1056 if BuildModule:
1057 LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir)
1058 return True
1059
1060 # build library
1061 if Target == 'libraries':
1062 pass
1063
1064 # not build modules
1065
1066
1067 # cleanall
1068 if Target == 'cleanall':
1069 try:
1070 #os.rmdir(AutoGenObject.BuildDir)
1071 RemoveDirectory(AutoGenObject.BuildDir, True)
1072 #
1073 # First should close DB.
1074 #
1075 self.Db.Close()
1076 RemoveDirectory(gBuildCacheDir, True)
1077 except WindowsError, X:
1078 EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X))
1079 return True
1080
1081 ## Rebase module image and Get function address for the input module list.
1082 #
1083 def _RebaseModule (self, MapBuffer, BaseAddress, ModuleList, AddrIsOffset = True, ModeIsSmm = False):
1084 if ModeIsSmm:
1085 AddrIsOffset = False
1086 InfFileNameList = ModuleList.keys()
1087 #InfFileNameList.sort()
1088 for InfFile in InfFileNameList:
1089 sys.stdout.write (".")
1090 sys.stdout.flush()
1091 ModuleInfo = ModuleList[InfFile]
1092 ModuleName = ModuleInfo.BaseName
1093 ModuleOutputImage = ModuleInfo.Image.FileName
1094 ModuleDebugImage = os.path.join(ModuleInfo.DebugDir, ModuleInfo.BaseName + '.efi')
1095 ## for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1096 if not ModeIsSmm:
1097 BaseAddress = BaseAddress - ModuleInfo.Image.Size
1098 #
1099 # Update Image to new BaseAddress by GenFw tool
1100 #
1101 LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir)
1102 LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir)
1103 else:
1104 #
1105 # Set new address to the section header only for SMM driver.
1106 #
1107 LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir)
1108 LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir)
1109 #
1110 # Collect funtion address from Map file
1111 #
1112 ImageMapTable = ModuleOutputImage.replace('.efi', '.map')
1113 FunctionList = []
1114 if os.path.exists(ImageMapTable):
1115 OrigImageBaseAddress = 0
1116 ImageMap = open (ImageMapTable, 'r')
1117 for LinStr in ImageMap:
1118 if len (LinStr.strip()) == 0:
1119 continue
1120 #
1121 # Get the preferred address set on link time.
1122 #
1123 if LinStr.find ('Preferred load address is') != -1:
1124 StrList = LinStr.split()
1125 OrigImageBaseAddress = int (StrList[len(StrList) - 1], 16)
1126
1127 StrList = LinStr.split()
1128 if len (StrList) > 4:
1129 if StrList[3] == 'f' or StrList[3] =='F':
1130 Name = StrList[1]
1131 RelativeAddress = int (StrList[2], 16) - OrigImageBaseAddress
1132 FunctionList.append ((Name, RelativeAddress))
1133 if ModuleInfo.Arch == 'IPF' and Name.endswith('_ModuleEntryPoint'):
1134 #
1135 # Get the real entry point address for IPF image.
1136 #
1137 ModuleInfo.Image.EntryPoint = RelativeAddress
1138 ImageMap.close()
1139 #
1140 # Add general information.
1141 #
1142 if ModeIsSmm:
1143 MapBuffer.write('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint))
1144 elif AddrIsOffset:
1145 MapBuffer.write('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName, 0 - BaseAddress, 0 - (BaseAddress + ModuleInfo.Image.EntryPoint)))
1146 else:
1147 MapBuffer.write('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint))
1148 #
1149 # Add guid and general seciton section.
1150 #
1151 TextSectionAddress = 0
1152 DataSectionAddress = 0
1153 for SectionHeader in ModuleInfo.Image.SectionHeaderList:
1154 if SectionHeader[0] == '.text':
1155 TextSectionAddress = SectionHeader[1]
1156 elif SectionHeader[0] in ['.data', '.sdata']:
1157 DataSectionAddress = SectionHeader[1]
1158 if AddrIsOffset:
1159 MapBuffer.write('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + TextSectionAddress), 0 - (BaseAddress + DataSectionAddress)))
1160 else:
1161 MapBuffer.write('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo.Guid, BaseAddress + TextSectionAddress, BaseAddress + DataSectionAddress))
1162 #
1163 # Add debug image full path.
1164 #
1165 MapBuffer.write('(IMAGE=%s)\n\n' % (ModuleDebugImage))
1166 #
1167 # Add funtion address
1168 #
1169 for Function in FunctionList:
1170 if AddrIsOffset:
1171 MapBuffer.write(' -0x%010X %s\n' % (0 - (BaseAddress + Function[1]), Function[0]))
1172 else:
1173 MapBuffer.write(' 0x%010X %s\n' % (BaseAddress + Function[1], Function[0]))
1174 ImageMap.close()
1175
1176 #
1177 # for SMM module in SMRAM, the SMRAM will be allocated from base to top.
1178 #
1179 if ModeIsSmm:
1180 BaseAddress = BaseAddress + ModuleInfo.Image.Size
1181
1182 ## Collect MAP information of all FVs
1183 #
1184 def _CollectFvMapBuffer (self, MapBuffer, Wa, ModuleList):
1185 if self.Fdf:
1186 # First get the XIP base address for FV map file.
1187 GuidPattern = re.compile("[-a-fA-F0-9]+")
1188 GuidName = re.compile("\(GUID=[-a-fA-F0-9]+")
1189 for FvName in Wa.FdfProfile.FvDict.keys():
1190 FvMapBuffer = os.path.join(Wa.FvDir, FvName + '.Fv.map')
1191 if not os.path.exists(FvMapBuffer):
1192 continue
1193 FvMap = open(FvMapBuffer, 'r')
1194 #skip FV size information
1195 FvMap.readline()
1196 FvMap.readline()
1197 FvMap.readline()
1198 FvMap.readline()
1199 for Line in FvMap:
1200 MatchGuid = GuidPattern.match(Line)
1201 if MatchGuid != None:
1202 #
1203 # Replace GUID with module name
1204 #
1205 GuidString = MatchGuid.group()
1206 if GuidString.upper() in ModuleList:
1207 Line = Line.replace(GuidString, ModuleList[GuidString.upper()].Name)
1208 MapBuffer.write('%s' % (Line))
1209 #
1210 # Add the debug image full path.
1211 #
1212 MatchGuid = GuidName.match(Line)
1213 if MatchGuid != None:
1214 GuidString = MatchGuid.group().split("=")[1]
1215 if GuidString.upper() in ModuleList:
1216 MapBuffer.write('(IMAGE=%s)\n' % (os.path.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].Name + '.efi')))
1217
1218 FvMap.close()
1219
1220 ## Collect MAP information of all modules
1221 #
1222 def _CollectModuleMapBuffer (self, MapBuffer, ModuleList):
1223 sys.stdout.write ("Generate Load Module At Fix Address Map")
1224 sys.stdout.flush()
1225 PatchEfiImageList = []
1226 PeiModuleList = {}
1227 BtModuleList = {}
1228 RtModuleList = {}
1229 SmmModuleList = {}
1230 PeiSize = 0
1231 BtSize = 0
1232 RtSize = 0
1233 # reserve 4K size in SMRAM to make SMM module address not from 0.
1234 SmmSize = 0x1000
1235 IsIpfPlatform = False
1236 if 'IPF' in self.ArchList:
1237 IsIpfPlatform = True
1238 for ModuleGuid in ModuleList:
1239 Module = ModuleList[ModuleGuid]
1240 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (Module.MetaFile, Module.Arch, Module.ToolChain, Module.BuildTarget)
1241
1242 OutputImageFile = ''
1243 for ResultFile in Module.CodaTargetList:
1244 if str(ResultFile.Target).endswith('.efi'):
1245 #
1246 # module list for PEI, DXE, RUNTIME and SMM
1247 #
1248 OutputImageFile = os.path.join(Module.OutputDir, Module.Name + '.efi')
1249 ImageClass = PeImageClass (OutputImageFile)
1250 if not ImageClass.IsValid:
1251 EdkLogger.error("build", FILE_PARSE_FAILURE, ExtraData=ImageClass.ErrorInfo)
1252 ImageInfo = PeImageInfo(Module.Name, Module.Guid, Module.Arch, Module.OutputDir, Module.DebugDir, ImageClass)
1253 if Module.ModuleType in ['PEI_CORE', 'PEIM', 'COMBINED_PEIM_DRIVER','PIC_PEIM', 'RELOCATABLE_PEIM', 'DXE_CORE']:
1254 PeiModuleList[Module.MetaFile] = ImageInfo
1255 PeiSize += ImageInfo.Image.Size
1256 elif Module.ModuleType in ['BS_DRIVER', 'DXE_DRIVER', 'UEFI_DRIVER']:
1257 BtModuleList[Module.MetaFile] = ImageInfo
1258 BtSize += ImageInfo.Image.Size
1259 elif Module.ModuleType in ['DXE_RUNTIME_DRIVER', 'RT_DRIVER', 'DXE_SAL_DRIVER', 'SAL_RT_DRIVER']:
1260 RtModuleList[Module.MetaFile] = ImageInfo
1261 #IPF runtime driver needs to be at 2 page alignment.
1262 if IsIpfPlatform and ImageInfo.Image.Size % 0x2000 != 0:
1263 ImageInfo.Image.Size = (ImageInfo.Image.Size / 0x2000 + 1) * 0x2000
1264 RtSize += ImageInfo.Image.Size
1265 elif Module.ModuleType in ['SMM_CORE', 'DXE_SMM_DRIVER']:
1266 SmmModuleList[Module.MetaFile] = ImageInfo
1267 SmmSize += ImageInfo.Image.Size
1268 if Module.ModuleType == 'DXE_SMM_DRIVER':
1269 PiSpecVersion = '0x00000000'
1270 if 'PI_SPECIFICATION_VERSION' in Module.Module.Specification:
1271 PiSpecVersion = Module.Module.Specification['PI_SPECIFICATION_VERSION']
1272 # for PI specification < PI1.1, DXE_SMM_DRIVER also runs as BOOT time driver.
1273 if int(PiSpecVersion, 16) < 0x0001000A:
1274 BtModuleList[Module.MetaFile] = ImageInfo
1275 BtSize += ImageInfo.Image.Size
1276 break
1277 #
1278 # EFI image is final target.
1279 # Check EFI image contains patchable FixAddress related PCDs.
1280 #
1281 if OutputImageFile != '':
1282 ModuleIsPatch = False
1283 for Pcd in Module.ModulePcdList:
1284 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_LIST:
1285 ModuleIsPatch = True
1286 break
1287 if not ModuleIsPatch:
1288 for Pcd in Module.LibraryPcdList:
1289 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_LIST:
1290 ModuleIsPatch = True
1291 break
1292
1293 if not ModuleIsPatch:
1294 continue
1295 #
1296 # Module includes the patchable load fix address PCDs.
1297 # It will be fixed up later.
1298 #
1299 PatchEfiImageList.append (OutputImageFile)
1300
1301 #
1302 # Get Top Memory address
1303 #
1304 ReservedRuntimeMemorySize = 0
1305 TopMemoryAddress = 0
1306 if self.LoadFixAddress == 0xFFFFFFFFFFFFFFFF:
1307 TopMemoryAddress = 0
1308 else:
1309 TopMemoryAddress = self.LoadFixAddress
1310 if TopMemoryAddress < RtSize + BtSize + PeiSize:
1311 EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS is too low to load driver")
1312 # Make IPF runtime driver at 2 page alignment.
1313 if IsIpfPlatform:
1314 ReservedRuntimeMemorySize = TopMemoryAddress % 0x2000
1315 RtSize = RtSize + ReservedRuntimeMemorySize
1316
1317 #
1318 # Patch FixAddress related PCDs into EFI image
1319 #
1320 for EfiImage in PatchEfiImageList:
1321 EfiImageMap = EfiImage.replace('.efi', '.map')
1322 if not os.path.exists(EfiImageMap):
1323 continue
1324 #
1325 # Get PCD offset in EFI image by GenPatchPcdTable function
1326 #
1327 PcdTable = parsePcdInfoFromMapFile(EfiImageMap, EfiImage)
1328 #
1329 # Patch real PCD value by PatchPcdValue tool
1330 #
1331 for PcdInfo in PcdTable:
1332 ReturnValue = 0
1333 if PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE:
1334 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE, str (PeiSize/0x1000))
1335 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE:
1336 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE_DATA_TYPE, str (BtSize/0x1000))
1337 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE:
1338 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE_DATA_TYPE, str (RtSize/0x1000))
1339 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE and len (SmmModuleList) > 0:
1340 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE_DATA_TYPE, str (SmmSize/0x1000))
1341 if ReturnValue != 0:
1342 EdkLogger.error("build", PARAMETER_INVALID, "Patch PCD value failed", ExtraData=ErrorInfo)
1343
1344 MapBuffer.write('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize/0x1000))
1345 MapBuffer.write('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize/0x1000))
1346 MapBuffer.write('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize/0x1000))
1347 if len (SmmModuleList) > 0:
1348 MapBuffer.write('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize/0x1000))
1349
1350 PeiBaseAddr = TopMemoryAddress - RtSize - BtSize
1351 BtBaseAddr = TopMemoryAddress - RtSize
1352 RtBaseAddr = TopMemoryAddress - ReservedRuntimeMemorySize
1353
1354 self._RebaseModule (MapBuffer, PeiBaseAddr, PeiModuleList, TopMemoryAddress == 0)
1355 self._RebaseModule (MapBuffer, BtBaseAddr, BtModuleList, TopMemoryAddress == 0)
1356 self._RebaseModule (MapBuffer, RtBaseAddr, RtModuleList, TopMemoryAddress == 0)
1357 self._RebaseModule (MapBuffer, 0x1000, SmmModuleList, AddrIsOffset = False, ModeIsSmm = True)
1358 MapBuffer.write('\n\n')
1359 sys.stdout.write ("\n")
1360 sys.stdout.flush()
1361
1362 ## Save platform Map file
1363 #
1364 def _SaveMapFile (self, MapBuffer, Wa):
1365 #
1366 # Map file path is got.
1367 #
1368 MapFilePath = os.path.join(Wa.BuildDir, Wa.Name + '.map')
1369 #
1370 # Save address map into MAP file.
1371 #
1372 SaveFileOnChange(MapFilePath, MapBuffer.getvalue(), False)
1373 MapBuffer.close()
1374 if self.LoadFixAddress != 0:
1375 sys.stdout.write ("\nLoad Module At Fix Address Map file can be found at %s\n" %(MapFilePath))
1376 sys.stdout.flush()
1377
1378 ## Build active platform for different build targets and different tool chains
1379 #
1380 def _BuildPlatform(self):
1381 for BuildTarget in self.BuildTargetList:
1382 GlobalData.gGlobalDefines['TARGET'] = BuildTarget
1383 for ToolChain in self.ToolChainList:
1384 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain
1385 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain
1386 Wa = WorkspaceAutoGen(
1387 self.WorkspaceDir,
1388 self.PlatformFile,
1389 BuildTarget,
1390 ToolChain,
1391 self.ArchList,
1392 self.BuildDatabase,
1393 self.TargetTxt,
1394 self.ToolDef,
1395 self.Fdf,
1396 self.FdList,
1397 self.FvList,
1398 self.CapList,
1399 self.SkuId,
1400 self.UniFlag,
1401 self.Progress
1402 )
1403 self.Fdf = Wa.FdfFile
1404 self.LoadFixAddress = Wa.Platform.LoadFixAddress
1405 self.BuildReport.AddPlatformReport(Wa)
1406 self.Progress.Stop("done!")
1407 for Arch in Wa.ArchList:
1408 GlobalData.gGlobalDefines['ARCH'] = Arch
1409 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)
1410 self._BuildPa(self.Target, Pa)
1411
1412 # Create MAP file when Load Fix Address is enabled.
1413 if self.Target in ["", "all", "fds"]:
1414 for Arch in Wa.ArchList:
1415 GlobalData.gGlobalDefines['ARCH'] = Arch
1416 #
1417 # Check whether the set fix address is above 4G for 32bit image.
1418 #
1419 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:
1420 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")
1421 #
1422 # Get Module List
1423 #
1424 ModuleList = {}
1425 for Pa in Wa.AutoGenObjectList:
1426 for Ma in Pa.ModuleAutoGenList:
1427 if Ma == None:
1428 continue
1429 if not Ma.IsLibrary:
1430 ModuleList[Ma.Guid.upper()] = Ma
1431
1432 MapBuffer = StringIO('')
1433 if self.LoadFixAddress != 0:
1434 #
1435 # Rebase module to the preferred memory address before GenFds
1436 #
1437 self._CollectModuleMapBuffer(MapBuffer, ModuleList)
1438 if self.Fdf:
1439 #
1440 # create FDS again for the updated EFI image
1441 #
1442 self._Build("fds", Wa)
1443 if self.Fdf:
1444 #
1445 # Create MAP file for all platform FVs after GenFds.
1446 #
1447 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)
1448 #
1449 # Save MAP buffer into MAP file.
1450 #
1451 self._SaveMapFile (MapBuffer, Wa)
1452
1453 ## Build active module for different build targets, different tool chains and different archs
1454 #
1455 def _BuildModule(self):
1456 for BuildTarget in self.BuildTargetList:
1457 GlobalData.gGlobalDefines['TARGET'] = BuildTarget
1458 for ToolChain in self.ToolChainList:
1459 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain
1460 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain
1461 #
1462 # module build needs platform build information, so get platform
1463 # AutoGen first
1464 #
1465 Wa = WorkspaceAutoGen(
1466 self.WorkspaceDir,
1467 self.PlatformFile,
1468 BuildTarget,
1469 ToolChain,
1470 self.ArchList,
1471 self.BuildDatabase,
1472 self.TargetTxt,
1473 self.ToolDef,
1474 self.Fdf,
1475 self.FdList,
1476 self.FvList,
1477 self.CapList,
1478 self.SkuId,
1479 self.UniFlag,
1480 self.Progress,
1481 self.ModuleFile
1482 )
1483 self.Fdf = Wa.FdfFile
1484 self.LoadFixAddress = Wa.Platform.LoadFixAddress
1485 Wa.CreateMakeFile(False)
1486 self.Progress.Stop("done!")
1487 MaList = []
1488 for Arch in Wa.ArchList:
1489 GlobalData.gGlobalDefines['ARCH'] = Arch
1490 Ma = ModuleAutoGen(Wa, self.ModuleFile, BuildTarget, ToolChain, Arch, self.PlatformFile)
1491 if Ma == None: continue
1492 MaList.append(Ma)
1493 if not Ma.IsBinaryModule:
1494 self._Build(self.Target, Ma, BuildModule=True)
1495
1496 self.BuildReport.AddPlatformReport(Wa, MaList)
1497 if MaList == []:
1498 EdkLogger.error(
1499 'build',
1500 BUILD_ERROR,
1501 "Module for [%s] is not a component of active platform."\
1502 " Please make sure that the ARCH and inf file path are"\
1503 " given in the same as in [%s]" %\
1504 (', '.join(Wa.ArchList), self.PlatformFile),
1505 ExtraData=self.ModuleFile
1506 )
1507 # Create MAP file when Load Fix Address is enabled.
1508 if self.Target == "fds" and self.Fdf:
1509 for Arch in Wa.ArchList:
1510 #
1511 # Check whether the set fix address is above 4G for 32bit image.
1512 #
1513 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:
1514 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")
1515 #
1516 # Get Module List
1517 #
1518 ModuleList = {}
1519 for Pa in Wa.AutoGenObjectList:
1520 for Ma in Pa.ModuleAutoGenList:
1521 if Ma == None:
1522 continue
1523 if not Ma.IsLibrary:
1524 ModuleList[Ma.Guid.upper()] = Ma
1525
1526 MapBuffer = StringIO('')
1527 if self.LoadFixAddress != 0:
1528 #
1529 # Rebase module to the preferred memory address before GenFds
1530 #
1531 self._CollectModuleMapBuffer(MapBuffer, ModuleList)
1532 #
1533 # create FDS again for the updated EFI image
1534 #
1535 self._Build("fds", Wa)
1536 #
1537 # Create MAP file for all platform FVs after GenFds.
1538 #
1539 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)
1540 #
1541 # Save MAP buffer into MAP file.
1542 #
1543 self._SaveMapFile (MapBuffer, Wa)
1544
1545 ## Build a platform in multi-thread mode
1546 #
1547 def _MultiThreadBuildPlatform(self):
1548 for BuildTarget in self.BuildTargetList:
1549 GlobalData.gGlobalDefines['TARGET'] = BuildTarget
1550 for ToolChain in self.ToolChainList:
1551 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain
1552 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain
1553 Wa = WorkspaceAutoGen(
1554 self.WorkspaceDir,
1555 self.PlatformFile,
1556 BuildTarget,
1557 ToolChain,
1558 self.ArchList,
1559 self.BuildDatabase,
1560 self.TargetTxt,
1561 self.ToolDef,
1562 self.Fdf,
1563 self.FdList,
1564 self.FvList,
1565 self.CapList,
1566 self.SkuId,
1567 self.UniFlag,
1568 self.Progress
1569 )
1570 self.Fdf = Wa.FdfFile
1571 self.LoadFixAddress = Wa.Platform.LoadFixAddress
1572 self.BuildReport.AddPlatformReport(Wa)
1573 Wa.CreateMakeFile(False)
1574
1575 # multi-thread exit flag
1576 ExitFlag = threading.Event()
1577 ExitFlag.clear()
1578 for Arch in Wa.ArchList:
1579 GlobalData.gGlobalDefines['ARCH'] = Arch
1580 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)
1581 if Pa == None:
1582 continue
1583 pModules = []
1584 for Module in Pa.Platform.Modules:
1585 # Get ModuleAutoGen object to generate C code file and makefile
1586 Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile)
1587 if Ma == None:
1588 continue
1589 # Not to auto-gen for targets 'clean', 'cleanlib', 'cleanall', 'run', 'fds'
1590 if self.Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:
1591 # for target which must generate AutoGen code and makefile
1592 if not self.SkipAutoGen or self.Target == 'genc':
1593 Ma.CreateCodeFile(True)
1594 if self.Target == "genc":
1595 continue
1596
1597 if not self.SkipAutoGen or self.Target == 'genmake':
1598 Ma.CreateMakeFile(True)
1599 Ma.CreateAsBuiltInf()
1600 if self.Target == "genmake":
1601 continue
1602 pModules.append(Ma)
1603 self.Progress.Stop("done!")
1604
1605 for Ma in pModules:
1606 # Generate build task for the module
1607 Bt = BuildTask.New(ModuleMakeUnit(Ma, self.Target))
1608 # Break build if any build thread has error
1609 if BuildTask.HasError():
1610 # we need a full version of makefile for platform
1611 ExitFlag.set()
1612 BuildTask.WaitForComplete()
1613 Pa.CreateMakeFile(False)
1614 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
1615 # Start task scheduler
1616 if not BuildTask.IsOnGoing():
1617 BuildTask.StartScheduler(self.ThreadNumber, ExitFlag)
1618
1619 # in case there's an interruption. we need a full version of makefile for platform
1620 Pa.CreateMakeFile(False)
1621 if BuildTask.HasError():
1622 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
1623
1624 #
1625 # Save temp tables to a TmpTableDict.
1626 #
1627 for Key in Wa.BuildDatabase._CACHE_:
1628 if Wa.BuildDatabase._CACHE_[Key]._RawData and Wa.BuildDatabase._CACHE_[Key]._RawData._Table and Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table:
1629 if TemporaryTablePattern.match(Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table):
1630 TmpTableDict[Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table] = Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Cur
1631 #
1632 #
1633 # All modules have been put in build tasks queue. Tell task scheduler
1634 # to exit if all tasks are completed
1635 #
1636 ExitFlag.set()
1637 BuildTask.WaitForComplete()
1638
1639 #
1640 # Check for build error, and raise exception if one
1641 # has been signaled.
1642 #
1643 if BuildTask.HasError():
1644 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
1645
1646 # Create MAP file when Load Fix Address is enabled.
1647 if self.Target in ["", "all", "fds"]:
1648 for Arch in Wa.ArchList:
1649 #
1650 # Check whether the set fix address is above 4G for 32bit image.
1651 #
1652 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:
1653 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")
1654 #
1655 # Get Module List
1656 #
1657 ModuleList = {}
1658 for Pa in Wa.AutoGenObjectList:
1659 for Ma in Pa.ModuleAutoGenList:
1660 if Ma == None:
1661 continue
1662 if not Ma.IsLibrary:
1663 ModuleList[Ma.Guid.upper()] = Ma
1664 #
1665 # Rebase module to the preferred memory address before GenFds
1666 #
1667 MapBuffer = StringIO('')
1668 if self.LoadFixAddress != 0:
1669 self._CollectModuleMapBuffer(MapBuffer, ModuleList)
1670
1671 if self.Fdf:
1672 #
1673 # Generate FD image if there's a FDF file found
1674 #
1675 LaunchCommand(Wa.GenFdsCommand, os.getcwd())
1676
1677 #
1678 # Create MAP file for all platform FVs after GenFds.
1679 #
1680 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)
1681 #
1682 # Save MAP buffer into MAP file.
1683 #
1684 self._SaveMapFile(MapBuffer, Wa)
1685
1686 ## Generate GuidedSectionTools.txt in the FV directories.
1687 #
1688 def CreateGuidedSectionToolsFile(self):
1689 for BuildTarget in self.BuildTargetList:
1690 for ToolChain in self.ToolChainList:
1691 Wa = WorkspaceAutoGen(
1692 self.WorkspaceDir,
1693 self.PlatformFile,
1694 BuildTarget,
1695 ToolChain,
1696 self.ArchList,
1697 self.BuildDatabase,
1698 self.TargetTxt,
1699 self.ToolDef,
1700 self.Fdf,
1701 self.FdList,
1702 self.FvList,
1703 self.CapList,
1704 self.SkuId,
1705 self.UniFlag
1706 )
1707 FvDir = Wa.FvDir
1708 if not os.path.exists(FvDir):
1709 continue
1710
1711 for Arch in self.ArchList:
1712 # Build up the list of supported architectures for this build
1713 prefix = '%s_%s_%s_' % (BuildTarget, ToolChain, Arch)
1714
1715 # Look through the tool definitions for GUIDed tools
1716 guidAttribs = []
1717 for (attrib, value) in self.ToolDef.ToolsDefTxtDictionary.iteritems():
1718 if attrib.upper().endswith('_GUID'):
1719 split = attrib.split('_')
1720 thisPrefix = '_'.join(split[0:3]) + '_'
1721 if thisPrefix == prefix:
1722 guid = self.ToolDef.ToolsDefTxtDictionary[attrib]
1723 guid = guid.lower()
1724 toolName = split[3]
1725 path = '_'.join(split[0:4]) + '_PATH'
1726 path = self.ToolDef.ToolsDefTxtDictionary[path]
1727 path = self.GetFullPathOfTool(path)
1728 guidAttribs.append((guid, toolName, path))
1729
1730 # Write out GuidedSecTools.txt
1731 toolsFile = os.path.join(FvDir, 'GuidedSectionTools.txt')
1732 toolsFile = open(toolsFile, 'wt')
1733 for guidedSectionTool in guidAttribs:
1734 print >> toolsFile, ' '.join(guidedSectionTool)
1735 toolsFile.close()
1736
1737 ## Returns the full path of the tool.
1738 #
1739 def GetFullPathOfTool (self, tool):
1740 if os.path.exists(tool):
1741 return os.path.realpath(tool)
1742 else:
1743 # We need to search for the tool using the
1744 # PATH environment variable.
1745 for dirInPath in os.environ['PATH'].split(os.pathsep):
1746 foundPath = os.path.join(dirInPath, tool)
1747 if os.path.exists(foundPath):
1748 return os.path.realpath(foundPath)
1749
1750 # If the tool was not found in the path then we just return
1751 # the input tool.
1752 return tool
1753
1754 ## Launch the module or platform build
1755 #
1756 def Launch(self):
1757 if not self.ModuleFile:
1758 if not self.SpawnMode or self.Target not in ["", "all"]:
1759 self.SpawnMode = False
1760 self._BuildPlatform()
1761 else:
1762 self._MultiThreadBuildPlatform()
1763 self.CreateGuidedSectionToolsFile()
1764 else:
1765 self.SpawnMode = False
1766 self._BuildModule()
1767
1768 ## Do some clean-up works when error occurred
1769 def Relinquish(self):
1770 OldLogLevel = EdkLogger.GetLevel()
1771 EdkLogger.SetLevel(EdkLogger.ERROR)
1772 #self.DumpBuildData()
1773 Utils.Progressor.Abort()
1774 if self.SpawnMode == True:
1775 BuildTask.Abort()
1776 EdkLogger.SetLevel(OldLogLevel)
1777
1778 def DumpBuildData(self):
1779 CacheDirectory = os.path.join(self.WorkspaceDir, gBuildCacheDir)
1780 Utils.CreateDirectory(CacheDirectory)
1781 Utils.DataDump(Utils.gFileTimeStampCache, os.path.join(CacheDirectory, "gFileTimeStampCache"))
1782 Utils.DataDump(Utils.gDependencyDatabase, os.path.join(CacheDirectory, "gDependencyDatabase"))
1783
1784 def RestoreBuildData(self):
1785 FilePath = os.path.join(self.WorkspaceDir, gBuildCacheDir, "gFileTimeStampCache")
1786 if Utils.gFileTimeStampCache == {} and os.path.isfile(FilePath):
1787 Utils.gFileTimeStampCache = Utils.DataRestore(FilePath)
1788 if Utils.gFileTimeStampCache == None:
1789 Utils.gFileTimeStampCache = {}
1790
1791 FilePath = os.path.join(self.WorkspaceDir, gBuildCacheDir, "gDependencyDatabase")
1792 if Utils.gDependencyDatabase == {} and os.path.isfile(FilePath):
1793 Utils.gDependencyDatabase = Utils.DataRestore(FilePath)
1794 if Utils.gDependencyDatabase == None:
1795 Utils.gDependencyDatabase = {}
1796
1797 def ParseDefines(DefineList=[]):
1798 DefineDict = {}
1799 if DefineList != None:
1800 for Define in DefineList:
1801 DefineTokenList = Define.split("=", 1)
1802 if not GlobalData.gMacroNamePattern.match(DefineTokenList[0]):
1803 EdkLogger.error('build', FORMAT_INVALID,
1804 "The macro name must be in the pattern [A-Z][A-Z0-9_]*",
1805 ExtraData=DefineTokenList[0])
1806
1807 if len(DefineTokenList) == 1:
1808 DefineDict[DefineTokenList[0]] = "TRUE"
1809 else:
1810 DefineDict[DefineTokenList[0]] = DefineTokenList[1].strip()
1811 return DefineDict
1812
1813 gParamCheck = []
1814 def SingleCheckCallback(option, opt_str, value, parser):
1815 if option not in gParamCheck:
1816 setattr(parser.values, option.dest, value)
1817 gParamCheck.append(option)
1818 else:
1819 parser.error("Option %s only allows one instance in command line!" % option)
1820
1821 ## Parse command line options
1822 #
1823 # Using standard Python module optparse to parse command line option of this tool.
1824 #
1825 # @retval Opt A optparse.Values object containing the parsed options
1826 # @retval Args Target of build command
1827 #
1828 def MyOptionParser():
1829 Parser = OptionParser(description=__copyright__,version=__version__,prog="build.exe",usage="%prog [options] [all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]")
1830 Parser.add_option("-a", "--arch", action="append", type="choice", choices=['IA32','X64','IPF','EBC','ARM', 'AARCH64'], dest="TargetArch",
1831 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.")
1832 Parser.add_option("-p", "--platform", action="callback", type="string", dest="PlatformFile", callback=SingleCheckCallback,
1833 help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.")
1834 Parser.add_option("-m", "--module", action="callback", type="string", dest="ModuleFile", callback=SingleCheckCallback,
1835 help="Build the module specified by the INF file name argument.")
1836 Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Using the TARGET to build the platform, overriding target.txt's TARGET definition.",
1837 action="append")
1838 Parser.add_option("-t", "--tagname", action="append", type="string", dest="ToolChain",
1839 help="Using the Tool Chain Tagname to build the platform, overriding target.txt's TOOL_CHAIN_TAG definition.")
1840 Parser.add_option("-x", "--sku-id", action="callback", type="string", dest="SkuId", callback=SingleCheckCallback,
1841 help="Using this name of SKU ID to build the platform, overriding SKUID_IDENTIFIER in DSC file.")
1842
1843 Parser.add_option("-n", action="callback", type="int", dest="ThreadNumber", callback=SingleCheckCallback,
1844 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.")
1845
1846 Parser.add_option("-f", "--fdf", action="callback", type="string", dest="FdfFile", callback=SingleCheckCallback,
1847 help="The name of the FDF file to use, which overrides the setting in the DSC file.")
1848 Parser.add_option("-r", "--rom-image", action="append", type="string", dest="RomImage", default=[],
1849 help="The name of FD to be generated. The name must be from [FD] section in FDF file.")
1850 Parser.add_option("-i", "--fv-image", action="append", type="string", dest="FvImage", default=[],
1851 help="The name of FV to be generated. The name must be from [FV] section in FDF file.")
1852 Parser.add_option("-C", "--capsule-image", action="append", type="string", dest="CapName", default=[],
1853 help="The name of Capsule to be generated. The name must be from [Capsule] section in FDF file.")
1854 Parser.add_option("-u", "--skip-autogen", action="store_true", dest="SkipAutoGen", help="Skip AutoGen step.")
1855 Parser.add_option("-e", "--re-parse", action="store_true", dest="Reparse", help="Re-parse all meta-data files.")
1856
1857 Parser.add_option("-c", "--case-insensitive", action="store_true", dest="CaseInsensitive", default=False, help="Don't check case of file name.")
1858
1859 Parser.add_option("-w", "--warning-as-error", action="store_true", dest="WarningAsError", help="Treat warning in tools as error.")
1860 Parser.add_option("-j", "--log", action="store", dest="LogFile", help="Put log in specified file as well as on console.")
1861
1862 Parser.add_option("-s", "--silent", action="store_true", type=None, dest="SilentMode",
1863 help="Make use of silent mode of (n)make.")
1864 Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.")
1865 Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed, "\
1866 "including library instances selected, final dependency expression, "\
1867 "and warning messages, etc.")
1868 Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.")
1869 Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".")
1870
1871 Parser.add_option("-y", "--report-file", action="store", dest="ReportFile", help="Create/overwrite the report to the specified filename.")
1872 Parser.add_option("-Y", "--report-type", action="append", type="choice", choices=['PCD','LIBRARY','FLASH','DEPEX','BUILD_FLAGS','FIXED_ADDRESS', 'EXECUTION_ORDER'], dest="ReportType", default=[],
1873 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]. "\
1874 "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]")
1875 Parser.add_option("-F", "--flag", action="store", type="string", dest="Flag",
1876 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. "\
1877 "This option can also be specified by setting *_*_*_BUILD_FLAGS in [BuildOptions] section of platform DSC. If they are both specified, this value "\
1878 "will override the setting in [BuildOptions] section of platform DSC.")
1879 Parser.add_option("-N", "--no-cache", action="store_true", dest="DisableCache", default=False, help="Disable build cache mechanism")
1880
1881 (Opt, Args)=Parser.parse_args()
1882 return (Opt, Args)
1883
1884 ## Tool entrance method
1885 #
1886 # This method mainly dispatch specific methods per the command line options.
1887 # If no error found, return zero value so the caller of this tool can know
1888 # if it's executed successfully or not.
1889 #
1890 # @retval 0 Tool was successful
1891 # @retval 1 Tool failed
1892 #
1893 def Main():
1894 StartTime = time.time()
1895
1896 # Initialize log system
1897 EdkLogger.Initialize()
1898
1899 #
1900 # Parse the options and args
1901 #
1902 (Option, Target) = MyOptionParser()
1903 GlobalData.gOptions = Option
1904 GlobalData.gCaseInsensitive = Option.CaseInsensitive
1905
1906 # Set log level
1907 if Option.verbose != None:
1908 EdkLogger.SetLevel(EdkLogger.VERBOSE)
1909 elif Option.quiet != None:
1910 EdkLogger.SetLevel(EdkLogger.QUIET)
1911 elif Option.debug != None:
1912 EdkLogger.SetLevel(Option.debug + 1)
1913 else:
1914 EdkLogger.SetLevel(EdkLogger.INFO)
1915
1916 if Option.LogFile != None:
1917 EdkLogger.SetLogFile(Option.LogFile)
1918
1919 if Option.WarningAsError == True:
1920 EdkLogger.SetWarningAsError()
1921
1922 if platform.platform().find("Windows") >= 0:
1923 GlobalData.gIsWindows = True
1924 else:
1925 GlobalData.gIsWindows = False
1926
1927 EdkLogger.quiet("Build environment: %s" % platform.platform())
1928 EdkLogger.quiet(time.strftime("Build start time: %H:%M:%S, %b.%d %Y\n", time.localtime()));
1929 ReturnCode = 0
1930 MyBuild = None
1931 try:
1932 if len(Target) == 0:
1933 Target = "all"
1934 elif len(Target) >= 2:
1935 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "More than one targets are not supported.",
1936 ExtraData="Please select one of: %s" %(' '.join(gSupportedTarget)))
1937 else:
1938 Target = Target[0].lower()
1939
1940 if Target not in gSupportedTarget:
1941 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "Not supported target [%s]." % Target,
1942 ExtraData="Please select one of: %s" %(' '.join(gSupportedTarget)))
1943
1944 #
1945 # Check environment variable: EDK_TOOLS_PATH, WORKSPACE, PATH
1946 #
1947 CheckEnvVariable()
1948 GlobalData.gCommandLineDefines.update(ParseDefines(Option.Macros))
1949
1950 Workspace = os.getenv("WORKSPACE")
1951 #
1952 # Get files real name in workspace dir
1953 #
1954 GlobalData.gAllFiles = Utils.DirCache(Workspace)
1955
1956 WorkingDirectory = os.getcwd()
1957 if not Option.ModuleFile:
1958 FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.inf')))
1959 FileNum = len(FileList)
1960 if FileNum >= 2:
1961 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "There are %d INF files in %s." % (FileNum, WorkingDirectory),
1962 ExtraData="Please use '-m <INF_FILE_PATH>' switch to choose one.")
1963 elif FileNum == 1:
1964 Option.ModuleFile = NormFile(FileList[0], Workspace)
1965
1966 if Option.ModuleFile:
1967 if os.path.isabs (Option.ModuleFile):
1968 if os.path.normcase (os.path.normpath(Option.ModuleFile)).find (Workspace) == 0:
1969 Option.ModuleFile = NormFile(os.path.normpath(Option.ModuleFile), Workspace)
1970 Option.ModuleFile = PathClass(Option.ModuleFile, Workspace)
1971 ErrorCode, ErrorInfo = Option.ModuleFile.Validate(".inf", False)
1972 if ErrorCode != 0:
1973 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)
1974
1975 if Option.PlatformFile != None:
1976 if os.path.isabs (Option.PlatformFile):
1977 if os.path.normcase (os.path.normpath(Option.PlatformFile)).find (Workspace) == 0:
1978 Option.PlatformFile = NormFile(os.path.normpath(Option.PlatformFile), Workspace)
1979 Option.PlatformFile = PathClass(Option.PlatformFile, Workspace)
1980
1981 if Option.FdfFile != None:
1982 if os.path.isabs (Option.FdfFile):
1983 if os.path.normcase (os.path.normpath(Option.FdfFile)).find (Workspace) == 0:
1984 Option.FdfFile = NormFile(os.path.normpath(Option.FdfFile), Workspace)
1985 Option.FdfFile = PathClass(Option.FdfFile, Workspace)
1986 ErrorCode, ErrorInfo = Option.FdfFile.Validate(".fdf", False)
1987 if ErrorCode != 0:
1988 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)
1989
1990 if Option.Flag != None and Option.Flag not in ['-c', '-s']:
1991 EdkLogger.error("build", OPTION_VALUE_INVALID, "UNI flag must be one of -c or -s")
1992
1993 MyBuild = Build(Target, Workspace, Option)
1994 GlobalData.gCommandLineDefines['ARCH'] = ' '.join(MyBuild.ArchList)
1995 MyBuild.Launch()
1996 # Drop temp tables to avoid database locked.
1997 for TmpTableName in TmpTableDict:
1998 SqlCommand = """drop table IF EXISTS %s""" % TmpTableName
1999 TmpTableDict[TmpTableName].execute(SqlCommand)
2000 #MyBuild.DumpBuildData()
2001 except FatalError, X:
2002 if MyBuild != None:
2003 # for multi-thread build exits safely
2004 MyBuild.Relinquish()
2005 if Option != None and Option.debug != None:
2006 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2007 ReturnCode = X.args[0]
2008 except Warning, X:
2009 # error from Fdf parser
2010 if MyBuild != None:
2011 # for multi-thread build exits safely
2012 MyBuild.Relinquish()
2013 if Option != None and Option.debug != None:
2014 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2015 else:
2016 EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError = False)
2017 ReturnCode = FORMAT_INVALID
2018 except KeyboardInterrupt:
2019 ReturnCode = ABORT_ERROR
2020 if Option != None and Option.debug != None:
2021 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2022 except:
2023 if MyBuild != None:
2024 # for multi-thread build exits safely
2025 MyBuild.Relinquish()
2026
2027 # try to get the meta-file from the object causing exception
2028 Tb = sys.exc_info()[-1]
2029 MetaFile = GlobalData.gProcessingFile
2030 while Tb != None:
2031 if 'self' in Tb.tb_frame.f_locals and hasattr(Tb.tb_frame.f_locals['self'], 'MetaFile'):
2032 MetaFile = Tb.tb_frame.f_locals['self'].MetaFile
2033 Tb = Tb.tb_next
2034 EdkLogger.error(
2035 "\nbuild",
2036 CODE_ERROR,
2037 "Unknown fatal error when processing [%s]" % MetaFile,
2038 ExtraData="\n(Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!)\n",
2039 RaiseError=False
2040 )
2041 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
2042 ReturnCode = CODE_ERROR
2043 finally:
2044 Utils.Progressor.Abort()
2045
2046 if ReturnCode == 0:
2047 Conclusion = "Done"
2048 elif ReturnCode == ABORT_ERROR:
2049 Conclusion = "Aborted"
2050 else:
2051 Conclusion = "Failed"
2052 FinishTime = time.time()
2053 BuildDuration = time.gmtime(int(round(FinishTime - StartTime)))
2054 BuildDurationStr = ""
2055 if BuildDuration.tm_yday > 1:
2056 BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration) + ", %d day(s)"%(BuildDuration.tm_yday - 1)
2057 else:
2058 BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration)
2059 if MyBuild != None:
2060 MyBuild.BuildReport.GenerateReport(BuildDurationStr)
2061 MyBuild.Db.Close()
2062 EdkLogger.SetLevel(EdkLogger.QUIET)
2063 EdkLogger.quiet("\n- %s -" % Conclusion)
2064 EdkLogger.quiet(time.strftime("Build end time: %H:%M:%S, %b.%d %Y", time.localtime()))
2065 EdkLogger.quiet("Build total time: %s\n" % BuildDurationStr)
2066 return ReturnCode
2067
2068 if __name__ == '__main__':
2069 r = Main()
2070 ## 0-127 is a safe return range, and 1 is a standard default error
2071 if r < 0 or r > 127: r = 1
2072 sys.exit(r)
2073