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