]> git.proxmox.com Git - mirror_edk2.git/blame_incremental - BaseTools/Source/Python/build/build.py
BaseTools:GuidedSectionTools.txt is not generated correctly
[mirror_edk2.git] / BaseTools / Source / Python / build / build.py
... / ...
CommitLineData
1## @file\r
2# build a platform or a module\r
3#\r
4# Copyright (c) 2014, Hewlett-Packard Development Company, L.P.<BR>\r
5# Copyright (c) 2007 - 2020, Intel Corporation. All rights reserved.<BR>\r
6# Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR>\r
7# Copyright (c) 2020, ARM Limited. All rights reserved.<BR>\r
8#\r
9# SPDX-License-Identifier: BSD-2-Clause-Patent\r
10#\r
11\r
12##\r
13# Import Modules\r
14#\r
15from __future__ import print_function\r
16from __future__ import absolute_import\r
17import os.path as path\r
18import sys\r
19import os\r
20import re\r
21import glob\r
22import time\r
23import platform\r
24import traceback\r
25import multiprocessing\r
26from threading import Thread,Event,BoundedSemaphore\r
27import threading\r
28from subprocess import Popen,PIPE, STDOUT\r
29from collections import OrderedDict, defaultdict\r
30\r
31from AutoGen.PlatformAutoGen import PlatformAutoGen\r
32from AutoGen.ModuleAutoGen import ModuleAutoGen\r
33from AutoGen.WorkspaceAutoGen import WorkspaceAutoGen\r
34from AutoGen.AutoGenWorker import AutoGenWorkerInProcess,AutoGenManager,\\r
35 LogAgent\r
36from AutoGen import GenMake\r
37from Common import Misc as Utils\r
38\r
39from Common.TargetTxtClassObject import TargetTxtDict\r
40from Common.ToolDefClassObject import ToolDefDict\r
41from buildoptions import MyOptionParser\r
42from Common.Misc import PathClass,SaveFileOnChange,RemoveDirectory\r
43from Common.StringUtils import NormPath\r
44from Common.MultipleWorkspace import MultipleWorkspace as mws\r
45from Common.BuildToolError import *\r
46from Common.DataType import *\r
47import Common.EdkLogger as EdkLogger\r
48\r
49from Workspace.WorkspaceDatabase import BuildDB\r
50\r
51from BuildReport import BuildReport\r
52from GenPatchPcdTable.GenPatchPcdTable import PeImageClass,parsePcdInfoFromMapFile\r
53from PatchPcdValue.PatchPcdValue import PatchBinaryFile\r
54\r
55import Common.GlobalData as GlobalData\r
56from GenFds.GenFds import GenFds, GenFdsApi\r
57import multiprocessing as mp\r
58from multiprocessing import Manager\r
59from AutoGen.DataPipe import MemoryDataPipe\r
60from AutoGen.ModuleAutoGenHelper import WorkSpaceInfo, PlatformInfo\r
61from GenFds.FdfParser import FdfParser\r
62from AutoGen.IncludesAutoGen import IncludesAutoGen\r
63from GenFds.GenFds import resetFdsGlobalVariable\r
64\r
65## standard targets of build command\r
66gSupportedTarget = ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run']\r
67\r
68## build configuration file\r
69gBuildConfiguration = "target.txt"\r
70gToolsDefinition = "tools_def.txt"\r
71\r
72TemporaryTablePattern = re.compile(r'^_\d+_\d+_[a-fA-F0-9]+$')\r
73TmpTableDict = {}\r
74\r
75## Check environment PATH variable to make sure the specified tool is found\r
76#\r
77# If the tool is found in the PATH, then True is returned\r
78# Otherwise, False is returned\r
79#\r
80def IsToolInPath(tool):\r
81 if 'PATHEXT' in os.environ:\r
82 extns = os.environ['PATHEXT'].split(os.path.pathsep)\r
83 else:\r
84 extns = ('',)\r
85 for pathDir in os.environ['PATH'].split(os.path.pathsep):\r
86 for ext in extns:\r
87 if os.path.exists(os.path.join(pathDir, tool + ext)):\r
88 return True\r
89 return False\r
90\r
91## Check environment variables\r
92#\r
93# Check environment variables that must be set for build. Currently they are\r
94#\r
95# WORKSPACE The directory all packages/platforms start from\r
96# EDK_TOOLS_PATH The directory contains all tools needed by the build\r
97# PATH $(EDK_TOOLS_PATH)/Bin/<sys> must be set in PATH\r
98#\r
99# If any of above environment variable is not set or has error, the build\r
100# will be broken.\r
101#\r
102def CheckEnvVariable():\r
103 # check WORKSPACE\r
104 if "WORKSPACE" not in os.environ:\r
105 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",\r
106 ExtraData="WORKSPACE")\r
107\r
108 WorkspaceDir = os.path.normcase(os.path.normpath(os.environ["WORKSPACE"]))\r
109 if not os.path.exists(WorkspaceDir):\r
110 EdkLogger.error("build", FILE_NOT_FOUND, "WORKSPACE doesn't exist", ExtraData=WorkspaceDir)\r
111 elif ' ' in WorkspaceDir:\r
112 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in WORKSPACE path",\r
113 ExtraData=WorkspaceDir)\r
114 os.environ["WORKSPACE"] = WorkspaceDir\r
115\r
116 # set multiple workspace\r
117 PackagesPath = os.getenv("PACKAGES_PATH")\r
118 mws.setWs(WorkspaceDir, PackagesPath)\r
119 if mws.PACKAGES_PATH:\r
120 for Path in mws.PACKAGES_PATH:\r
121 if not os.path.exists(Path):\r
122 EdkLogger.error("build", FILE_NOT_FOUND, "One Path in PACKAGES_PATH doesn't exist", ExtraData=Path)\r
123 elif ' ' in Path:\r
124 EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in PACKAGES_PATH", ExtraData=Path)\r
125\r
126\r
127 os.environ["EDK_TOOLS_PATH"] = os.path.normcase(os.environ["EDK_TOOLS_PATH"])\r
128\r
129 # check EDK_TOOLS_PATH\r
130 if "EDK_TOOLS_PATH" not in os.environ:\r
131 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",\r
132 ExtraData="EDK_TOOLS_PATH")\r
133\r
134 # check PATH\r
135 if "PATH" not in os.environ:\r
136 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found",\r
137 ExtraData="PATH")\r
138\r
139 GlobalData.gWorkspace = WorkspaceDir\r
140\r
141 GlobalData.gGlobalDefines["WORKSPACE"] = WorkspaceDir\r
142 GlobalData.gGlobalDefines["EDK_TOOLS_PATH"] = os.environ["EDK_TOOLS_PATH"]\r
143\r
144## Get normalized file path\r
145#\r
146# Convert the path to be local format, and remove the WORKSPACE path at the\r
147# beginning if the file path is given in full path.\r
148#\r
149# @param FilePath File path to be normalized\r
150# @param Workspace Workspace path which the FilePath will be checked against\r
151#\r
152# @retval string The normalized file path\r
153#\r
154def NormFile(FilePath, Workspace):\r
155 # check if the path is absolute or relative\r
156 if os.path.isabs(FilePath):\r
157 FileFullPath = os.path.normpath(FilePath)\r
158 else:\r
159 FileFullPath = os.path.normpath(mws.join(Workspace, FilePath))\r
160 Workspace = mws.getWs(Workspace, FilePath)\r
161\r
162 # check if the file path exists or not\r
163 if not os.path.isfile(FileFullPath):\r
164 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData="\t%s (Please give file in absolute path or relative to WORKSPACE)" % FileFullPath)\r
165\r
166 # remove workspace directory from the beginning part of the file path\r
167 if Workspace[-1] in ["\\", "/"]:\r
168 return FileFullPath[len(Workspace):]\r
169 else:\r
170 return FileFullPath[(len(Workspace) + 1):]\r
171\r
172## Get the output of an external program\r
173#\r
174# This is the entrance method of thread reading output of an external program and\r
175# putting them in STDOUT/STDERR of current program.\r
176#\r
177# @param From The stream message read from\r
178# @param To The stream message put on\r
179# @param ExitFlag The flag used to indicate stopping reading\r
180#\r
181def ReadMessage(From, To, ExitFlag,MemTo=None):\r
182 while True:\r
183 # read one line a time\r
184 Line = From.readline()\r
185 # empty string means "end"\r
186 if Line is not None and Line != b"":\r
187 LineStr = Line.rstrip().decode(encoding='utf-8', errors='ignore')\r
188 if MemTo is not None:\r
189 if "Note: including file:" == LineStr.lstrip()[:21]:\r
190 MemTo.append(LineStr)\r
191 else:\r
192 To(LineStr)\r
193 MemTo.append(LineStr)\r
194 else:\r
195 To(LineStr)\r
196 else:\r
197 break\r
198 if ExitFlag.isSet():\r
199 break\r
200\r
201class MakeSubProc(Popen):\r
202 def __init__(self,*args, **argv):\r
203 super(MakeSubProc,self).__init__(*args, **argv)\r
204 self.ProcOut = []\r
205\r
206## Launch an external program\r
207#\r
208# This method will call subprocess.Popen to execute an external program with\r
209# given options in specified directory. Because of the dead-lock issue during\r
210# redirecting output of the external program, threads are used to to do the\r
211# redirection work.\r
212#\r
213# @param Command A list or string containing the call of the program\r
214# @param WorkingDir The directory in which the program will be running\r
215#\r
216def LaunchCommand(Command, WorkingDir,ModuleAuto = None):\r
217 BeginTime = time.time()\r
218 # if working directory doesn't exist, Popen() will raise an exception\r
219 if not os.path.isdir(WorkingDir):\r
220 EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=WorkingDir)\r
221\r
222 # Command is used as the first Argument in following Popen().\r
223 # It could be a string or sequence. We find that if command is a string in following Popen(),\r
224 # ubuntu may fail with an error message that the command is not found.\r
225 # So here we may need convert command from string to list instance.\r
226 if platform.system() != 'Windows':\r
227 if not isinstance(Command, list):\r
228 Command = Command.split()\r
229 Command = ' '.join(Command)\r
230\r
231 Proc = None\r
232 EndOfProcedure = None\r
233 try:\r
234 # launch the command\r
235 Proc = MakeSubProc(Command, stdout=PIPE, stderr=STDOUT, env=os.environ, cwd=WorkingDir, bufsize=-1, shell=True)\r
236\r
237 # launch two threads to read the STDOUT and STDERR\r
238 EndOfProcedure = Event()\r
239 EndOfProcedure.clear()\r
240 if Proc.stdout:\r
241 StdOutThread = Thread(target=ReadMessage, args=(Proc.stdout, EdkLogger.info, EndOfProcedure,Proc.ProcOut))\r
242 StdOutThread.setName("STDOUT-Redirector")\r
243 StdOutThread.setDaemon(False)\r
244 StdOutThread.start()\r
245\r
246\r
247 # waiting for program exit\r
248 Proc.wait()\r
249 except: # in case of aborting\r
250 # terminate the threads redirecting the program output\r
251 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())\r
252 if EndOfProcedure is not None:\r
253 EndOfProcedure.set()\r
254 if Proc is None:\r
255 if not isinstance(Command, type("")):\r
256 Command = " ".join(Command)\r
257 EdkLogger.error("build", COMMAND_FAILURE, "Failed to start command", ExtraData="%s [%s]" % (Command, WorkingDir))\r
258\r
259 if Proc.stdout:\r
260 StdOutThread.join()\r
261\r
262 # check the return code of the program\r
263 if Proc.returncode != 0:\r
264 if not isinstance(Command, type("")):\r
265 Command = " ".join(Command)\r
266 # print out the Response file and its content when make failure\r
267 RespFile = os.path.join(WorkingDir, 'OUTPUT', 'respfilelist.txt')\r
268 if os.path.isfile(RespFile):\r
269 f = open(RespFile)\r
270 RespContent = f.read()\r
271 f.close()\r
272 EdkLogger.info(RespContent)\r
273\r
274 EdkLogger.error("build", COMMAND_FAILURE, ExtraData="%s [%s]" % (Command, WorkingDir))\r
275 if ModuleAuto:\r
276 iau = IncludesAutoGen(WorkingDir,ModuleAuto)\r
277 if ModuleAuto.ToolChainFamily == TAB_COMPILER_MSFT:\r
278 iau.CreateDepsFileForMsvc(Proc.ProcOut)\r
279 else:\r
280 iau.UpdateDepsFileforNonMsvc()\r
281 iau.UpdateDepsFileforTrim()\r
282 iau.CreateModuleDeps()\r
283 iau.CreateDepsInclude()\r
284 iau.CreateDepsTarget()\r
285 return "%dms" % (int(round((time.time() - BeginTime) * 1000)))\r
286\r
287## The smallest unit that can be built in multi-thread build mode\r
288#\r
289# This is the base class of build unit. The "Obj" parameter must provide\r
290# __str__(), __eq__() and __hash__() methods. Otherwise there could be build units\r
291# missing build.\r
292#\r
293# Currently the "Obj" should be only ModuleAutoGen or PlatformAutoGen objects.\r
294#\r
295class BuildUnit:\r
296 ## The constructor\r
297 #\r
298 # @param self The object pointer\r
299 # @param Obj The object the build is working on\r
300 # @param Target The build target name, one of gSupportedTarget\r
301 # @param Dependency The BuildUnit(s) which must be completed in advance\r
302 # @param WorkingDir The directory build command starts in\r
303 #\r
304 def __init__(self, Obj, BuildCommand, Target, Dependency, WorkingDir="."):\r
305 self.BuildObject = Obj\r
306 self.Dependency = Dependency\r
307 self.WorkingDir = WorkingDir\r
308 self.Target = Target\r
309 self.BuildCommand = BuildCommand\r
310 if not BuildCommand:\r
311 EdkLogger.error("build", OPTION_MISSING,\r
312 "No build command found for this module. "\r
313 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %\r
314 (Obj.BuildTarget, Obj.ToolChain, Obj.Arch),\r
315 ExtraData=str(Obj))\r
316\r
317\r
318 ## str() method\r
319 #\r
320 # It just returns the string representation of self.BuildObject\r
321 #\r
322 # @param self The object pointer\r
323 #\r
324 def __str__(self):\r
325 return str(self.BuildObject)\r
326\r
327 ## "==" operator method\r
328 #\r
329 # It just compares self.BuildObject with "Other". So self.BuildObject must\r
330 # provide its own __eq__() method.\r
331 #\r
332 # @param self The object pointer\r
333 # @param Other The other BuildUnit object compared to\r
334 #\r
335 def __eq__(self, Other):\r
336 return Other and self.BuildObject == Other.BuildObject \\r
337 and Other.BuildObject \\r
338 and self.BuildObject.Arch == Other.BuildObject.Arch\r
339\r
340 ## hash() method\r
341 #\r
342 # It just returns the hash value of self.BuildObject which must be hashable.\r
343 #\r
344 # @param self The object pointer\r
345 #\r
346 def __hash__(self):\r
347 return hash(self.BuildObject) + hash(self.BuildObject.Arch)\r
348\r
349 def __repr__(self):\r
350 return repr(self.BuildObject)\r
351\r
352## The smallest module unit that can be built by nmake/make command in multi-thread build mode\r
353#\r
354# This class is for module build by nmake/make build system. The "Obj" parameter\r
355# must provide __str__(), __eq__() and __hash__() methods. Otherwise there could\r
356# be make units missing build.\r
357#\r
358# Currently the "Obj" should be only ModuleAutoGen object.\r
359#\r
360class ModuleMakeUnit(BuildUnit):\r
361 ## The constructor\r
362 #\r
363 # @param self The object pointer\r
364 # @param Obj The ModuleAutoGen object the build is working on\r
365 # @param Target The build target name, one of gSupportedTarget\r
366 #\r
367 def __init__(self, Obj, BuildCommand,Target):\r
368 Dependency = [ModuleMakeUnit(La, BuildCommand,Target) for La in Obj.LibraryAutoGenList]\r
369 BuildUnit.__init__(self, Obj, BuildCommand, Target, Dependency, Obj.MakeFileDir)\r
370 if Target in [None, "", "all"]:\r
371 self.Target = "tbuild"\r
372\r
373## The smallest platform unit that can be built by nmake/make command in multi-thread build mode\r
374#\r
375# This class is for platform build by nmake/make build system. The "Obj" parameter\r
376# must provide __str__(), __eq__() and __hash__() methods. Otherwise there could\r
377# be make units missing build.\r
378#\r
379# Currently the "Obj" should be only PlatformAutoGen object.\r
380#\r
381class PlatformMakeUnit(BuildUnit):\r
382 ## The constructor\r
383 #\r
384 # @param self The object pointer\r
385 # @param Obj The PlatformAutoGen object the build is working on\r
386 # @param Target The build target name, one of gSupportedTarget\r
387 #\r
388 def __init__(self, Obj, BuildCommand, Target):\r
389 Dependency = [ModuleMakeUnit(Lib, BuildCommand, Target) for Lib in self.BuildObject.LibraryAutoGenList]\r
390 Dependency.extend([ModuleMakeUnit(Mod, BuildCommand,Target) for Mod in self.BuildObject.ModuleAutoGenList])\r
391 BuildUnit.__init__(self, Obj, BuildCommand, Target, Dependency, Obj.MakeFileDir)\r
392\r
393## The class representing the task of a module build or platform build\r
394#\r
395# This class manages the build tasks in multi-thread build mode. Its jobs include\r
396# scheduling thread running, catching thread error, monitor the thread status, etc.\r
397#\r
398class BuildTask:\r
399 # queue for tasks waiting for schedule\r
400 _PendingQueue = OrderedDict()\r
401 _PendingQueueLock = threading.Lock()\r
402\r
403 # queue for tasks ready for running\r
404 _ReadyQueue = OrderedDict()\r
405 _ReadyQueueLock = threading.Lock()\r
406\r
407 # queue for run tasks\r
408 _RunningQueue = OrderedDict()\r
409 _RunningQueueLock = threading.Lock()\r
410\r
411 # queue containing all build tasks, in case duplicate build\r
412 _TaskQueue = OrderedDict()\r
413\r
414 # flag indicating error occurs in a running thread\r
415 _ErrorFlag = threading.Event()\r
416 _ErrorFlag.clear()\r
417 _ErrorMessage = ""\r
418\r
419 # BoundedSemaphore object used to control the number of running threads\r
420 _Thread = None\r
421\r
422 # flag indicating if the scheduler is started or not\r
423 _SchedulerStopped = threading.Event()\r
424 _SchedulerStopped.set()\r
425\r
426 ## Start the task scheduler thread\r
427 #\r
428 # @param MaxThreadNumber The maximum thread number\r
429 # @param ExitFlag Flag used to end the scheduler\r
430 #\r
431 @staticmethod\r
432 def StartScheduler(MaxThreadNumber, ExitFlag):\r
433 SchedulerThread = Thread(target=BuildTask.Scheduler, args=(MaxThreadNumber, ExitFlag))\r
434 SchedulerThread.setName("Build-Task-Scheduler")\r
435 SchedulerThread.setDaemon(False)\r
436 SchedulerThread.start()\r
437 # wait for the scheduler to be started, especially useful in Linux\r
438 while not BuildTask.IsOnGoing():\r
439 time.sleep(0.01)\r
440\r
441 ## Scheduler method\r
442 #\r
443 # @param MaxThreadNumber The maximum thread number\r
444 # @param ExitFlag Flag used to end the scheduler\r
445 #\r
446 @staticmethod\r
447 def Scheduler(MaxThreadNumber, ExitFlag):\r
448 BuildTask._SchedulerStopped.clear()\r
449 try:\r
450 # use BoundedSemaphore to control the maximum running threads\r
451 BuildTask._Thread = BoundedSemaphore(MaxThreadNumber)\r
452 #\r
453 # scheduling loop, which will exits when no pending/ready task and\r
454 # indicated to do so, or there's error in running thread\r
455 #\r
456 while (len(BuildTask._PendingQueue) > 0 or len(BuildTask._ReadyQueue) > 0 \\r
457 or not ExitFlag.isSet()) and not BuildTask._ErrorFlag.isSet():\r
458 EdkLogger.debug(EdkLogger.DEBUG_8, "Pending Queue (%d), Ready Queue (%d)"\r
459 % (len(BuildTask._PendingQueue), len(BuildTask._ReadyQueue)))\r
460\r
461 # get all pending tasks\r
462 BuildTask._PendingQueueLock.acquire()\r
463 BuildObjectList = list(BuildTask._PendingQueue.keys())\r
464 #\r
465 # check if their dependency is resolved, and if true, move them\r
466 # into ready queue\r
467 #\r
468 for BuildObject in BuildObjectList:\r
469 Bt = BuildTask._PendingQueue[BuildObject]\r
470 if Bt.IsReady():\r
471 BuildTask._ReadyQueue[BuildObject] = BuildTask._PendingQueue.pop(BuildObject)\r
472 BuildTask._PendingQueueLock.release()\r
473\r
474 # launch build thread until the maximum number of threads is reached\r
475 while not BuildTask._ErrorFlag.isSet():\r
476 # empty ready queue, do nothing further\r
477 if len(BuildTask._ReadyQueue) == 0:\r
478 break\r
479\r
480 # wait for active thread(s) exit\r
481 BuildTask._Thread.acquire(True)\r
482\r
483 # start a new build thread\r
484 Bo, Bt = BuildTask._ReadyQueue.popitem()\r
485\r
486 # move into running queue\r
487 BuildTask._RunningQueueLock.acquire()\r
488 BuildTask._RunningQueue[Bo] = Bt\r
489 BuildTask._RunningQueueLock.release()\r
490\r
491 Bt.Start()\r
492 # avoid tense loop\r
493 time.sleep(0.01)\r
494\r
495 # avoid tense loop\r
496 time.sleep(0.01)\r
497\r
498 # wait for all running threads exit\r
499 if BuildTask._ErrorFlag.isSet():\r
500 EdkLogger.quiet("\nWaiting for all build threads exit...")\r
501 # while not BuildTask._ErrorFlag.isSet() and \\r
502 while len(BuildTask._RunningQueue) > 0:\r
503 EdkLogger.verbose("Waiting for thread ending...(%d)" % len(BuildTask._RunningQueue))\r
504 EdkLogger.debug(EdkLogger.DEBUG_8, "Threads [%s]" % ", ".join(Th.getName() for Th in threading.enumerate()))\r
505 # avoid tense loop\r
506 time.sleep(0.1)\r
507 except BaseException as X:\r
508 #\r
509 # TRICK: hide the output of threads left running, so that the user can\r
510 # catch the error message easily\r
511 #\r
512 EdkLogger.SetLevel(EdkLogger.ERROR)\r
513 BuildTask._ErrorFlag.set()\r
514 BuildTask._ErrorMessage = "build thread scheduler error\n\t%s" % str(X)\r
515\r
516 BuildTask._PendingQueue.clear()\r
517 BuildTask._ReadyQueue.clear()\r
518 BuildTask._RunningQueue.clear()\r
519 BuildTask._TaskQueue.clear()\r
520 BuildTask._SchedulerStopped.set()\r
521\r
522 ## Wait for all running method exit\r
523 #\r
524 @staticmethod\r
525 def WaitForComplete():\r
526 BuildTask._SchedulerStopped.wait()\r
527\r
528 ## Check if the scheduler is running or not\r
529 #\r
530 @staticmethod\r
531 def IsOnGoing():\r
532 return not BuildTask._SchedulerStopped.isSet()\r
533\r
534 ## Abort the build\r
535 @staticmethod\r
536 def Abort():\r
537 if BuildTask.IsOnGoing():\r
538 BuildTask._ErrorFlag.set()\r
539 BuildTask.WaitForComplete()\r
540\r
541 ## Check if there's error in running thread\r
542 #\r
543 # Since the main thread cannot catch exceptions in other thread, we have to\r
544 # use threading.Event to communicate this formation to main thread.\r
545 #\r
546 @staticmethod\r
547 def HasError():\r
548 return BuildTask._ErrorFlag.isSet()\r
549\r
550 ## Get error message in running thread\r
551 #\r
552 # Since the main thread cannot catch exceptions in other thread, we have to\r
553 # use a static variable to communicate this message to main thread.\r
554 #\r
555 @staticmethod\r
556 def GetErrorMessage():\r
557 return BuildTask._ErrorMessage\r
558\r
559 ## Factory method to create a BuildTask object\r
560 #\r
561 # This method will check if a module is building or has been built. And if\r
562 # true, just return the associated BuildTask object in the _TaskQueue. If\r
563 # not, create and return a new BuildTask object. The new BuildTask object\r
564 # will be appended to the _PendingQueue for scheduling later.\r
565 #\r
566 # @param BuildItem A BuildUnit object representing a build object\r
567 # @param Dependency The dependent build object of BuildItem\r
568 #\r
569 @staticmethod\r
570 def New(BuildItem, Dependency=None):\r
571 if BuildItem in BuildTask._TaskQueue:\r
572 Bt = BuildTask._TaskQueue[BuildItem]\r
573 return Bt\r
574\r
575 Bt = BuildTask()\r
576 Bt._Init(BuildItem, Dependency)\r
577 BuildTask._TaskQueue[BuildItem] = Bt\r
578\r
579 BuildTask._PendingQueueLock.acquire()\r
580 BuildTask._PendingQueue[BuildItem] = Bt\r
581 BuildTask._PendingQueueLock.release()\r
582\r
583 return Bt\r
584\r
585 ## The real constructor of BuildTask\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 def _Init(self, BuildItem, Dependency=None):\r
591 self.BuildItem = BuildItem\r
592\r
593 self.DependencyList = []\r
594 if Dependency is None:\r
595 Dependency = BuildItem.Dependency\r
596 else:\r
597 Dependency.extend(BuildItem.Dependency)\r
598 self.AddDependency(Dependency)\r
599 # flag indicating build completes, used to avoid unnecessary re-build\r
600 self.CompleteFlag = False\r
601\r
602 ## Check if all dependent build tasks are completed or not\r
603 #\r
604 def IsReady(self):\r
605 ReadyFlag = True\r
606 for Dep in self.DependencyList:\r
607 if Dep.CompleteFlag == True:\r
608 continue\r
609 ReadyFlag = False\r
610 break\r
611\r
612 return ReadyFlag\r
613\r
614 ## Add dependent build task\r
615 #\r
616 # @param Dependency The list of dependent build objects\r
617 #\r
618 def AddDependency(self, Dependency):\r
619 for Dep in Dependency:\r
620 if not Dep.BuildObject.IsBinaryModule and not Dep.BuildObject.CanSkipbyCache(GlobalData.gModuleCacheHit):\r
621 self.DependencyList.append(BuildTask.New(Dep)) # BuildTask list\r
622\r
623 ## The thread wrapper of LaunchCommand function\r
624 #\r
625 # @param Command A list or string contains the call of the command\r
626 # @param WorkingDir The directory in which the program will be running\r
627 #\r
628 def _CommandThread(self, Command, WorkingDir):\r
629 try:\r
630 self.BuildItem.BuildObject.BuildTime = LaunchCommand(Command, WorkingDir,self.BuildItem.BuildObject)\r
631 self.CompleteFlag = True\r
632\r
633 # Run hash operation post dependency to account for libs\r
634 # Run if --hash or --binary-destination\r
635 if GlobalData.gUseHashCache and not GlobalData.gBinCacheSource:\r
636 self.BuildItem.BuildObject.GenModuleHash()\r
637 if GlobalData.gBinCacheDest:\r
638 self.BuildItem.BuildObject.GenCMakeHash()\r
639\r
640 except:\r
641 #\r
642 # TRICK: hide the output of threads left running, so that the user can\r
643 # catch the error message easily\r
644 #\r
645 if not BuildTask._ErrorFlag.isSet():\r
646 GlobalData.gBuildingModule = "%s [%s, %s, %s]" % (str(self.BuildItem.BuildObject),\r
647 self.BuildItem.BuildObject.Arch,\r
648 self.BuildItem.BuildObject.ToolChain,\r
649 self.BuildItem.BuildObject.BuildTarget\r
650 )\r
651 EdkLogger.SetLevel(EdkLogger.ERROR)\r
652 BuildTask._ErrorFlag.set()\r
653 BuildTask._ErrorMessage = "%s broken\n %s [%s]" % \\r
654 (threading.currentThread().getName(), Command, WorkingDir)\r
655\r
656 # indicate there's a thread is available for another build task\r
657 BuildTask._RunningQueueLock.acquire()\r
658 BuildTask._RunningQueue.pop(self.BuildItem)\r
659 BuildTask._RunningQueueLock.release()\r
660 BuildTask._Thread.release()\r
661\r
662 ## Start build task thread\r
663 #\r
664 def Start(self):\r
665 EdkLogger.quiet("Building ... %s" % repr(self.BuildItem))\r
666 Command = self.BuildItem.BuildCommand + [self.BuildItem.Target]\r
667 self.BuildTread = Thread(target=self._CommandThread, args=(Command, self.BuildItem.WorkingDir))\r
668 self.BuildTread.setName("build thread")\r
669 self.BuildTread.setDaemon(False)\r
670 self.BuildTread.start()\r
671\r
672## The class contains the information related to EFI image\r
673#\r
674class PeImageInfo():\r
675 ## Constructor\r
676 #\r
677 # Constructor will load all required image information.\r
678 #\r
679 # @param BaseName The full file path of image.\r
680 # @param Guid The GUID for image.\r
681 # @param Arch Arch of this image.\r
682 # @param OutputDir The output directory for image.\r
683 # @param DebugDir The debug directory for image.\r
684 # @param ImageClass PeImage Information\r
685 #\r
686 def __init__(self, BaseName, Guid, Arch, OutputDir, DebugDir, ImageClass):\r
687 self.BaseName = BaseName\r
688 self.Guid = Guid\r
689 self.Arch = Arch\r
690 self.OutputDir = OutputDir\r
691 self.DebugDir = DebugDir\r
692 self.Image = ImageClass\r
693 self.Image.Size = (self.Image.Size // 0x1000 + 1) * 0x1000\r
694\r
695## The class implementing the EDK2 build process\r
696#\r
697# The build process includes:\r
698# 1. Load configuration from target.txt and tools_def.txt in $(WORKSPACE)/Conf\r
699# 2. Parse DSC file of active platform\r
700# 3. Parse FDF file if any\r
701# 4. Establish build database, including parse all other files (module, package)\r
702# 5. Create AutoGen files (C code file, depex file, makefile) if necessary\r
703# 6. Call build command\r
704#\r
705class Build():\r
706 ## Constructor\r
707 #\r
708 # Constructor will load all necessary configurations, parse platform, modules\r
709 # and packages and the establish a database for AutoGen.\r
710 #\r
711 # @param Target The build command target, one of gSupportedTarget\r
712 # @param WorkspaceDir The directory of workspace\r
713 # @param BuildOptions Build options passed from command line\r
714 #\r
715 def __init__(self, Target, WorkspaceDir, BuildOptions,log_q):\r
716 self.WorkspaceDir = WorkspaceDir\r
717 self.Target = Target\r
718 self.PlatformFile = BuildOptions.PlatformFile\r
719 self.ModuleFile = BuildOptions.ModuleFile\r
720 self.ArchList = BuildOptions.TargetArch\r
721 self.ToolChainList = BuildOptions.ToolChain\r
722 self.BuildTargetList= BuildOptions.BuildTarget\r
723 self.Fdf = BuildOptions.FdfFile\r
724 self.FdList = BuildOptions.RomImage\r
725 self.FvList = BuildOptions.FvImage\r
726 self.CapList = BuildOptions.CapName\r
727 self.SilentMode = BuildOptions.SilentMode\r
728 self.ThreadNumber = 1\r
729 self.SkipAutoGen = BuildOptions.SkipAutoGen\r
730 self.Reparse = BuildOptions.Reparse\r
731 self.SkuId = BuildOptions.SkuId\r
732 if self.SkuId:\r
733 GlobalData.gSKUID_CMD = self.SkuId\r
734 self.ConfDirectory = BuildOptions.ConfDirectory\r
735 self.SpawnMode = True\r
736 self.BuildReport = BuildReport(BuildOptions.ReportFile, BuildOptions.ReportType)\r
737 self.AutoGenTime = 0\r
738 self.MakeTime = 0\r
739 self.GenFdsTime = 0\r
740 self.MakeFileName = ""\r
741 TargetObj = TargetTxtDict()\r
742 ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"),"Conf")))\r
743 self.TargetTxt = TargetObj.Target\r
744 self.ToolDef = ToolDefObj.ToolDef\r
745 GlobalData.BuildOptionPcd = BuildOptions.OptionPcd if BuildOptions.OptionPcd else []\r
746 #Set global flag for build mode\r
747 GlobalData.gIgnoreSource = BuildOptions.IgnoreSources\r
748 GlobalData.gUseHashCache = BuildOptions.UseHashCache\r
749 GlobalData.gBinCacheDest = BuildOptions.BinCacheDest\r
750 GlobalData.gBinCacheSource = BuildOptions.BinCacheSource\r
751 GlobalData.gEnableGenfdsMultiThread = not BuildOptions.NoGenfdsMultiThread\r
752 GlobalData.gDisableIncludePathCheck = BuildOptions.DisableIncludePathCheck\r
753\r
754 if GlobalData.gBinCacheDest and not GlobalData.gUseHashCache:\r
755 EdkLogger.error("build", OPTION_NOT_SUPPORTED, ExtraData="--binary-destination must be used together with --hash.")\r
756\r
757 if GlobalData.gBinCacheSource and not GlobalData.gUseHashCache:\r
758 EdkLogger.error("build", OPTION_NOT_SUPPORTED, ExtraData="--binary-source must be used together with --hash.")\r
759\r
760 if GlobalData.gBinCacheDest and GlobalData.gBinCacheSource:\r
761 EdkLogger.error("build", OPTION_NOT_SUPPORTED, ExtraData="--binary-destination can not be used together with --binary-source.")\r
762\r
763 if GlobalData.gBinCacheSource:\r
764 BinCacheSource = os.path.normpath(GlobalData.gBinCacheSource)\r
765 if not os.path.isabs(BinCacheSource):\r
766 BinCacheSource = mws.join(self.WorkspaceDir, BinCacheSource)\r
767 GlobalData.gBinCacheSource = BinCacheSource\r
768 else:\r
769 if GlobalData.gBinCacheSource is not None:\r
770 EdkLogger.error("build", OPTION_VALUE_INVALID, ExtraData="Invalid value of option --binary-source.")\r
771\r
772 if GlobalData.gBinCacheDest:\r
773 BinCacheDest = os.path.normpath(GlobalData.gBinCacheDest)\r
774 if not os.path.isabs(BinCacheDest):\r
775 BinCacheDest = mws.join(self.WorkspaceDir, BinCacheDest)\r
776 GlobalData.gBinCacheDest = BinCacheDest\r
777 else:\r
778 if GlobalData.gBinCacheDest is not None:\r
779 EdkLogger.error("build", OPTION_VALUE_INVALID, ExtraData="Invalid value of option --binary-destination.")\r
780\r
781 GlobalData.gDatabasePath = os.path.normpath(os.path.join(GlobalData.gConfDirectory, GlobalData.gDatabasePath))\r
782 if not os.path.exists(os.path.join(GlobalData.gConfDirectory, '.cache')):\r
783 os.makedirs(os.path.join(GlobalData.gConfDirectory, '.cache'))\r
784 self.Db = BuildDB\r
785 self.BuildDatabase = self.Db.BuildObject\r
786 self.Platform = None\r
787 self.ToolChainFamily = None\r
788 self.LoadFixAddress = 0\r
789 self.UniFlag = BuildOptions.Flag\r
790 self.BuildModules = []\r
791 self.HashSkipModules = []\r
792 self.Db_Flag = False\r
793 self.LaunchPrebuildFlag = False\r
794 self.PlatformBuildPath = os.path.join(GlobalData.gConfDirectory, '.cache', '.PlatformBuild')\r
795 if BuildOptions.CommandLength:\r
796 GlobalData.gCommandMaxLength = BuildOptions.CommandLength\r
797\r
798 # print dot character during doing some time-consuming work\r
799 self.Progress = Utils.Progressor()\r
800 # print current build environment and configuration\r
801 EdkLogger.quiet("%-16s = %s" % ("WORKSPACE", os.environ["WORKSPACE"]))\r
802 if "PACKAGES_PATH" in os.environ:\r
803 # WORKSPACE env has been converted before. Print the same path style with WORKSPACE env.\r
804 EdkLogger.quiet("%-16s = %s" % ("PACKAGES_PATH", os.path.normcase(os.path.normpath(os.environ["PACKAGES_PATH"]))))\r
805 EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_PATH", os.environ["EDK_TOOLS_PATH"]))\r
806 if "EDK_TOOLS_BIN" in os.environ:\r
807 # Print the same path style with WORKSPACE env.\r
808 EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_BIN", os.path.normcase(os.path.normpath(os.environ["EDK_TOOLS_BIN"]))))\r
809 EdkLogger.quiet("%-16s = %s" % ("CONF_PATH", GlobalData.gConfDirectory))\r
810 if "PYTHON3_ENABLE" in os.environ:\r
811 PYTHON3_ENABLE = os.environ["PYTHON3_ENABLE"]\r
812 if PYTHON3_ENABLE != "TRUE":\r
813 PYTHON3_ENABLE = "FALSE"\r
814 EdkLogger.quiet("%-16s = %s" % ("PYTHON3_ENABLE", PYTHON3_ENABLE))\r
815 if "PYTHON_COMMAND" in os.environ:\r
816 EdkLogger.quiet("%-16s = %s" % ("PYTHON_COMMAND", os.environ["PYTHON_COMMAND"]))\r
817 self.InitPreBuild()\r
818 self.InitPostBuild()\r
819 if self.Prebuild:\r
820 EdkLogger.quiet("%-16s = %s" % ("PREBUILD", self.Prebuild))\r
821 if self.Postbuild:\r
822 EdkLogger.quiet("%-16s = %s" % ("POSTBUILD", self.Postbuild))\r
823 if self.Prebuild:\r
824 self.LaunchPrebuild()\r
825 TargetObj = TargetTxtDict()\r
826 ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"), "Conf")))\r
827 self.TargetTxt = TargetObj.Target\r
828 self.ToolDef = ToolDefObj.ToolDef\r
829 if not (self.LaunchPrebuildFlag and os.path.exists(self.PlatformBuildPath)):\r
830 self.InitBuild()\r
831\r
832 self.AutoGenMgr = None\r
833 EdkLogger.info("")\r
834 os.chdir(self.WorkspaceDir)\r
835 self.log_q = log_q\r
836 GlobalData.file_lock = mp.Lock()\r
837 # Init cache data for local only\r
838 GlobalData.gPackageHashFile = dict()\r
839 GlobalData.gModulePreMakeCacheStatus = dict()\r
840 GlobalData.gModuleMakeCacheStatus = dict()\r
841 GlobalData.gHashChainStatus = dict()\r
842 GlobalData.gCMakeHashFile = dict()\r
843 GlobalData.gModuleHashFile = dict()\r
844 GlobalData.gFileHashDict = dict()\r
845 GlobalData.gModuleAllCacheStatus = set()\r
846 GlobalData.gModuleCacheHit = set()\r
847\r
848 def StartAutoGen(self,mqueue, DataPipe,SkipAutoGen,PcdMaList,cqueue):\r
849 try:\r
850 if SkipAutoGen:\r
851 return True,0\r
852 feedback_q = mp.Queue()\r
853 error_event = mp.Event()\r
854 FfsCmd = DataPipe.Get("FfsCommand")\r
855 if FfsCmd is None:\r
856 FfsCmd = {}\r
857 GlobalData.FfsCmd = FfsCmd\r
858 auto_workers = [AutoGenWorkerInProcess(mqueue,DataPipe.dump_file,feedback_q,GlobalData.file_lock,cqueue,self.log_q,error_event) for _ in range(self.ThreadNumber)]\r
859 self.AutoGenMgr = AutoGenManager(auto_workers,feedback_q,error_event)\r
860 self.AutoGenMgr.start()\r
861 for w in auto_workers:\r
862 w.start()\r
863 if PcdMaList is not None:\r
864 for PcdMa in PcdMaList:\r
865 # SourceFileList calling sequence impact the makefile string sequence.\r
866 # Create cached SourceFileList here to unify its calling sequence for both\r
867 # CanSkipbyPreMakeCache and CreateCodeFile/CreateMakeFile.\r
868 RetVal = PcdMa.SourceFileList\r
869 # Force cache miss for PCD driver\r
870 if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and self.Target in [None, "", "all"]:\r
871 cqueue.put((PcdMa.MetaFile.Path, PcdMa.Arch, "PreMakeCache", False))\r
872\r
873 PcdMa.CreateCodeFile(False)\r
874 PcdMa.CreateMakeFile(False,GenFfsList = DataPipe.Get("FfsCommand").get((PcdMa.MetaFile.Path, PcdMa.Arch),[]))\r
875\r
876 # Force cache miss for PCD driver\r
877 if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]:\r
878 cqueue.put((PcdMa.MetaFile.Path, PcdMa.Arch, "MakeCache", False))\r
879\r
880 self.AutoGenMgr.join()\r
881 rt = self.AutoGenMgr.Status\r
882 return rt, 0\r
883 except FatalError as e:\r
884 return False, e.args[0]\r
885 except:\r
886 return False, UNKNOWN_ERROR\r
887\r
888 ## Load configuration\r
889 #\r
890 # This method will parse target.txt and get the build configurations.\r
891 #\r
892 def LoadConfiguration(self):\r
893\r
894 # if no ARCH given in command line, get it from target.txt\r
895 if not self.ArchList:\r
896 self.ArchList = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TARGET_ARCH]\r
897 self.ArchList = tuple(self.ArchList)\r
898\r
899 # if no build target given in command line, get it from target.txt\r
900 if not self.BuildTargetList:\r
901 self.BuildTargetList = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TARGET]\r
902\r
903 # if no tool chain given in command line, get it from target.txt\r
904 if not self.ToolChainList:\r
905 self.ToolChainList = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TOOL_CHAIN_TAG]\r
906 if self.ToolChainList is None or len(self.ToolChainList) == 0:\r
907 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE, ExtraData="No toolchain given. Don't know how to build.\n")\r
908\r
909 # check if the tool chains are defined or not\r
910 NewToolChainList = []\r
911 for ToolChain in self.ToolChainList:\r
912 if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG]:\r
913 EdkLogger.warn("build", "Tool chain [%s] is not defined" % ToolChain)\r
914 else:\r
915 NewToolChainList.append(ToolChain)\r
916 # if no tool chain available, break the build\r
917 if len(NewToolChainList) == 0:\r
918 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,\r
919 ExtraData="[%s] not defined. No toolchain available for build!\n" % ", ".join(self.ToolChainList))\r
920 else:\r
921 self.ToolChainList = NewToolChainList\r
922\r
923 ToolChainFamily = []\r
924 ToolDefinition = self.ToolDef.ToolsDefTxtDatabase\r
925 for Tool in self.ToolChainList:\r
926 if TAB_TOD_DEFINES_FAMILY not in ToolDefinition or Tool not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \\r
927 or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][Tool]:\r
928 EdkLogger.warn("build", "No tool chain family found in configuration for %s. Default to MSFT." % Tool)\r
929 ToolChainFamily.append(TAB_COMPILER_MSFT)\r
930 else:\r
931 ToolChainFamily.append(ToolDefinition[TAB_TOD_DEFINES_FAMILY][Tool])\r
932 self.ToolChainFamily = ToolChainFamily\r
933\r
934 if not self.PlatformFile:\r
935 PlatformFile = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_ACTIVE_PLATFORM]\r
936 if not PlatformFile:\r
937 # Try to find one in current directory\r
938 WorkingDirectory = os.getcwd()\r
939 FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.dsc')))\r
940 FileNum = len(FileList)\r
941 if FileNum >= 2:\r
942 EdkLogger.error("build", OPTION_MISSING,\r
943 ExtraData="There are %d DSC files in %s. Use '-p' to specify one.\n" % (FileNum, WorkingDirectory))\r
944 elif FileNum == 1:\r
945 PlatformFile = FileList[0]\r
946 else:\r
947 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,\r
948 ExtraData="No active platform specified in target.txt or command line! Nothing can be built.\n")\r
949\r
950 self.PlatformFile = PathClass(NormFile(PlatformFile, self.WorkspaceDir), self.WorkspaceDir)\r
951 self.ThreadNumber = ThreadNum()\r
952 ## Initialize build configuration\r
953 #\r
954 # This method will parse DSC file and merge the configurations from\r
955 # command line and target.txt, then get the final build configurations.\r
956 #\r
957 def InitBuild(self):\r
958 # parse target.txt, tools_def.txt, and platform file\r
959 self.LoadConfiguration()\r
960\r
961 # Allow case-insensitive for those from command line or configuration file\r
962 ErrorCode, ErrorInfo = self.PlatformFile.Validate(".dsc", False)\r
963 if ErrorCode != 0:\r
964 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)\r
965\r
966\r
967 def InitPreBuild(self):\r
968 self.LoadConfiguration()\r
969 ErrorCode, ErrorInfo = self.PlatformFile.Validate(".dsc", False)\r
970 if ErrorCode != 0:\r
971 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)\r
972 if self.BuildTargetList:\r
973 GlobalData.gGlobalDefines['TARGET'] = self.BuildTargetList[0]\r
974 if self.ArchList:\r
975 GlobalData.gGlobalDefines['ARCH'] = self.ArchList[0]\r
976 if self.ToolChainList:\r
977 GlobalData.gGlobalDefines['TOOLCHAIN'] = self.ToolChainList[0]\r
978 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = self.ToolChainList[0]\r
979 if self.ToolChainFamily:\r
980 GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[0]\r
981 if 'PREBUILD' in GlobalData.gCommandLineDefines:\r
982 self.Prebuild = GlobalData.gCommandLineDefines.get('PREBUILD')\r
983 else:\r
984 self.Db_Flag = True\r
985 Platform = self.Db.MapPlatform(str(self.PlatformFile))\r
986 self.Prebuild = str(Platform.Prebuild)\r
987 if self.Prebuild:\r
988 PrebuildList = []\r
989 #\r
990 # Evaluate all arguments and convert arguments that are WORKSPACE\r
991 # relative paths to absolute paths. Filter arguments that look like\r
992 # flags or do not follow the file/dir naming rules to avoid false\r
993 # positives on this conversion.\r
994 #\r
995 for Arg in self.Prebuild.split():\r
996 #\r
997 # Do not modify Arg if it looks like a flag or an absolute file path\r
998 #\r
999 if Arg.startswith('-') or os.path.isabs(Arg):\r
1000 PrebuildList.append(Arg)\r
1001 continue\r
1002 #\r
1003 # Do not modify Arg if it does not look like a Workspace relative\r
1004 # path that starts with a valid package directory name\r
1005 #\r
1006 if not Arg[0].isalpha() or os.path.dirname(Arg) == '':\r
1007 PrebuildList.append(Arg)\r
1008 continue\r
1009 #\r
1010 # If Arg looks like a WORKSPACE relative path, then convert to an\r
1011 # absolute path and check to see if the file exists.\r
1012 #\r
1013 Temp = mws.join(self.WorkspaceDir, Arg)\r
1014 if os.path.isfile(Temp):\r
1015 Arg = Temp\r
1016 PrebuildList.append(Arg)\r
1017 self.Prebuild = ' '.join(PrebuildList)\r
1018 self.Prebuild += self.PassCommandOption(self.BuildTargetList, self.ArchList, self.ToolChainList, self.PlatformFile, self.Target)\r
1019\r
1020 def InitPostBuild(self):\r
1021 if 'POSTBUILD' in GlobalData.gCommandLineDefines:\r
1022 self.Postbuild = GlobalData.gCommandLineDefines.get('POSTBUILD')\r
1023 else:\r
1024 Platform = self.Db.MapPlatform(str(self.PlatformFile))\r
1025 self.Postbuild = str(Platform.Postbuild)\r
1026 if self.Postbuild:\r
1027 PostbuildList = []\r
1028 #\r
1029 # Evaluate all arguments and convert arguments that are WORKSPACE\r
1030 # relative paths to absolute paths. Filter arguments that look like\r
1031 # flags or do not follow the file/dir naming rules to avoid false\r
1032 # positives on this conversion.\r
1033 #\r
1034 for Arg in self.Postbuild.split():\r
1035 #\r
1036 # Do not modify Arg if it looks like a flag or an absolute file path\r
1037 #\r
1038 if Arg.startswith('-') or os.path.isabs(Arg):\r
1039 PostbuildList.append(Arg)\r
1040 continue\r
1041 #\r
1042 # Do not modify Arg if it does not look like a Workspace relative\r
1043 # path that starts with a valid package directory name\r
1044 #\r
1045 if not Arg[0].isalpha() or os.path.dirname(Arg) == '':\r
1046 PostbuildList.append(Arg)\r
1047 continue\r
1048 #\r
1049 # If Arg looks like a WORKSPACE relative path, then convert to an\r
1050 # absolute path and check to see if the file exists.\r
1051 #\r
1052 Temp = mws.join(self.WorkspaceDir, Arg)\r
1053 if os.path.isfile(Temp):\r
1054 Arg = Temp\r
1055 PostbuildList.append(Arg)\r
1056 self.Postbuild = ' '.join(PostbuildList)\r
1057 self.Postbuild += self.PassCommandOption(self.BuildTargetList, self.ArchList, self.ToolChainList, self.PlatformFile, self.Target)\r
1058\r
1059 def PassCommandOption(self, BuildTarget, TargetArch, ToolChain, PlatformFile, Target):\r
1060 BuildStr = ''\r
1061 if GlobalData.gCommand and isinstance(GlobalData.gCommand, list):\r
1062 BuildStr += ' ' + ' '.join(GlobalData.gCommand)\r
1063 TargetFlag = False\r
1064 ArchFlag = False\r
1065 ToolChainFlag = False\r
1066 PlatformFileFlag = False\r
1067\r
1068 if GlobalData.gOptions and not GlobalData.gOptions.BuildTarget:\r
1069 TargetFlag = True\r
1070 if GlobalData.gOptions and not GlobalData.gOptions.TargetArch:\r
1071 ArchFlag = True\r
1072 if GlobalData.gOptions and not GlobalData.gOptions.ToolChain:\r
1073 ToolChainFlag = True\r
1074 if GlobalData.gOptions and not GlobalData.gOptions.PlatformFile:\r
1075 PlatformFileFlag = True\r
1076\r
1077 if TargetFlag and BuildTarget:\r
1078 if isinstance(BuildTarget, list) or isinstance(BuildTarget, tuple):\r
1079 BuildStr += ' -b ' + ' -b '.join(BuildTarget)\r
1080 elif isinstance(BuildTarget, str):\r
1081 BuildStr += ' -b ' + BuildTarget\r
1082 if ArchFlag and TargetArch:\r
1083 if isinstance(TargetArch, list) or isinstance(TargetArch, tuple):\r
1084 BuildStr += ' -a ' + ' -a '.join(TargetArch)\r
1085 elif isinstance(TargetArch, str):\r
1086 BuildStr += ' -a ' + TargetArch\r
1087 if ToolChainFlag and ToolChain:\r
1088 if isinstance(ToolChain, list) or isinstance(ToolChain, tuple):\r
1089 BuildStr += ' -t ' + ' -t '.join(ToolChain)\r
1090 elif isinstance(ToolChain, str):\r
1091 BuildStr += ' -t ' + ToolChain\r
1092 if PlatformFileFlag and PlatformFile:\r
1093 if isinstance(PlatformFile, list) or isinstance(PlatformFile, tuple):\r
1094 BuildStr += ' -p ' + ' -p '.join(PlatformFile)\r
1095 elif isinstance(PlatformFile, str):\r
1096 BuildStr += ' -p' + PlatformFile\r
1097 BuildStr += ' --conf=' + GlobalData.gConfDirectory\r
1098 if Target:\r
1099 BuildStr += ' ' + Target\r
1100\r
1101 return BuildStr\r
1102\r
1103 def LaunchPrebuild(self):\r
1104 if self.Prebuild:\r
1105 EdkLogger.info("\n- Prebuild Start -\n")\r
1106 self.LaunchPrebuildFlag = True\r
1107 #\r
1108 # The purpose of .PrebuildEnv file is capture environment variable settings set by the prebuild script\r
1109 # and preserve them for the rest of the main build step, because the child process environment will\r
1110 # evaporate as soon as it exits, we cannot get it in build step.\r
1111 #\r
1112 PrebuildEnvFile = os.path.join(GlobalData.gConfDirectory, '.cache', '.PrebuildEnv')\r
1113 if os.path.isfile(PrebuildEnvFile):\r
1114 os.remove(PrebuildEnvFile)\r
1115 if os.path.isfile(self.PlatformBuildPath):\r
1116 os.remove(self.PlatformBuildPath)\r
1117 if sys.platform == "win32":\r
1118 args = ' && '.join((self.Prebuild, 'set > ' + PrebuildEnvFile))\r
1119 Process = Popen(args, stdout=PIPE, stderr=PIPE, shell=True)\r
1120 else:\r
1121 args = ' && '.join((self.Prebuild, 'env > ' + PrebuildEnvFile))\r
1122 Process = Popen(args, stdout=PIPE, stderr=PIPE, shell=True)\r
1123\r
1124 # launch two threads to read the STDOUT and STDERR\r
1125 EndOfProcedure = Event()\r
1126 EndOfProcedure.clear()\r
1127 if Process.stdout:\r
1128 StdOutThread = Thread(target=ReadMessage, args=(Process.stdout, EdkLogger.info, EndOfProcedure))\r
1129 StdOutThread.setName("STDOUT-Redirector")\r
1130 StdOutThread.setDaemon(False)\r
1131 StdOutThread.start()\r
1132\r
1133 if Process.stderr:\r
1134 StdErrThread = Thread(target=ReadMessage, args=(Process.stderr, EdkLogger.quiet, EndOfProcedure))\r
1135 StdErrThread.setName("STDERR-Redirector")\r
1136 StdErrThread.setDaemon(False)\r
1137 StdErrThread.start()\r
1138 # waiting for program exit\r
1139 Process.wait()\r
1140\r
1141 if Process.stdout:\r
1142 StdOutThread.join()\r
1143 if Process.stderr:\r
1144 StdErrThread.join()\r
1145 if Process.returncode != 0 :\r
1146 EdkLogger.error("Prebuild", PREBUILD_ERROR, 'Prebuild process is not success!')\r
1147\r
1148 if os.path.exists(PrebuildEnvFile):\r
1149 f = open(PrebuildEnvFile)\r
1150 envs = f.readlines()\r
1151 f.close()\r
1152 envs = [l.split("=", 1) for l in envs ]\r
1153 envs = [[I.strip() for I in item] for item in envs if len(item) == 2]\r
1154 os.environ.update(dict(envs))\r
1155 EdkLogger.info("\n- Prebuild Done -\n")\r
1156\r
1157 def LaunchPostbuild(self):\r
1158 if self.Postbuild:\r
1159 EdkLogger.info("\n- Postbuild Start -\n")\r
1160 if sys.platform == "win32":\r
1161 Process = Popen(self.Postbuild, stdout=PIPE, stderr=PIPE, shell=True)\r
1162 else:\r
1163 Process = Popen(self.Postbuild, stdout=PIPE, stderr=PIPE, shell=True)\r
1164 # launch two threads to read the STDOUT and STDERR\r
1165 EndOfProcedure = Event()\r
1166 EndOfProcedure.clear()\r
1167 if Process.stdout:\r
1168 StdOutThread = Thread(target=ReadMessage, args=(Process.stdout, EdkLogger.info, EndOfProcedure))\r
1169 StdOutThread.setName("STDOUT-Redirector")\r
1170 StdOutThread.setDaemon(False)\r
1171 StdOutThread.start()\r
1172\r
1173 if Process.stderr:\r
1174 StdErrThread = Thread(target=ReadMessage, args=(Process.stderr, EdkLogger.quiet, EndOfProcedure))\r
1175 StdErrThread.setName("STDERR-Redirector")\r
1176 StdErrThread.setDaemon(False)\r
1177 StdErrThread.start()\r
1178 # waiting for program exit\r
1179 Process.wait()\r
1180\r
1181 if Process.stdout:\r
1182 StdOutThread.join()\r
1183 if Process.stderr:\r
1184 StdErrThread.join()\r
1185 if Process.returncode != 0 :\r
1186 EdkLogger.error("Postbuild", POSTBUILD_ERROR, 'Postbuild process is not success!')\r
1187 EdkLogger.info("\n- Postbuild Done -\n")\r
1188\r
1189 ## Build a module or platform\r
1190 #\r
1191 # Create autogen code and makefile for a module or platform, and the launch\r
1192 # "make" command to build it\r
1193 #\r
1194 # @param Target The target of build command\r
1195 # @param Platform The platform file\r
1196 # @param Module The module file\r
1197 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"\r
1198 # @param ToolChain The name of toolchain to build\r
1199 # @param Arch The arch of the module/platform\r
1200 # @param CreateDepModuleCodeFile Flag used to indicate creating code\r
1201 # for dependent modules/Libraries\r
1202 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile\r
1203 # for dependent modules/Libraries\r
1204 #\r
1205 def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False, FfsCommand=None, PcdMaList=None):\r
1206 if AutoGenObject is None:\r
1207 return False\r
1208 if FfsCommand is None:\r
1209 FfsCommand = {}\r
1210 # skip file generation for cleanxxx targets, run and fds target\r
1211 if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:\r
1212 # for target which must generate AutoGen code and makefile\r
1213 mqueue = mp.Queue()\r
1214 for m in AutoGenObject.GetAllModuleInfo:\r
1215 mqueue.put(m)\r
1216\r
1217 AutoGenObject.DataPipe.DataContainer = {"CommandTarget": self.Target}\r
1218 AutoGenObject.DataPipe.DataContainer = {"Workspace_timestamp": AutoGenObject.Workspace._SrcTimeStamp}\r
1219 AutoGenObject.CreateLibModuelDirs()\r
1220 AutoGenObject.DataPipe.DataContainer = {"LibraryBuildDirectoryList":AutoGenObject.LibraryBuildDirectoryList}\r
1221 AutoGenObject.DataPipe.DataContainer = {"ModuleBuildDirectoryList":AutoGenObject.ModuleBuildDirectoryList}\r
1222 AutoGenObject.DataPipe.DataContainer = {"FdsCommandDict": AutoGenObject.Workspace.GenFdsCommandDict}\r
1223 self.Progress.Start("Generating makefile and code")\r
1224 data_pipe_file = os.path.join(AutoGenObject.BuildDir, "GlobalVar_%s_%s.bin" % (str(AutoGenObject.Guid),AutoGenObject.Arch))\r
1225 AutoGenObject.DataPipe.dump(data_pipe_file)\r
1226 cqueue = mp.Queue()\r
1227 autogen_rt,errorcode = self.StartAutoGen(mqueue, AutoGenObject.DataPipe, self.SkipAutoGen, PcdMaList, cqueue)\r
1228 AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt")\r
1229 with open(AutoGenIdFile,"w") as fw:\r
1230 fw.write("Arch=%s\n" % "|".join((AutoGenObject.Workspace.ArchList)))\r
1231 fw.write("BuildDir=%s\n" % AutoGenObject.Workspace.BuildDir)\r
1232 fw.write("PlatformGuid=%s\n" % str(AutoGenObject.Guid))\r
1233 self.Progress.Stop("done!")\r
1234 if not autogen_rt:\r
1235 self.AutoGenMgr.TerminateWorkers()\r
1236 self.AutoGenMgr.join(1)\r
1237 raise FatalError(errorcode)\r
1238 AutoGenObject.CreateCodeFile(False)\r
1239 AutoGenObject.CreateMakeFile(False)\r
1240 else:\r
1241 # always recreate top/platform makefile when clean, just in case of inconsistency\r
1242 AutoGenObject.CreateCodeFile(True)\r
1243 AutoGenObject.CreateMakeFile(True)\r
1244\r
1245 if EdkLogger.GetLevel() == EdkLogger.QUIET:\r
1246 EdkLogger.quiet("Building ... %s" % repr(AutoGenObject))\r
1247\r
1248 BuildCommand = AutoGenObject.BuildCommand\r
1249 if BuildCommand is None or len(BuildCommand) == 0:\r
1250 EdkLogger.error("build", OPTION_MISSING,\r
1251 "No build command found for this module. "\r
1252 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %\r
1253 (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch),\r
1254 ExtraData=str(AutoGenObject))\r
1255\r
1256 # run\r
1257 if Target == 'run':\r
1258 return True\r
1259\r
1260 # build modules\r
1261 if BuildModule:\r
1262 BuildCommand = BuildCommand + [Target]\r
1263 LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir)\r
1264 self.CreateAsBuiltInf()\r
1265 if GlobalData.gBinCacheDest:\r
1266 self.GenDestCache()\r
1267 elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource:\r
1268 # Only for --hash\r
1269 # Update PreMakeCacheChain files\r
1270 self.GenLocalPreMakeCache()\r
1271 self.BuildModules = []\r
1272 return True\r
1273\r
1274 # build library\r
1275 if Target == 'libraries':\r
1276 DirList = []\r
1277 for Lib in AutoGenObject.LibraryAutoGenList:\r
1278 if not Lib.IsBinaryModule:\r
1279 DirList.append((os.path.join(AutoGenObject.BuildDir, Lib.BuildDir),Lib))\r
1280 for Lib, LibAutoGen in DirList:\r
1281 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, self.MakeFileName)), 'pbuild']\r
1282 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,LibAutoGen)\r
1283 return True\r
1284\r
1285 # build module\r
1286 if Target == 'modules':\r
1287 DirList = []\r
1288 for Lib in AutoGenObject.LibraryAutoGenList:\r
1289 if not Lib.IsBinaryModule:\r
1290 DirList.append((os.path.join(AutoGenObject.BuildDir, Lib.BuildDir),Lib))\r
1291 for Lib, LibAutoGen in DirList:\r
1292 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, self.MakeFileName)), 'pbuild']\r
1293 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,LibAutoGen)\r
1294\r
1295 DirList = []\r
1296 for ModuleAutoGen in AutoGenObject.ModuleAutoGenList:\r
1297 if not ModuleAutoGen.IsBinaryModule:\r
1298 DirList.append((os.path.join(AutoGenObject.BuildDir, ModuleAutoGen.BuildDir),ModuleAutoGen))\r
1299 for Mod,ModAutoGen in DirList:\r
1300 NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Mod, self.MakeFileName)), 'pbuild']\r
1301 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,ModAutoGen)\r
1302 self.CreateAsBuiltInf()\r
1303 if GlobalData.gBinCacheDest:\r
1304 self.GenDestCache()\r
1305 elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource:\r
1306 # Only for --hash\r
1307 # Update PreMakeCacheChain files\r
1308 self.GenLocalPreMakeCache()\r
1309 self.BuildModules = []\r
1310 return True\r
1311\r
1312 # cleanlib\r
1313 if Target == 'cleanlib':\r
1314 for Lib in AutoGenObject.LibraryBuildDirectoryList:\r
1315 LibMakefile = os.path.normpath(os.path.join(Lib, self.MakeFileName))\r
1316 if os.path.exists(LibMakefile):\r
1317 NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall']\r
1318 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)\r
1319 return True\r
1320\r
1321 # clean\r
1322 if Target == 'clean':\r
1323 for Mod in AutoGenObject.ModuleBuildDirectoryList:\r
1324 ModMakefile = os.path.normpath(os.path.join(Mod, self.MakeFileName))\r
1325 if os.path.exists(ModMakefile):\r
1326 NewBuildCommand = BuildCommand + ['-f', ModMakefile, 'cleanall']\r
1327 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)\r
1328 for Lib in AutoGenObject.LibraryBuildDirectoryList:\r
1329 LibMakefile = os.path.normpath(os.path.join(Lib, self.MakeFileName))\r
1330 if os.path.exists(LibMakefile):\r
1331 NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall']\r
1332 LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir)\r
1333 return True\r
1334\r
1335 # cleanall\r
1336 if Target == 'cleanall':\r
1337 try:\r
1338 #os.rmdir(AutoGenObject.BuildDir)\r
1339 RemoveDirectory(AutoGenObject.BuildDir, True)\r
1340 except WindowsError as X:\r
1341 EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X))\r
1342 return True\r
1343\r
1344 ## Build a module or platform\r
1345 #\r
1346 # Create autogen code and makefile for a module or platform, and the launch\r
1347 # "make" command to build it\r
1348 #\r
1349 # @param Target The target of build command\r
1350 # @param Platform The platform file\r
1351 # @param Module The module file\r
1352 # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE"\r
1353 # @param ToolChain The name of toolchain to build\r
1354 # @param Arch The arch of the module/platform\r
1355 # @param CreateDepModuleCodeFile Flag used to indicate creating code\r
1356 # for dependent modules/Libraries\r
1357 # @param CreateDepModuleMakeFile Flag used to indicate creating makefile\r
1358 # for dependent modules/Libraries\r
1359 #\r
1360 def _Build(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False):\r
1361 if AutoGenObject is None:\r
1362 return False\r
1363\r
1364 # skip file generation for cleanxxx targets, run and fds target\r
1365 if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:\r
1366 # for target which must generate AutoGen code and makefile\r
1367 if not self.SkipAutoGen or Target == 'genc':\r
1368 self.Progress.Start("Generating code")\r
1369 AutoGenObject.CreateCodeFile(CreateDepsCodeFile)\r
1370 self.Progress.Stop("done!")\r
1371 if Target == "genc":\r
1372 return True\r
1373\r
1374 if not self.SkipAutoGen or Target == 'genmake':\r
1375 self.Progress.Start("Generating makefile")\r
1376 AutoGenObject.CreateMakeFile(CreateDepsMakeFile)\r
1377 #AutoGenObject.CreateAsBuiltInf()\r
1378 self.Progress.Stop("done!")\r
1379 if Target == "genmake":\r
1380 return True\r
1381 else:\r
1382 # always recreate top/platform makefile when clean, just in case of inconsistency\r
1383 AutoGenObject.CreateCodeFile(True)\r
1384 AutoGenObject.CreateMakeFile(True)\r
1385\r
1386 if EdkLogger.GetLevel() == EdkLogger.QUIET:\r
1387 EdkLogger.quiet("Building ... %s" % repr(AutoGenObject))\r
1388\r
1389 BuildCommand = AutoGenObject.BuildCommand\r
1390 if BuildCommand is None or len(BuildCommand) == 0:\r
1391 EdkLogger.error("build", OPTION_MISSING,\r
1392 "No build command found for this module. "\r
1393 "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." %\r
1394 (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch),\r
1395 ExtraData=str(AutoGenObject))\r
1396\r
1397 # build modules\r
1398 if BuildModule:\r
1399 if Target != 'fds':\r
1400 BuildCommand = BuildCommand + [Target]\r
1401 AutoGenObject.BuildTime = LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir)\r
1402 self.CreateAsBuiltInf()\r
1403 if GlobalData.gBinCacheDest:\r
1404 self.GenDestCache()\r
1405 elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource:\r
1406 # Only for --hash\r
1407 # Update PreMakeCacheChain files\r
1408 self.GenLocalPreMakeCache()\r
1409 self.BuildModules = []\r
1410 return True\r
1411\r
1412 # genfds\r
1413 if Target == 'fds':\r
1414 if GenFdsApi(AutoGenObject.GenFdsCommandDict, self.Db):\r
1415 EdkLogger.error("build", COMMAND_FAILURE)\r
1416 return True\r
1417\r
1418 # run\r
1419 if Target == 'run':\r
1420 return True\r
1421\r
1422 # build library\r
1423 if Target == 'libraries':\r
1424 pass\r
1425\r
1426 # not build modules\r
1427\r
1428\r
1429 # cleanall\r
1430 if Target == 'cleanall':\r
1431 try:\r
1432 #os.rmdir(AutoGenObject.BuildDir)\r
1433 RemoveDirectory(AutoGenObject.BuildDir, True)\r
1434 except WindowsError as X:\r
1435 EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X))\r
1436 return True\r
1437\r
1438 ## Rebase module image and Get function address for the input module list.\r
1439 #\r
1440 def _RebaseModule (self, MapBuffer, BaseAddress, ModuleList, AddrIsOffset = True, ModeIsSmm = False):\r
1441 if ModeIsSmm:\r
1442 AddrIsOffset = False\r
1443 for InfFile in ModuleList:\r
1444 sys.stdout.write (".")\r
1445 sys.stdout.flush()\r
1446 ModuleInfo = ModuleList[InfFile]\r
1447 ModuleName = ModuleInfo.BaseName\r
1448 ModuleOutputImage = ModuleInfo.Image.FileName\r
1449 ModuleDebugImage = os.path.join(ModuleInfo.DebugDir, ModuleInfo.BaseName + '.efi')\r
1450 ## for SMM module in SMRAM, the SMRAM will be allocated from base to top.\r
1451 if not ModeIsSmm:\r
1452 BaseAddress = BaseAddress - ModuleInfo.Image.Size\r
1453 #\r
1454 # Update Image to new BaseAddress by GenFw tool\r
1455 #\r
1456 LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir)\r
1457 LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir)\r
1458 else:\r
1459 #\r
1460 # Set new address to the section header only for SMM driver.\r
1461 #\r
1462 LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir)\r
1463 LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir)\r
1464 #\r
1465 # Collect function address from Map file\r
1466 #\r
1467 ImageMapTable = ModuleOutputImage.replace('.efi', '.map')\r
1468 FunctionList = []\r
1469 if os.path.exists(ImageMapTable):\r
1470 OrigImageBaseAddress = 0\r
1471 ImageMap = open(ImageMapTable, 'r')\r
1472 for LinStr in ImageMap:\r
1473 if len (LinStr.strip()) == 0:\r
1474 continue\r
1475 #\r
1476 # Get the preferred address set on link time.\r
1477 #\r
1478 if LinStr.find ('Preferred load address is') != -1:\r
1479 StrList = LinStr.split()\r
1480 OrigImageBaseAddress = int (StrList[len(StrList) - 1], 16)\r
1481\r
1482 StrList = LinStr.split()\r
1483 if len (StrList) > 4:\r
1484 if StrList[3] == 'f' or StrList[3] == 'F':\r
1485 Name = StrList[1]\r
1486 RelativeAddress = int (StrList[2], 16) - OrigImageBaseAddress\r
1487 FunctionList.append ((Name, RelativeAddress))\r
1488\r
1489 ImageMap.close()\r
1490 #\r
1491 # Add general information.\r
1492 #\r
1493 if ModeIsSmm:\r
1494 MapBuffer.append('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint))\r
1495 elif AddrIsOffset:\r
1496 MapBuffer.append('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName, 0 - BaseAddress, 0 - (BaseAddress + ModuleInfo.Image.EntryPoint)))\r
1497 else:\r
1498 MapBuffer.append('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint))\r
1499 #\r
1500 # Add guid and general seciton section.\r
1501 #\r
1502 TextSectionAddress = 0\r
1503 DataSectionAddress = 0\r
1504 for SectionHeader in ModuleInfo.Image.SectionHeaderList:\r
1505 if SectionHeader[0] == '.text':\r
1506 TextSectionAddress = SectionHeader[1]\r
1507 elif SectionHeader[0] in ['.data', '.sdata']:\r
1508 DataSectionAddress = SectionHeader[1]\r
1509 if AddrIsOffset:\r
1510 MapBuffer.append('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + TextSectionAddress), 0 - (BaseAddress + DataSectionAddress)))\r
1511 else:\r
1512 MapBuffer.append('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo.Guid, BaseAddress + TextSectionAddress, BaseAddress + DataSectionAddress))\r
1513 #\r
1514 # Add debug image full path.\r
1515 #\r
1516 MapBuffer.append('(IMAGE=%s)\n\n' % (ModuleDebugImage))\r
1517 #\r
1518 # Add function address\r
1519 #\r
1520 for Function in FunctionList:\r
1521 if AddrIsOffset:\r
1522 MapBuffer.append(' -0x%010X %s\n' % (0 - (BaseAddress + Function[1]), Function[0]))\r
1523 else:\r
1524 MapBuffer.append(' 0x%010X %s\n' % (BaseAddress + Function[1], Function[0]))\r
1525 ImageMap.close()\r
1526\r
1527 #\r
1528 # for SMM module in SMRAM, the SMRAM will be allocated from base to top.\r
1529 #\r
1530 if ModeIsSmm:\r
1531 BaseAddress = BaseAddress + ModuleInfo.Image.Size\r
1532\r
1533 ## Collect MAP information of all FVs\r
1534 #\r
1535 def _CollectFvMapBuffer (self, MapBuffer, Wa, ModuleList):\r
1536 if self.Fdf:\r
1537 # First get the XIP base address for FV map file.\r
1538 GuidPattern = re.compile("[-a-fA-F0-9]+")\r
1539 GuidName = re.compile(r"\(GUID=[-a-fA-F0-9]+")\r
1540 for FvName in Wa.FdfProfile.FvDict:\r
1541 FvMapBuffer = os.path.join(Wa.FvDir, FvName + '.Fv.map')\r
1542 if not os.path.exists(FvMapBuffer):\r
1543 continue\r
1544 FvMap = open(FvMapBuffer, 'r')\r
1545 #skip FV size information\r
1546 FvMap.readline()\r
1547 FvMap.readline()\r
1548 FvMap.readline()\r
1549 FvMap.readline()\r
1550 for Line in FvMap:\r
1551 MatchGuid = GuidPattern.match(Line)\r
1552 if MatchGuid is not None:\r
1553 #\r
1554 # Replace GUID with module name\r
1555 #\r
1556 GuidString = MatchGuid.group()\r
1557 if GuidString.upper() in ModuleList:\r
1558 Line = Line.replace(GuidString, ModuleList[GuidString.upper()].Name)\r
1559 MapBuffer.append(Line)\r
1560 #\r
1561 # Add the debug image full path.\r
1562 #\r
1563 MatchGuid = GuidName.match(Line)\r
1564 if MatchGuid is not None:\r
1565 GuidString = MatchGuid.group().split("=")[1]\r
1566 if GuidString.upper() in ModuleList:\r
1567 MapBuffer.append('(IMAGE=%s)\n' % (os.path.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].Name + '.efi')))\r
1568\r
1569 FvMap.close()\r
1570\r
1571 ## Collect MAP information of all modules\r
1572 #\r
1573 def _CollectModuleMapBuffer (self, MapBuffer, ModuleList):\r
1574 sys.stdout.write ("Generate Load Module At Fix Address Map")\r
1575 sys.stdout.flush()\r
1576 PatchEfiImageList = []\r
1577 PeiModuleList = {}\r
1578 BtModuleList = {}\r
1579 RtModuleList = {}\r
1580 SmmModuleList = {}\r
1581 PeiSize = 0\r
1582 BtSize = 0\r
1583 RtSize = 0\r
1584 # reserve 4K size in SMRAM to make SMM module address not from 0.\r
1585 SmmSize = 0x1000\r
1586 for ModuleGuid in ModuleList:\r
1587 Module = ModuleList[ModuleGuid]\r
1588 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (Module.MetaFile, Module.Arch, Module.ToolChain, Module.BuildTarget)\r
1589\r
1590 OutputImageFile = ''\r
1591 for ResultFile in Module.CodaTargetList:\r
1592 if str(ResultFile.Target).endswith('.efi'):\r
1593 #\r
1594 # module list for PEI, DXE, RUNTIME and SMM\r
1595 #\r
1596 OutputImageFile = os.path.join(Module.OutputDir, Module.Name + '.efi')\r
1597 ImageClass = PeImageClass (OutputImageFile)\r
1598 if not ImageClass.IsValid:\r
1599 EdkLogger.error("build", FILE_PARSE_FAILURE, ExtraData=ImageClass.ErrorInfo)\r
1600 ImageInfo = PeImageInfo(Module.Name, Module.Guid, Module.Arch, Module.OutputDir, Module.DebugDir, ImageClass)\r
1601 if Module.ModuleType in [SUP_MODULE_PEI_CORE, SUP_MODULE_PEIM, EDK_COMPONENT_TYPE_COMBINED_PEIM_DRIVER, EDK_COMPONENT_TYPE_PIC_PEIM, EDK_COMPONENT_TYPE_RELOCATABLE_PEIM, SUP_MODULE_DXE_CORE]:\r
1602 PeiModuleList[Module.MetaFile] = ImageInfo\r
1603 PeiSize += ImageInfo.Image.Size\r
1604 elif Module.ModuleType in [EDK_COMPONENT_TYPE_BS_DRIVER, SUP_MODULE_DXE_DRIVER, SUP_MODULE_UEFI_DRIVER]:\r
1605 BtModuleList[Module.MetaFile] = ImageInfo\r
1606 BtSize += ImageInfo.Image.Size\r
1607 elif Module.ModuleType in [SUP_MODULE_DXE_RUNTIME_DRIVER, EDK_COMPONENT_TYPE_RT_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, EDK_COMPONENT_TYPE_SAL_RT_DRIVER]:\r
1608 RtModuleList[Module.MetaFile] = ImageInfo\r
1609 RtSize += ImageInfo.Image.Size\r
1610 elif Module.ModuleType in [SUP_MODULE_SMM_CORE, SUP_MODULE_DXE_SMM_DRIVER, SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE]:\r
1611 SmmModuleList[Module.MetaFile] = ImageInfo\r
1612 SmmSize += ImageInfo.Image.Size\r
1613 if Module.ModuleType == SUP_MODULE_DXE_SMM_DRIVER:\r
1614 PiSpecVersion = Module.Module.Specification.get('PI_SPECIFICATION_VERSION', '0x00000000')\r
1615 # for PI specification < PI1.1, DXE_SMM_DRIVER also runs as BOOT time driver.\r
1616 if int(PiSpecVersion, 16) < 0x0001000A:\r
1617 BtModuleList[Module.MetaFile] = ImageInfo\r
1618 BtSize += ImageInfo.Image.Size\r
1619 break\r
1620 #\r
1621 # EFI image is final target.\r
1622 # Check EFI image contains patchable FixAddress related PCDs.\r
1623 #\r
1624 if OutputImageFile != '':\r
1625 ModuleIsPatch = False\r
1626 for Pcd in Module.ModulePcdList:\r
1627 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SET:\r
1628 ModuleIsPatch = True\r
1629 break\r
1630 if not ModuleIsPatch:\r
1631 for Pcd in Module.LibraryPcdList:\r
1632 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SET:\r
1633 ModuleIsPatch = True\r
1634 break\r
1635\r
1636 if not ModuleIsPatch:\r
1637 continue\r
1638 #\r
1639 # Module includes the patchable load fix address PCDs.\r
1640 # It will be fixed up later.\r
1641 #\r
1642 PatchEfiImageList.append (OutputImageFile)\r
1643\r
1644 #\r
1645 # Get Top Memory address\r
1646 #\r
1647 ReservedRuntimeMemorySize = 0\r
1648 TopMemoryAddress = 0\r
1649 if self.LoadFixAddress == 0xFFFFFFFFFFFFFFFF:\r
1650 TopMemoryAddress = 0\r
1651 else:\r
1652 TopMemoryAddress = self.LoadFixAddress\r
1653 if TopMemoryAddress < RtSize + BtSize + PeiSize:\r
1654 EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS is too low to load driver")\r
1655\r
1656 #\r
1657 # Patch FixAddress related PCDs into EFI image\r
1658 #\r
1659 for EfiImage in PatchEfiImageList:\r
1660 EfiImageMap = EfiImage.replace('.efi', '.map')\r
1661 if not os.path.exists(EfiImageMap):\r
1662 continue\r
1663 #\r
1664 # Get PCD offset in EFI image by GenPatchPcdTable function\r
1665 #\r
1666 PcdTable = parsePcdInfoFromMapFile(EfiImageMap, EfiImage)\r
1667 #\r
1668 # Patch real PCD value by PatchPcdValue tool\r
1669 #\r
1670 for PcdInfo in PcdTable:\r
1671 ReturnValue = 0\r
1672 if PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE:\r
1673 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE, str (PeiSize // 0x1000))\r
1674 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE:\r
1675 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE_DATA_TYPE, str (BtSize // 0x1000))\r
1676 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE:\r
1677 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE_DATA_TYPE, str (RtSize // 0x1000))\r
1678 elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE and len (SmmModuleList) > 0:\r
1679 ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE_DATA_TYPE, str (SmmSize // 0x1000))\r
1680 if ReturnValue != 0:\r
1681 EdkLogger.error("build", PARAMETER_INVALID, "Patch PCD value failed", ExtraData=ErrorInfo)\r
1682\r
1683 MapBuffer.append('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize // 0x1000))\r
1684 MapBuffer.append('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize // 0x1000))\r
1685 MapBuffer.append('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize // 0x1000))\r
1686 if len (SmmModuleList) > 0:\r
1687 MapBuffer.append('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize // 0x1000))\r
1688\r
1689 PeiBaseAddr = TopMemoryAddress - RtSize - BtSize\r
1690 BtBaseAddr = TopMemoryAddress - RtSize\r
1691 RtBaseAddr = TopMemoryAddress - ReservedRuntimeMemorySize\r
1692\r
1693 self._RebaseModule (MapBuffer, PeiBaseAddr, PeiModuleList, TopMemoryAddress == 0)\r
1694 self._RebaseModule (MapBuffer, BtBaseAddr, BtModuleList, TopMemoryAddress == 0)\r
1695 self._RebaseModule (MapBuffer, RtBaseAddr, RtModuleList, TopMemoryAddress == 0)\r
1696 self._RebaseModule (MapBuffer, 0x1000, SmmModuleList, AddrIsOffset=False, ModeIsSmm=True)\r
1697 MapBuffer.append('\n\n')\r
1698 sys.stdout.write ("\n")\r
1699 sys.stdout.flush()\r
1700\r
1701 ## Save platform Map file\r
1702 #\r
1703 def _SaveMapFile (self, MapBuffer, Wa):\r
1704 #\r
1705 # Map file path is got.\r
1706 #\r
1707 MapFilePath = os.path.join(Wa.BuildDir, Wa.Name + '.map')\r
1708 #\r
1709 # Save address map into MAP file.\r
1710 #\r
1711 SaveFileOnChange(MapFilePath, ''.join(MapBuffer), False)\r
1712 if self.LoadFixAddress != 0:\r
1713 sys.stdout.write ("\nLoad Module At Fix Address Map file can be found at %s\n" % (MapFilePath))\r
1714 sys.stdout.flush()\r
1715\r
1716 ## Build active platform for different build targets and different tool chains\r
1717 #\r
1718 def _BuildPlatform(self):\r
1719 SaveFileOnChange(self.PlatformBuildPath, '# DO NOT EDIT \n# FILE auto-generated\n', False)\r
1720 for BuildTarget in self.BuildTargetList:\r
1721 GlobalData.gGlobalDefines['TARGET'] = BuildTarget\r
1722 index = 0\r
1723 for ToolChain in self.ToolChainList:\r
1724 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain\r
1725 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain\r
1726 GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index]\r
1727 index += 1\r
1728 Wa = WorkspaceAutoGen(\r
1729 self.WorkspaceDir,\r
1730 self.PlatformFile,\r
1731 BuildTarget,\r
1732 ToolChain,\r
1733 self.ArchList,\r
1734 self.BuildDatabase,\r
1735 self.TargetTxt,\r
1736 self.ToolDef,\r
1737 self.Fdf,\r
1738 self.FdList,\r
1739 self.FvList,\r
1740 self.CapList,\r
1741 self.SkuId,\r
1742 self.UniFlag,\r
1743 self.Progress\r
1744 )\r
1745 self.Fdf = Wa.FdfFile\r
1746 self.LoadFixAddress = Wa.Platform.LoadFixAddress\r
1747 self.BuildReport.AddPlatformReport(Wa)\r
1748 self.Progress.Stop("done!")\r
1749\r
1750 # Add ffs build to makefile\r
1751 CmdListDict = {}\r
1752 if GlobalData.gEnableGenfdsMultiThread and self.Fdf:\r
1753 CmdListDict = self._GenFfsCmd(Wa.ArchList)\r
1754\r
1755 for Arch in Wa.ArchList:\r
1756 PcdMaList = []\r
1757 GlobalData.gGlobalDefines['ARCH'] = Arch\r
1758 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)\r
1759 for Module in Pa.Platform.Modules:\r
1760 # Get ModuleAutoGen object to generate C code file and makefile\r
1761 Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe)\r
1762 if Ma is None:\r
1763 continue\r
1764 if Ma.PcdIsDriver:\r
1765 Ma.PlatformInfo = Pa\r
1766 Ma.Workspace = Wa\r
1767 PcdMaList.append(Ma)\r
1768 self.BuildModules.append(Ma)\r
1769 Pa.DataPipe.DataContainer = {"FfsCommand":CmdListDict}\r
1770 Pa.DataPipe.DataContainer = {"Workspace_timestamp": Wa._SrcTimeStamp}\r
1771 self._BuildPa(self.Target, Pa, FfsCommand=CmdListDict,PcdMaList=PcdMaList)\r
1772\r
1773 # Create MAP file when Load Fix Address is enabled.\r
1774 if self.Target in ["", "all", "fds"]:\r
1775 for Arch in Wa.ArchList:\r
1776 GlobalData.gGlobalDefines['ARCH'] = Arch\r
1777 #\r
1778 # Check whether the set fix address is above 4G for 32bit image.\r
1779 #\r
1780 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:\r
1781 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
1782 #\r
1783 # Get Module List\r
1784 #\r
1785 ModuleList = {}\r
1786 for Pa in Wa.AutoGenObjectList:\r
1787 for Ma in Pa.ModuleAutoGenList:\r
1788 if Ma is None:\r
1789 continue\r
1790 if not Ma.IsLibrary:\r
1791 ModuleList[Ma.Guid.upper()] = Ma\r
1792\r
1793 MapBuffer = []\r
1794 if self.LoadFixAddress != 0:\r
1795 #\r
1796 # Rebase module to the preferred memory address before GenFds\r
1797 #\r
1798 self._CollectModuleMapBuffer(MapBuffer, ModuleList)\r
1799 if self.Fdf:\r
1800 #\r
1801 # create FDS again for the updated EFI image\r
1802 #\r
1803 self._Build("fds", Wa)\r
1804 #\r
1805 # Create MAP file for all platform FVs after GenFds.\r
1806 #\r
1807 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)\r
1808 #\r
1809 # Save MAP buffer into MAP file.\r
1810 #\r
1811 self._SaveMapFile (MapBuffer, Wa)\r
1812 self.CreateGuidedSectionToolsFile(Wa)\r
1813\r
1814 ## Build active module for different build targets, different tool chains and different archs\r
1815 #\r
1816 def _BuildModule(self):\r
1817 for BuildTarget in self.BuildTargetList:\r
1818 GlobalData.gGlobalDefines['TARGET'] = BuildTarget\r
1819 index = 0\r
1820 for ToolChain in self.ToolChainList:\r
1821 WorkspaceAutoGenTime = time.time()\r
1822 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain\r
1823 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain\r
1824 GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index]\r
1825 index += 1\r
1826 #\r
1827 # module build needs platform build information, so get platform\r
1828 # AutoGen first\r
1829 #\r
1830 Wa = WorkspaceAutoGen(\r
1831 self.WorkspaceDir,\r
1832 self.PlatformFile,\r
1833 BuildTarget,\r
1834 ToolChain,\r
1835 self.ArchList,\r
1836 self.BuildDatabase,\r
1837 self.TargetTxt,\r
1838 self.ToolDef,\r
1839 self.Fdf,\r
1840 self.FdList,\r
1841 self.FvList,\r
1842 self.CapList,\r
1843 self.SkuId,\r
1844 self.UniFlag,\r
1845 self.Progress,\r
1846 self.ModuleFile\r
1847 )\r
1848 self.Fdf = Wa.FdfFile\r
1849 self.LoadFixAddress = Wa.Platform.LoadFixAddress\r
1850 Wa.CreateMakeFile(False)\r
1851 # Add ffs build to makefile\r
1852 CmdListDict = None\r
1853 if GlobalData.gEnableGenfdsMultiThread and self.Fdf:\r
1854 CmdListDict = self._GenFfsCmd(Wa.ArchList)\r
1855\r
1856 GlobalData.file_lock = mp.Lock()\r
1857 GlobalData.FfsCmd = CmdListDict\r
1858\r
1859 self.Progress.Stop("done!")\r
1860 MaList = []\r
1861 ExitFlag = threading.Event()\r
1862 ExitFlag.clear()\r
1863 self.AutoGenTime += int(round((time.time() - WorkspaceAutoGenTime)))\r
1864 for Arch in Wa.ArchList:\r
1865 AutoGenStart = time.time()\r
1866 GlobalData.gGlobalDefines['ARCH'] = Arch\r
1867 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)\r
1868 for Module in Pa.Platform.Modules:\r
1869 if self.ModuleFile.Dir == Module.Dir and self.ModuleFile.Name == Module.Name:\r
1870 Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe)\r
1871 if Ma is None:\r
1872 continue\r
1873 if Ma.PcdIsDriver:\r
1874 Ma.PlatformInfo = Pa\r
1875 Ma.Workspace = Wa\r
1876 MaList.append(Ma)\r
1877\r
1878 if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and self.Target in [None, "", "all"]:\r
1879 if Ma.CanSkipbyPreMakeCache():\r
1880 continue\r
1881 else:\r
1882 self.PreMakeCacheMiss.add(Ma)\r
1883\r
1884 # Not to auto-gen for targets 'clean', 'cleanlib', 'cleanall', 'run', 'fds'\r
1885 if self.Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']:\r
1886 # for target which must generate AutoGen code and makefile\r
1887 if not self.SkipAutoGen or self.Target == 'genc':\r
1888 self.Progress.Start("Generating code")\r
1889 Ma.CreateCodeFile(True)\r
1890 self.Progress.Stop("done!")\r
1891 if self.Target == "genc":\r
1892 return True\r
1893 if not self.SkipAutoGen or self.Target == 'genmake':\r
1894 self.Progress.Start("Generating makefile")\r
1895 if CmdListDict and self.Fdf and (Module.Path, Arch) in CmdListDict:\r
1896 Ma.CreateMakeFile(True, CmdListDict[Module.Path, Arch])\r
1897 del CmdListDict[Module.Path, Arch]\r
1898 else:\r
1899 Ma.CreateMakeFile(True)\r
1900 self.Progress.Stop("done!")\r
1901 if self.Target == "genmake":\r
1902 return True\r
1903\r
1904 if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]:\r
1905 if Ma.CanSkipbyMakeCache():\r
1906 continue\r
1907 else:\r
1908 self.MakeCacheMiss.add(Ma)\r
1909\r
1910 self.BuildModules.append(Ma)\r
1911 self.AutoGenTime += int(round((time.time() - AutoGenStart)))\r
1912 MakeStart = time.time()\r
1913 for Ma in self.BuildModules:\r
1914 if not Ma.IsBinaryModule:\r
1915 Bt = BuildTask.New(ModuleMakeUnit(Ma, Pa.BuildCommand,self.Target))\r
1916 # Break build if any build thread has error\r
1917 if BuildTask.HasError():\r
1918 # we need a full version of makefile for platform\r
1919 ExitFlag.set()\r
1920 BuildTask.WaitForComplete()\r
1921 Pa.CreateMakeFile(False)\r
1922 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)\r
1923 # Start task scheduler\r
1924 if not BuildTask.IsOnGoing():\r
1925 BuildTask.StartScheduler(self.ThreadNumber, ExitFlag)\r
1926\r
1927 # in case there's an interruption. we need a full version of makefile for platform\r
1928 Pa.CreateMakeFile(False)\r
1929 if BuildTask.HasError():\r
1930 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)\r
1931 self.MakeTime += int(round((time.time() - MakeStart)))\r
1932\r
1933 MakeContiue = time.time()\r
1934 ExitFlag.set()\r
1935 BuildTask.WaitForComplete()\r
1936 self.CreateAsBuiltInf()\r
1937 if GlobalData.gBinCacheDest:\r
1938 self.GenDestCache()\r
1939 elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource:\r
1940 # Only for --hash\r
1941 # Update PreMakeCacheChain files\r
1942 self.GenLocalPreMakeCache()\r
1943 self.BuildModules = []\r
1944 self.MakeTime += int(round((time.time() - MakeContiue)))\r
1945 if BuildTask.HasError():\r
1946 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)\r
1947\r
1948 self.BuildReport.AddPlatformReport(Wa, MaList)\r
1949 if MaList == []:\r
1950 EdkLogger.error(\r
1951 'build',\r
1952 BUILD_ERROR,\r
1953 "Module for [%s] is not a component of active platform."\\r
1954 " Please make sure that the ARCH and inf file path are"\\r
1955 " given in the same as in [%s]" % \\r
1956 (', '.join(Wa.ArchList), self.PlatformFile),\r
1957 ExtraData=self.ModuleFile\r
1958 )\r
1959 # Create MAP file when Load Fix Address is enabled.\r
1960 if self.Target == "fds" and self.Fdf:\r
1961 for Arch in Wa.ArchList:\r
1962 #\r
1963 # Check whether the set fix address is above 4G for 32bit image.\r
1964 #\r
1965 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:\r
1966 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
1967 #\r
1968 # Get Module List\r
1969 #\r
1970 ModuleList = {}\r
1971 for Pa in Wa.AutoGenObjectList:\r
1972 for Ma in Pa.ModuleAutoGenList:\r
1973 if Ma is None:\r
1974 continue\r
1975 if not Ma.IsLibrary:\r
1976 ModuleList[Ma.Guid.upper()] = Ma\r
1977\r
1978 MapBuffer = []\r
1979 if self.LoadFixAddress != 0:\r
1980 #\r
1981 # Rebase module to the preferred memory address before GenFds\r
1982 #\r
1983 self._CollectModuleMapBuffer(MapBuffer, ModuleList)\r
1984 #\r
1985 # create FDS again for the updated EFI image\r
1986 #\r
1987 GenFdsStart = time.time()\r
1988 self._Build("fds", Wa)\r
1989 self.GenFdsTime += int(round((time.time() - GenFdsStart)))\r
1990 #\r
1991 # Create MAP file for all platform FVs after GenFds.\r
1992 #\r
1993 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)\r
1994 #\r
1995 # Save MAP buffer into MAP file.\r
1996 #\r
1997 self._SaveMapFile (MapBuffer, Wa)\r
1998\r
1999 def _GenFfsCmd(self,ArchList):\r
2000 # convert dictionary of Cmd:(Inf,Arch)\r
2001 # to a new dictionary of (Inf,Arch):Cmd,Cmd,Cmd...\r
2002 CmdSetDict = defaultdict(set)\r
2003 GenFfsDict = GenFds.GenFfsMakefile('', GlobalData.gFdfParser, self, ArchList, GlobalData)\r
2004 for Cmd in GenFfsDict:\r
2005 tmpInf, tmpArch = GenFfsDict[Cmd]\r
2006 CmdSetDict[tmpInf, tmpArch].add(Cmd)\r
2007 return CmdSetDict\r
2008 def VerifyAutoGenFiles(self):\r
2009 AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt")\r
2010 try:\r
2011 with open(AutoGenIdFile) as fd:\r
2012 lines = fd.readlines()\r
2013 except:\r
2014 return None\r
2015 for line in lines:\r
2016 if "Arch" in line:\r
2017 ArchList = line.strip().split("=")[1].split("|")\r
2018 if "BuildDir" in line:\r
2019 BuildDir = line.split("=")[1].strip()\r
2020 if "PlatformGuid" in line:\r
2021 PlatformGuid = line.split("=")[1].strip()\r
2022 GlobalVarList = []\r
2023 for arch in ArchList:\r
2024 global_var = os.path.join(BuildDir, "GlobalVar_%s_%s.bin" % (str(PlatformGuid),arch))\r
2025 if not os.path.exists(global_var):\r
2026 return None\r
2027 GlobalVarList.append(global_var)\r
2028 for global_var in GlobalVarList:\r
2029 data_pipe = MemoryDataPipe()\r
2030 data_pipe.load(global_var)\r
2031 target = data_pipe.Get("P_Info").get("Target")\r
2032 toolchain = data_pipe.Get("P_Info").get("ToolChain")\r
2033 archlist = data_pipe.Get("P_Info").get("ArchList")\r
2034 Arch = data_pipe.Get("P_Info").get("Arch")\r
2035 active_p = data_pipe.Get("P_Info").get("ActivePlatform")\r
2036 workspacedir = data_pipe.Get("P_Info").get("WorkspaceDir")\r
2037 PackagesPath = os.getenv("PACKAGES_PATH")\r
2038 mws.setWs(workspacedir, PackagesPath)\r
2039 LibraryBuildDirectoryList = data_pipe.Get("LibraryBuildDirectoryList")\r
2040 ModuleBuildDirectoryList = data_pipe.Get("ModuleBuildDirectoryList")\r
2041\r
2042 for m_build_dir in LibraryBuildDirectoryList:\r
2043 if not os.path.exists(os.path.join(m_build_dir,self.MakeFileName)):\r
2044 return None\r
2045 for m_build_dir in ModuleBuildDirectoryList:\r
2046 if not os.path.exists(os.path.join(m_build_dir,self.MakeFileName)):\r
2047 return None\r
2048 Wa = WorkSpaceInfo(\r
2049 workspacedir,active_p,target,toolchain,archlist\r
2050 )\r
2051 Pa = PlatformInfo(Wa, active_p, target, toolchain, Arch,data_pipe)\r
2052 Wa.AutoGenObjectList.append(Pa)\r
2053 return Wa\r
2054 def SetupMakeSetting(self,Wa):\r
2055 BuildModules = []\r
2056 for Pa in Wa.AutoGenObjectList:\r
2057 for m in Pa._MbList:\r
2058 ma = ModuleAutoGen(Wa,m.MetaFile, Pa.BuildTarget, Wa.ToolChain, Pa.Arch, Pa.MetaFile,Pa.DataPipe)\r
2059 BuildModules.append(ma)\r
2060 fdf_file = Wa.FlashDefinition\r
2061 if fdf_file:\r
2062 Fdf = FdfParser(fdf_file.Path)\r
2063 Fdf.ParseFile()\r
2064 GlobalData.gFdfParser = Fdf\r
2065 if Fdf.CurrentFdName and Fdf.CurrentFdName in Fdf.Profile.FdDict:\r
2066 FdDict = Fdf.Profile.FdDict[Fdf.CurrentFdName]\r
2067 for FdRegion in FdDict.RegionList:\r
2068 if str(FdRegion.RegionType) == 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList):\r
2069 if int(FdRegion.Offset) % 8 != 0:\r
2070 EdkLogger.error("build", FORMAT_INVALID, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion.Offset))\r
2071 Wa.FdfProfile = Fdf.Profile\r
2072 self.Fdf = Fdf\r
2073 else:\r
2074 self.Fdf = None\r
2075 return BuildModules\r
2076\r
2077 ## Build a platform in multi-thread mode\r
2078 #\r
2079 def PerformAutoGen(self,BuildTarget,ToolChain):\r
2080 WorkspaceAutoGenTime = time.time()\r
2081 Wa = WorkspaceAutoGen(\r
2082 self.WorkspaceDir,\r
2083 self.PlatformFile,\r
2084 BuildTarget,\r
2085 ToolChain,\r
2086 self.ArchList,\r
2087 self.BuildDatabase,\r
2088 self.TargetTxt,\r
2089 self.ToolDef,\r
2090 self.Fdf,\r
2091 self.FdList,\r
2092 self.FvList,\r
2093 self.CapList,\r
2094 self.SkuId,\r
2095 self.UniFlag,\r
2096 self.Progress\r
2097 )\r
2098 self.Fdf = Wa.FdfFile\r
2099 self.LoadFixAddress = Wa.Platform.LoadFixAddress\r
2100 self.BuildReport.AddPlatformReport(Wa)\r
2101 Wa.CreateMakeFile(False)\r
2102\r
2103 # Add ffs build to makefile\r
2104 CmdListDict = {}\r
2105 if GlobalData.gEnableGenfdsMultiThread and self.Fdf:\r
2106 CmdListDict = self._GenFfsCmd(Wa.ArchList)\r
2107\r
2108 self.AutoGenTime += int(round((time.time() - WorkspaceAutoGenTime)))\r
2109 BuildModules = []\r
2110 for Arch in Wa.ArchList:\r
2111 PcdMaList = []\r
2112 AutoGenStart = time.time()\r
2113 GlobalData.gGlobalDefines['ARCH'] = Arch\r
2114 Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch)\r
2115 if Pa is None:\r
2116 continue\r
2117 ModuleList = []\r
2118 for Inf in Pa.Platform.Modules:\r
2119 ModuleList.append(Inf)\r
2120 # Add the INF only list in FDF\r
2121 if GlobalData.gFdfParser is not None:\r
2122 for InfName in GlobalData.gFdfParser.Profile.InfList:\r
2123 Inf = PathClass(NormPath(InfName), self.WorkspaceDir, Arch)\r
2124 if Inf in Pa.Platform.Modules:\r
2125 continue\r
2126 ModuleList.append(Inf)\r
2127 Pa.DataPipe.DataContainer = {"FfsCommand":CmdListDict}\r
2128 Pa.DataPipe.DataContainer = {"Workspace_timestamp": Wa._SrcTimeStamp}\r
2129 Pa.DataPipe.DataContainer = {"CommandTarget": self.Target}\r
2130 Pa.CreateLibModuelDirs()\r
2131 # Fetch the MakeFileName.\r
2132 self.MakeFileName = Pa.MakeFileName\r
2133 if not self.MakeFileName:\r
2134 self.MakeFileName = Pa.MakeFile\r
2135\r
2136 Pa.DataPipe.DataContainer = {"LibraryBuildDirectoryList":Pa.LibraryBuildDirectoryList}\r
2137 Pa.DataPipe.DataContainer = {"ModuleBuildDirectoryList":Pa.ModuleBuildDirectoryList}\r
2138 Pa.DataPipe.DataContainer = {"FdsCommandDict": Wa.GenFdsCommandDict}\r
2139 # Prepare the cache share data for multiprocessing\r
2140 Pa.DataPipe.DataContainer = {"gPlatformHashFile":GlobalData.gPlatformHashFile}\r
2141 ModuleCodaFile = {}\r
2142 for ma in Pa.ModuleAutoGenList:\r
2143 ModuleCodaFile[(ma.MetaFile.File,ma.MetaFile.Root,ma.Arch,ma.MetaFile.Path)] = [item.Target for item in ma.CodaTargetList]\r
2144 Pa.DataPipe.DataContainer = {"ModuleCodaFile":ModuleCodaFile}\r
2145 # ModuleList contains all driver modules only\r
2146 for Module in ModuleList:\r
2147 # Get ModuleAutoGen object to generate C code file and makefile\r
2148 Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe)\r
2149 if Ma is None:\r
2150 continue\r
2151 if Ma.PcdIsDriver:\r
2152 Ma.PlatformInfo = Pa\r
2153 Ma.Workspace = Wa\r
2154 PcdMaList.append(Ma)\r
2155 self.AllDrivers.add(Ma)\r
2156 self.AllModules.add(Ma)\r
2157\r
2158 mqueue = mp.Queue()\r
2159 cqueue = mp.Queue()\r
2160 for m in Pa.GetAllModuleInfo:\r
2161 mqueue.put(m)\r
2162 module_file,module_root,module_path,module_basename,\\r
2163 module_originalpath,module_arch,IsLib = m\r
2164 Ma = ModuleAutoGen(Wa, PathClass(module_path, Wa), BuildTarget,\\r
2165 ToolChain, Arch, self.PlatformFile,Pa.DataPipe)\r
2166 self.AllModules.add(Ma)\r
2167 data_pipe_file = os.path.join(Pa.BuildDir, "GlobalVar_%s_%s.bin" % (str(Pa.Guid),Pa.Arch))\r
2168 Pa.DataPipe.dump(data_pipe_file)\r
2169\r
2170 autogen_rt, errorcode = self.StartAutoGen(mqueue, Pa.DataPipe, self.SkipAutoGen, PcdMaList, cqueue)\r
2171\r
2172 if not autogen_rt:\r
2173 self.AutoGenMgr.TerminateWorkers()\r
2174 self.AutoGenMgr.join(1)\r
2175 raise FatalError(errorcode)\r
2176\r
2177 if GlobalData.gUseHashCache:\r
2178 for item in GlobalData.gModuleAllCacheStatus:\r
2179 (MetaFilePath, Arch, CacheStr, Status) = item\r
2180 Ma = ModuleAutoGen(Wa, PathClass(MetaFilePath, Wa), BuildTarget,\\r
2181 ToolChain, Arch, self.PlatformFile,Pa.DataPipe)\r
2182 if CacheStr == "PreMakeCache" and Status == False:\r
2183 self.PreMakeCacheMiss.add(Ma)\r
2184 if CacheStr == "PreMakeCache" and Status == True:\r
2185 self.PreMakeCacheHit.add(Ma)\r
2186 GlobalData.gModuleCacheHit.add(Ma)\r
2187 if CacheStr == "MakeCache" and Status == False:\r
2188 self.MakeCacheMiss.add(Ma)\r
2189 if CacheStr == "MakeCache" and Status == True:\r
2190 self.MakeCacheHit.add(Ma)\r
2191 GlobalData.gModuleCacheHit.add(Ma)\r
2192 self.AutoGenTime += int(round((time.time() - AutoGenStart)))\r
2193 AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt")\r
2194 with open(AutoGenIdFile,"w") as fw:\r
2195 fw.write("Arch=%s\n" % "|".join((Wa.ArchList)))\r
2196 fw.write("BuildDir=%s\n" % Wa.BuildDir)\r
2197 fw.write("PlatformGuid=%s\n" % str(Wa.AutoGenObjectList[0].Guid))\r
2198\r
2199 if GlobalData.gBinCacheSource:\r
2200 BuildModules.extend(self.MakeCacheMiss)\r
2201 elif GlobalData.gUseHashCache and not GlobalData.gBinCacheDest:\r
2202 BuildModules.extend(self.PreMakeCacheMiss)\r
2203 else:\r
2204 BuildModules.extend(self.AllDrivers)\r
2205\r
2206 self.Progress.Stop("done!")\r
2207 return Wa, BuildModules\r
2208\r
2209 def _MultiThreadBuildPlatform(self):\r
2210 SaveFileOnChange(self.PlatformBuildPath, '# DO NOT EDIT \n# FILE auto-generated\n', False)\r
2211 for BuildTarget in self.BuildTargetList:\r
2212 GlobalData.gGlobalDefines['TARGET'] = BuildTarget\r
2213 index = 0\r
2214 for ToolChain in self.ToolChainList:\r
2215 resetFdsGlobalVariable()\r
2216 GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain\r
2217 GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain\r
2218 GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index]\r
2219 index += 1\r
2220 ExitFlag = threading.Event()\r
2221 ExitFlag.clear()\r
2222 if self.SkipAutoGen:\r
2223 Wa = self.VerifyAutoGenFiles()\r
2224 if Wa is None:\r
2225 self.SkipAutoGen = False\r
2226 Wa, self.BuildModules = self.PerformAutoGen(BuildTarget,ToolChain)\r
2227 else:\r
2228 GlobalData.gAutoGenPhase = True\r
2229 self.BuildModules = self.SetupMakeSetting(Wa)\r
2230 else:\r
2231 Wa, self.BuildModules = self.PerformAutoGen(BuildTarget,ToolChain)\r
2232 Pa = Wa.AutoGenObjectList[0]\r
2233 GlobalData.gAutoGenPhase = False\r
2234\r
2235 if GlobalData.gBinCacheSource:\r
2236 EdkLogger.quiet("[cache Summary]: Total module num: %s" % len(self.AllModules))\r
2237 EdkLogger.quiet("[cache Summary]: PreMakecache miss num: %s " % len(self.PreMakeCacheMiss))\r
2238 EdkLogger.quiet("[cache Summary]: Makecache miss num: %s " % len(self.MakeCacheMiss))\r
2239\r
2240 for Arch in Wa.ArchList:\r
2241 MakeStart = time.time()\r
2242 for Ma in set(self.BuildModules):\r
2243 # Generate build task for the module\r
2244 if not Ma.IsBinaryModule:\r
2245 Bt = BuildTask.New(ModuleMakeUnit(Ma, Pa.BuildCommand,self.Target))\r
2246 # Break build if any build thread has error\r
2247 if BuildTask.HasError():\r
2248 # we need a full version of makefile for platform\r
2249 ExitFlag.set()\r
2250 BuildTask.WaitForComplete()\r
2251 Pa.CreateMakeFile(False)\r
2252 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)\r
2253 # Start task scheduler\r
2254 if not BuildTask.IsOnGoing():\r
2255 BuildTask.StartScheduler(self.ThreadNumber, ExitFlag)\r
2256\r
2257 # in case there's an interruption. we need a full version of makefile for platform\r
2258\r
2259 if BuildTask.HasError():\r
2260 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)\r
2261 self.MakeTime += int(round((time.time() - MakeStart)))\r
2262\r
2263 MakeContiue = time.time()\r
2264 #\r
2265 #\r
2266 # All modules have been put in build tasks queue. Tell task scheduler\r
2267 # to exit if all tasks are completed\r
2268 #\r
2269 ExitFlag.set()\r
2270 BuildTask.WaitForComplete()\r
2271 self.CreateAsBuiltInf()\r
2272 if GlobalData.gBinCacheDest:\r
2273 self.GenDestCache()\r
2274 elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource:\r
2275 # Only for --hash\r
2276 # Update PreMakeCacheChain files\r
2277 self.GenLocalPreMakeCache()\r
2278 #\r
2279 # Get Module List\r
2280 #\r
2281 ModuleList = {ma.Guid.upper(): ma for ma in self.BuildModules}\r
2282 self.BuildModules = []\r
2283 self.MakeTime += int(round((time.time() - MakeContiue)))\r
2284 #\r
2285 # Check for build error, and raise exception if one\r
2286 # has been signaled.\r
2287 #\r
2288 if BuildTask.HasError():\r
2289 EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)\r
2290\r
2291 # Create MAP file when Load Fix Address is enabled.\r
2292 if self.Target in ["", "all", "fds"]:\r
2293 for Arch in Wa.ArchList:\r
2294 #\r
2295 # Check whether the set fix address is above 4G for 32bit image.\r
2296 #\r
2297 if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000:\r
2298 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
2299\r
2300 #\r
2301 # Rebase module to the preferred memory address before GenFds\r
2302 #\r
2303 MapBuffer = []\r
2304 if self.LoadFixAddress != 0:\r
2305 self._CollectModuleMapBuffer(MapBuffer, ModuleList)\r
2306\r
2307 if self.Fdf:\r
2308 #\r
2309 # Generate FD image if there's a FDF file found\r
2310 #\r
2311 GenFdsStart = time.time()\r
2312 if GenFdsApi(Wa.GenFdsCommandDict, self.Db):\r
2313 EdkLogger.error("build", COMMAND_FAILURE)\r
2314\r
2315 #\r
2316 # Create MAP file for all platform FVs after GenFds.\r
2317 #\r
2318 self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList)\r
2319 self.GenFdsTime += int(round((time.time() - GenFdsStart)))\r
2320 #\r
2321 # Save MAP buffer into MAP file.\r
2322 #\r
2323 self._SaveMapFile(MapBuffer, Wa)\r
2324 self.CreateGuidedSectionToolsFile(Wa)\r
2325 ## Generate GuidedSectionTools.txt in the FV directories.\r
2326 #\r
2327 def CreateGuidedSectionToolsFile(self,Wa):\r
2328 for BuildTarget in self.BuildTargetList:\r
2329 for ToolChain in self.ToolChainList:\r
2330 FvDir = Wa.FvDir\r
2331 if not os.path.exists(FvDir):\r
2332 continue\r
2333\r
2334 for Arch in self.ArchList:\r
2335 # Build up the list of supported architectures for this build\r
2336 prefix = '%s_%s_%s_' % (BuildTarget, ToolChain, Arch)\r
2337\r
2338 # Look through the tool definitions for GUIDed tools\r
2339 guidAttribs = []\r
2340 for (attrib, value) in self.ToolDef.ToolsDefTxtDictionary.items():\r
2341 if attrib.upper().endswith('_GUID'):\r
2342 split = attrib.split('_')\r
2343 thisPrefix = '_'.join(split[0:3]) + '_'\r
2344 if thisPrefix == prefix:\r
2345 guid = self.ToolDef.ToolsDefTxtDictionary[attrib]\r
2346 guid = guid.lower()\r
2347 toolName = split[3]\r
2348 path = '_'.join(split[0:4]) + '_PATH'\r
2349 path = self.ToolDef.ToolsDefTxtDictionary[path]\r
2350 path = self.GetRealPathOfTool(path)\r
2351 guidAttribs.append((guid, toolName, path))\r
2352\r
2353 # Write out GuidedSecTools.txt\r
2354 toolsFile = os.path.join(FvDir, 'GuidedSectionTools.txt')\r
2355 toolsFile = open(toolsFile, 'wt')\r
2356 for guidedSectionTool in guidAttribs:\r
2357 print(' '.join(guidedSectionTool), file=toolsFile)\r
2358 toolsFile.close()\r
2359\r
2360 ## Returns the real path of the tool.\r
2361 #\r
2362 def GetRealPathOfTool (self, tool):\r
2363 if os.path.exists(tool):\r
2364 return os.path.realpath(tool)\r
2365 return tool\r
2366\r
2367 ## Launch the module or platform build\r
2368 #\r
2369 def Launch(self):\r
2370 self.AllDrivers = set()\r
2371 self.AllModules = set()\r
2372 self.PreMakeCacheMiss = set()\r
2373 self.PreMakeCacheHit = set()\r
2374 self.MakeCacheMiss = set()\r
2375 self.MakeCacheHit = set()\r
2376 if not self.ModuleFile:\r
2377 if not self.SpawnMode or self.Target not in ["", "all"]:\r
2378 self.SpawnMode = False\r
2379 self._BuildPlatform()\r
2380 else:\r
2381 self._MultiThreadBuildPlatform()\r
2382 else:\r
2383 self.SpawnMode = False\r
2384 self._BuildModule()\r
2385\r
2386 if self.Target == 'cleanall':\r
2387 RemoveDirectory(os.path.dirname(GlobalData.gDatabasePath), True)\r
2388\r
2389 def CreateAsBuiltInf(self):\r
2390 for Module in self.BuildModules:\r
2391 Module.CreateAsBuiltInf()\r
2392\r
2393 def GenDestCache(self):\r
2394 for Module in self.AllModules:\r
2395 Module.GenPreMakefileHashList()\r
2396 Module.GenMakefileHashList()\r
2397 Module.CopyModuleToCache()\r
2398\r
2399 def GenLocalPreMakeCache(self):\r
2400 for Module in self.PreMakeCacheMiss:\r
2401 Module.GenPreMakefileHashList()\r
2402\r
2403 ## Do some clean-up works when error occurred\r
2404 def Relinquish(self):\r
2405 OldLogLevel = EdkLogger.GetLevel()\r
2406 EdkLogger.SetLevel(EdkLogger.ERROR)\r
2407 Utils.Progressor.Abort()\r
2408 if self.SpawnMode == True:\r
2409 BuildTask.Abort()\r
2410 EdkLogger.SetLevel(OldLogLevel)\r
2411\r
2412def ParseDefines(DefineList=[]):\r
2413 DefineDict = {}\r
2414 if DefineList is not None:\r
2415 for Define in DefineList:\r
2416 DefineTokenList = Define.split("=", 1)\r
2417 if not GlobalData.gMacroNamePattern.match(DefineTokenList[0]):\r
2418 EdkLogger.error('build', FORMAT_INVALID,\r
2419 "The macro name must be in the pattern [A-Z][A-Z0-9_]*",\r
2420 ExtraData=DefineTokenList[0])\r
2421\r
2422 if len(DefineTokenList) == 1:\r
2423 DefineDict[DefineTokenList[0]] = "TRUE"\r
2424 else:\r
2425 DefineDict[DefineTokenList[0]] = DefineTokenList[1].strip()\r
2426 return DefineDict\r
2427\r
2428\r
2429\r
2430def LogBuildTime(Time):\r
2431 if Time:\r
2432 TimeDurStr = ''\r
2433 TimeDur = time.gmtime(Time)\r
2434 if TimeDur.tm_yday > 1:\r
2435 TimeDurStr = time.strftime("%H:%M:%S", TimeDur) + ", %d day(s)" % (TimeDur.tm_yday - 1)\r
2436 else:\r
2437 TimeDurStr = time.strftime("%H:%M:%S", TimeDur)\r
2438 return TimeDurStr\r
2439 else:\r
2440 return None\r
2441def ThreadNum():\r
2442 OptionParser = MyOptionParser()\r
2443 if not OptionParser.BuildOption and not OptionParser.BuildTarget:\r
2444 OptionParser.GetOption()\r
2445 BuildOption, BuildTarget = OptionParser.BuildOption, OptionParser.BuildTarget\r
2446 ThreadNumber = BuildOption.ThreadNumber\r
2447 GlobalData.gCmdConfDir = BuildOption.ConfDirectory\r
2448 if ThreadNumber is None:\r
2449 TargetObj = TargetTxtDict()\r
2450 ThreadNumber = TargetObj.Target.TargetTxtDictionary[TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER]\r
2451 if ThreadNumber == '':\r
2452 ThreadNumber = 0\r
2453 else:\r
2454 ThreadNumber = int(ThreadNumber, 0)\r
2455\r
2456 if ThreadNumber == 0:\r
2457 try:\r
2458 ThreadNumber = multiprocessing.cpu_count()\r
2459 except (ImportError, NotImplementedError):\r
2460 ThreadNumber = 1\r
2461 return ThreadNumber\r
2462## Tool entrance method\r
2463#\r
2464# This method mainly dispatch specific methods per the command line options.\r
2465# If no error found, return zero value so the caller of this tool can know\r
2466# if it's executed successfully or not.\r
2467#\r
2468# @retval 0 Tool was successful\r
2469# @retval 1 Tool failed\r
2470#\r
2471LogQMaxSize = ThreadNum() * 10\r
2472def Main():\r
2473 StartTime = time.time()\r
2474\r
2475 #\r
2476 # Create a log Queue\r
2477 #\r
2478 LogQ = mp.Queue(LogQMaxSize)\r
2479 # Initialize log system\r
2480 EdkLogger.LogClientInitialize(LogQ)\r
2481 GlobalData.gCommand = sys.argv[1:]\r
2482 #\r
2483 # Parse the options and args\r
2484 #\r
2485 OptionParser = MyOptionParser()\r
2486 if not OptionParser.BuildOption and not OptionParser.BuildTarget:\r
2487 OptionParser.GetOption()\r
2488 Option, Target = OptionParser.BuildOption, OptionParser.BuildTarget\r
2489 GlobalData.gOptions = Option\r
2490 GlobalData.gCaseInsensitive = Option.CaseInsensitive\r
2491\r
2492 # Set log level\r
2493 LogLevel = EdkLogger.INFO\r
2494 if Option.verbose is not None:\r
2495 EdkLogger.SetLevel(EdkLogger.VERBOSE)\r
2496 LogLevel = EdkLogger.VERBOSE\r
2497 elif Option.quiet is not None:\r
2498 EdkLogger.SetLevel(EdkLogger.QUIET)\r
2499 LogLevel = EdkLogger.QUIET\r
2500 elif Option.debug is not None:\r
2501 EdkLogger.SetLevel(Option.debug + 1)\r
2502 LogLevel = Option.debug + 1\r
2503 else:\r
2504 EdkLogger.SetLevel(EdkLogger.INFO)\r
2505\r
2506 if Option.WarningAsError == True:\r
2507 EdkLogger.SetWarningAsError()\r
2508 Log_Agent = LogAgent(LogQ,LogLevel,Option.LogFile)\r
2509 Log_Agent.start()\r
2510\r
2511 if platform.platform().find("Windows") >= 0:\r
2512 GlobalData.gIsWindows = True\r
2513 else:\r
2514 GlobalData.gIsWindows = False\r
2515\r
2516 EdkLogger.quiet("Build environment: %s" % platform.platform())\r
2517 EdkLogger.quiet(time.strftime("Build start time: %H:%M:%S, %b.%d %Y\n", time.localtime()));\r
2518 ReturnCode = 0\r
2519 MyBuild = None\r
2520 BuildError = True\r
2521 try:\r
2522 if len(Target) == 0:\r
2523 Target = "all"\r
2524 elif len(Target) >= 2:\r
2525 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "More than one targets are not supported.",\r
2526 ExtraData="Please select one of: %s" % (' '.join(gSupportedTarget)))\r
2527 else:\r
2528 Target = Target[0].lower()\r
2529\r
2530 if Target not in gSupportedTarget:\r
2531 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "Not supported target [%s]." % Target,\r
2532 ExtraData="Please select one of: %s" % (' '.join(gSupportedTarget)))\r
2533\r
2534 #\r
2535 # Check environment variable: EDK_TOOLS_PATH, WORKSPACE, PATH\r
2536 #\r
2537 CheckEnvVariable()\r
2538 GlobalData.gCommandLineDefines.update(ParseDefines(Option.Macros))\r
2539\r
2540 Workspace = os.getenv("WORKSPACE")\r
2541 #\r
2542 # Get files real name in workspace dir\r
2543 #\r
2544 GlobalData.gAllFiles = Utils.DirCache(Workspace)\r
2545\r
2546 WorkingDirectory = os.getcwd()\r
2547 if not Option.ModuleFile:\r
2548 FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.inf')))\r
2549 FileNum = len(FileList)\r
2550 if FileNum >= 2:\r
2551 EdkLogger.error("build", OPTION_NOT_SUPPORTED, "There are %d INF files in %s." % (FileNum, WorkingDirectory),\r
2552 ExtraData="Please use '-m <INF_FILE_PATH>' switch to choose one.")\r
2553 elif FileNum == 1:\r
2554 Option.ModuleFile = NormFile(FileList[0], Workspace)\r
2555\r
2556 if Option.ModuleFile:\r
2557 if os.path.isabs (Option.ModuleFile):\r
2558 if os.path.normcase (os.path.normpath(Option.ModuleFile)).find (Workspace) == 0:\r
2559 Option.ModuleFile = NormFile(os.path.normpath(Option.ModuleFile), Workspace)\r
2560 Option.ModuleFile = PathClass(Option.ModuleFile, Workspace)\r
2561 ErrorCode, ErrorInfo = Option.ModuleFile.Validate(".inf", False)\r
2562 if ErrorCode != 0:\r
2563 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)\r
2564\r
2565 if Option.PlatformFile is not None:\r
2566 if os.path.isabs (Option.PlatformFile):\r
2567 if os.path.normcase (os.path.normpath(Option.PlatformFile)).find (Workspace) == 0:\r
2568 Option.PlatformFile = NormFile(os.path.normpath(Option.PlatformFile), Workspace)\r
2569 Option.PlatformFile = PathClass(Option.PlatformFile, Workspace)\r
2570\r
2571 if Option.FdfFile is not None:\r
2572 if os.path.isabs (Option.FdfFile):\r
2573 if os.path.normcase (os.path.normpath(Option.FdfFile)).find (Workspace) == 0:\r
2574 Option.FdfFile = NormFile(os.path.normpath(Option.FdfFile), Workspace)\r
2575 Option.FdfFile = PathClass(Option.FdfFile, Workspace)\r
2576 ErrorCode, ErrorInfo = Option.FdfFile.Validate(".fdf", False)\r
2577 if ErrorCode != 0:\r
2578 EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo)\r
2579\r
2580 if Option.Flag is not None and Option.Flag not in ['-c', '-s']:\r
2581 EdkLogger.error("build", OPTION_VALUE_INVALID, "UNI flag must be one of -c or -s")\r
2582\r
2583 MyBuild = Build(Target, Workspace, Option,LogQ)\r
2584 GlobalData.gCommandLineDefines['ARCH'] = ' '.join(MyBuild.ArchList)\r
2585 if not (MyBuild.LaunchPrebuildFlag and os.path.exists(MyBuild.PlatformBuildPath)):\r
2586 MyBuild.Launch()\r
2587\r
2588 #\r
2589 # All job done, no error found and no exception raised\r
2590 #\r
2591 BuildError = False\r
2592 except FatalError as X:\r
2593 if MyBuild is not None:\r
2594 # for multi-thread build exits safely\r
2595 MyBuild.Relinquish()\r
2596 if Option is not None and Option.debug is not None:\r
2597 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())\r
2598 ReturnCode = X.args[0]\r
2599 except Warning as X:\r
2600 # error from Fdf parser\r
2601 if MyBuild is not None:\r
2602 # for multi-thread build exits safely\r
2603 MyBuild.Relinquish()\r
2604 if Option is not None and Option.debug is not None:\r
2605 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())\r
2606 else:\r
2607 EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError=False)\r
2608 ReturnCode = FORMAT_INVALID\r
2609 except KeyboardInterrupt:\r
2610 if MyBuild is not None:\r
2611\r
2612 # for multi-thread build exits safely\r
2613 MyBuild.Relinquish()\r
2614 ReturnCode = ABORT_ERROR\r
2615 if Option is not None and Option.debug is not None:\r
2616 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())\r
2617 except:\r
2618 if MyBuild is not None:\r
2619 # for multi-thread build exits safely\r
2620 MyBuild.Relinquish()\r
2621\r
2622 # try to get the meta-file from the object causing exception\r
2623 Tb = sys.exc_info()[-1]\r
2624 MetaFile = GlobalData.gProcessingFile\r
2625 while Tb is not None:\r
2626 if 'self' in Tb.tb_frame.f_locals and hasattr(Tb.tb_frame.f_locals['self'], 'MetaFile'):\r
2627 MetaFile = Tb.tb_frame.f_locals['self'].MetaFile\r
2628 Tb = Tb.tb_next\r
2629 EdkLogger.error(\r
2630 "\nbuild",\r
2631 CODE_ERROR,\r
2632 "Unknown fatal error when processing [%s]" % MetaFile,\r
2633 ExtraData="\n(Please send email to %s for help, attaching following call stack trace!)\n" % MSG_EDKII_MAIL_ADDR,\r
2634 RaiseError=False\r
2635 )\r
2636 EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())\r
2637 ReturnCode = CODE_ERROR\r
2638 finally:\r
2639 Utils.Progressor.Abort()\r
2640 Utils.ClearDuplicatedInf()\r
2641\r
2642 if ReturnCode == 0:\r
2643 try:\r
2644 MyBuild.LaunchPostbuild()\r
2645 Conclusion = "Done"\r
2646 except:\r
2647 Conclusion = "Failed"\r
2648 elif ReturnCode == ABORT_ERROR:\r
2649 Conclusion = "Aborted"\r
2650 else:\r
2651 Conclusion = "Failed"\r
2652 FinishTime = time.time()\r
2653 BuildDuration = time.gmtime(int(round(FinishTime - StartTime)))\r
2654 BuildDurationStr = ""\r
2655 if BuildDuration.tm_yday > 1:\r
2656 BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration) + ", %d day(s)" % (BuildDuration.tm_yday - 1)\r
2657 else:\r
2658 BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration)\r
2659 if MyBuild is not None:\r
2660 if not BuildError:\r
2661 MyBuild.BuildReport.GenerateReport(BuildDurationStr, LogBuildTime(MyBuild.AutoGenTime), LogBuildTime(MyBuild.MakeTime), LogBuildTime(MyBuild.GenFdsTime))\r
2662\r
2663 EdkLogger.SetLevel(EdkLogger.QUIET)\r
2664 EdkLogger.quiet("\n- %s -" % Conclusion)\r
2665 EdkLogger.quiet(time.strftime("Build end time: %H:%M:%S, %b.%d %Y", time.localtime()))\r
2666 EdkLogger.quiet("Build total time: %s\n" % BuildDurationStr)\r
2667 Log_Agent.kill()\r
2668 Log_Agent.join()\r
2669 return ReturnCode\r
2670\r
2671if __name__ == '__main__':\r
2672 try:\r
2673 mp.set_start_method('spawn')\r
2674 except:\r
2675 pass\r
2676 r = Main()\r
2677 ## 0-127 is a safe return range, and 1 is a standard default error\r
2678 if r < 0 or r > 127: r = 1\r
2679 sys.exit(r)\r
2680\r