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