blob: 5be095015672df958a8b7ba7f2cdd0e0ab5950dc [file] [log] [blame]
Brian Silvermana29ebf92014-04-23 13:08:49 -05001#!/usr/bin/python3
2
Brian Silvermana29ebf92014-04-23 13:08:49 -05003import sys
4import subprocess
5import re
6import os
7import os.path
8import string
9import shutil
10import errno
Brian Silvermanc3740c32014-05-04 12:42:47 -070011import queue
12import threading
Brian Silvermanf2bbe092014-05-13 16:55:03 -070013import pty
Brian Silverman6bca4722014-05-20 17:02:49 -070014import signal
Brian Silvermanc3740c32014-05-04 12:42:47 -070015
16class TestThread(threading.Thread):
Brian Silvermane6bada62014-05-04 16:16:54 -070017 """Runs 1 test and keeps track of its current state.
18
19 A TestThread is either waiting to start the test, actually running it, done,
20 running it, or stopped. The first 3 always happen in that order and can
21 change to stopped at any time.
22
23 It will finish (ie join() will return) once the process has exited, at which
24 point accessing process to see the status is OK.
25
26 Attributes:
27 executable: The file path of the executable to run.
Brian Silvermanb9e89602014-06-27 14:21:08 -050028 args: A tuple of arguments to give the executable.
Brian Silvermane6bada62014-05-04 16:16:54 -070029 env: The environment variables to set.
30 done_queue: A queue.Queue to place self on once done running the test.
31 start_semaphore: A threading.Semaphore to wait on before starting.
32 process_lock: A lock around process.
33 process: The currently executing test process or None. Synchronized by
34 process_lock.
35 stopped: True if we're stopped.
Brian Silverman730bb012014-06-08 13:05:20 -070036 output: A queue of lines of output from the test.
Brian Silvermane6bada62014-05-04 16:16:54 -070037 """
Brian Silverman730bb012014-06-08 13:05:20 -070038
39 class OutputCopier(threading.Thread):
40 """Copies the output of a test from its output pty into a queue.
41
42 This is necessary because otherwise everything locks up if the test writes
43 too much output and fills up the pty's buffer.
44 """
45
46 def __init__(self, name, fd, queue):
47 super(TestThread.OutputCopier, self).__init__(
48 name=(name + '.OutputCopier'))
49
50 self.fd = fd
51 self.queue = queue
52
53 def run(self):
54 with os.fdopen(self.fd) as to_read:
55 try:
56 for line in to_read:
57 self.queue.put(line)
58 except IOError as e:
59# An EIO from the master side of the pty means we hit the end.
60 if e.errno == errno.EIO:
61 return
62 else:
63 raise e
64
Brian Silvermanb9e89602014-06-27 14:21:08 -050065 def __init__(self, executable, args, env, done_queue, start_semaphore):
Brian Silvermanc3740c32014-05-04 12:42:47 -070066 super(TestThread, self).__init__(
Brian Silvermanb9e89602014-06-27 14:21:08 -050067 name=os.path.split(executable)[-1])
Brian Silvermanc3740c32014-05-04 12:42:47 -070068
69 self.executable = executable
Brian Silvermanb9e89602014-06-27 14:21:08 -050070 self.args = args
Brian Silvermanc3740c32014-05-04 12:42:47 -070071 self.env = env
72 self.done_queue = done_queue
73 self.start_semaphore = start_semaphore
74
Brian Silverman730bb012014-06-08 13:05:20 -070075 self.output = queue.Queue()
76
Brian Silvermanc3740c32014-05-04 12:42:47 -070077 self.process_lock = threading.Lock()
78 self.process = None
79 self.stopped = False
Brian Silverman452aaec2014-05-05 16:52:18 -070080 self.returncode = None
Brian Silverman730bb012014-06-08 13:05:20 -070081 self.output_copier = None
Brian Silvermanc3740c32014-05-04 12:42:47 -070082
83 def run(self):
Brian Silverman48766e42014-12-29 21:37:04 -080084 def setup_test_process():
85# Shove it into its own process group so we can kill any subprocesses easily.
86 os.setpgid(0, 0)
87
Brian Silvermanc3740c32014-05-04 12:42:47 -070088 with self.start_semaphore:
Brian Silverman48766e42014-12-29 21:37:04 -080089 with self.process_lock:
90 if self.stopped:
91 return
Brian Silvermanc3740c32014-05-04 12:42:47 -070092 test_output('Starting test %s...' % self.name)
Brian Silverman730bb012014-06-08 13:05:20 -070093 output_to_read, subprocess_output = pty.openpty()
94 self.output_copier = TestThread.OutputCopier(self.name, output_to_read,
95 self.output)
96 self.output_copier.start()
Brian Silvermanf2bbe092014-05-13 16:55:03 -070097 try:
98 with self.process_lock:
Brian Silvermanb9e89602014-06-27 14:21:08 -050099 self.process = subprocess.Popen((self.name,) + self.args,
100 executable=self.executable,
Brian Silvermanf2bbe092014-05-13 16:55:03 -0700101 env=self.env,
102 stderr=subprocess.STDOUT,
103 stdout=subprocess_output,
Brian Silverman48766e42014-12-29 21:37:04 -0800104 stdin=open(os.devnull, 'r'),
105 preexec_fn=setup_test_process)
Brian Silvermanf2bbe092014-05-13 16:55:03 -0700106 finally:
107 os.close(subprocess_output)
Brian Silvermanc3740c32014-05-04 12:42:47 -0700108 self.process.wait()
109 with self.process_lock:
110 self.returncode = self.process.returncode
111 self.process = None
112 if not self.stopped:
Brian Silverman730bb012014-06-08 13:05:20 -0700113 self.output_copier.join()
Brian Silvermanc3740c32014-05-04 12:42:47 -0700114 self.done_queue.put(self)
115
Brian Silvermanc3740c32014-05-04 12:42:47 -0700116 def kill_process(self):
Brian Silvermanbf0e1db2014-05-10 22:13:15 -0700117 """Forcibly terminates any running process."""
Brian Silvermanc3740c32014-05-04 12:42:47 -0700118 with self.process_lock:
Brian Silverman452aaec2014-05-05 16:52:18 -0700119 if not self.process:
120 return
Brian Silverman6bca4722014-05-20 17:02:49 -0700121 try:
Brian Silverman48766e42014-12-29 21:37:04 -0800122 os.killpg(self.process.pid, signal.SIGKILL)
Brian Silverman6bca4722014-05-20 17:02:49 -0700123 except OSError as e:
124 if e.errno == errno.ESRCH:
125 # We don't really care if it's already gone.
126 pass
127 else:
128 raise e
Brian Silvermanbf0e1db2014-05-10 22:13:15 -0700129 def stop(self):
130 """Changes self to the stopped state."""
131 with self.process_lock:
132 self.stopped = True
Brian Silvermana29ebf92014-04-23 13:08:49 -0500133
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500134def aos_path():
Brian Silvermane6bada62014-05-04 16:16:54 -0700135 """Returns:
136 A relative path to the aos directory.
137 """
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500138 return os.path.join(os.path.dirname(__file__), '..')
139
Brian Silverman5e8dd492015-03-01 17:53:59 -0500140def get_ip():
141 """Retrieves the IP address to download code to."""
Brian Silvermane6bada62014-05-04 16:16:54 -0700142 FILENAME = os.path.normpath(os.path.join(aos_path(), '..',
Brian Silverman5e8dd492015-03-01 17:53:59 -0500143 'output', 'ip_address.txt'))
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500144 if not os.access(FILENAME, os.R_OK):
145 os.makedirs(os.path.dirname(FILENAME), exist_ok=True)
146 with open(FILENAME, 'w') as f:
Austin Schuhe77e9812015-02-16 02:58:17 -0800147 f.write('roboRIO-971.local')
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500148 with open(FILENAME, 'r') as f:
Brian Silverman5e8dd492015-03-01 17:53:59 -0500149 return f.readline().strip()
Austin Schuhd3680052014-10-25 17:52:18 -0700150
Brian Silverman5e8dd492015-03-01 17:53:59 -0500151def get_temp_dir():
152 """Retrieves the temporary directory to use when downloading."""
153 return '/home/admin/tmp/aos_downloader'
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500154
Brian Silverman5e8dd492015-03-01 17:53:59 -0500155def get_target_dir():
156 """Retrieves the tempory deploy directory for downloading code."""
157 return '/home/admin/robot_code'
Austin Schuhd3680052014-10-25 17:52:18 -0700158
Brian Silvermana9b1e5c2014-04-30 18:08:04 -0700159def user_output(message):
Brian Silvermane6bada62014-05-04 16:16:54 -0700160 """Prints message to the user."""
Brian Silvermana9b1e5c2014-04-30 18:08:04 -0700161 print('build.py: ' + message, file=sys.stderr)
162
Brian Silverman452aaec2014-05-05 16:52:18 -0700163# A lock to avoid making a mess intermingling test-related messages.
Brian Silvermanc3740c32014-05-04 12:42:47 -0700164test_output_lock = threading.RLock()
165def test_output(message):
Brian Silvermane6bada62014-05-04 16:16:54 -0700166 """Prints message to the user. Intended for messages related to tests."""
Brian Silvermanc3740c32014-05-04 12:42:47 -0700167 with test_output_lock:
Brian Silvermane6bada62014-05-04 16:16:54 -0700168 print('tests: ' + message, file=sys.stdout)
169
170def call_download_externals(argument):
171 """Calls download_externals.sh for a given set of externals.
172
173 Args:
174 argument: The argument to pass to the shell script to tell it what to
175 download.
176 """
177 subprocess.check_call(
178 (os.path.join(aos_path(), 'build', 'download_externals.sh'),
179 argument),
180 stdin=open(os.devnull, 'r'))
Brian Silvermanc3740c32014-05-04 12:42:47 -0700181
Brian Silvermana29ebf92014-04-23 13:08:49 -0500182class Processor(object):
Brian Silvermane6bada62014-05-04 16:16:54 -0700183 """Represents a processor architecture we can build for."""
184
Brian Silvermana29ebf92014-04-23 13:08:49 -0500185 class UnknownPlatform(Exception):
186 def __init__(self, message):
Brian Silverman452aaec2014-05-05 16:52:18 -0700187 super(Processor.UnknownPlatform, self).__init__()
Brian Silvermana29ebf92014-04-23 13:08:49 -0500188 self.message = message
189
Brian Silvermanb3d50542014-04-23 14:28:55 -0500190 class Platform(object):
Brian Silvermane6bada62014-05-04 16:16:54 -0700191 """Represents a single way to build the code."""
192
Brian Silvermanb3d50542014-04-23 14:28:55 -0500193 def outdir(self):
Brian Silvermane6bada62014-05-04 16:16:54 -0700194 """Returns:
195 The path of the directory build outputs get put in to.
196 """
Brian Silvermanb3d50542014-04-23 14:28:55 -0500197 return os.path.join(
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500198 aos_path(), '..', 'output', self.outname())
Brian Silvermanb3d50542014-04-23 14:28:55 -0500199 def build_ninja(self):
Brian Silvermane6bada62014-05-04 16:16:54 -0700200 """Returns:
201 The path of the build.ninja file.
202 """
Brian Silvermanb3d50542014-04-23 14:28:55 -0500203 return os.path.join(self.outdir(), 'build.ninja')
204
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500205 def do_deploy(self, dry_run, command):
Brian Silvermane6bada62014-05-04 16:16:54 -0700206 """Helper for subclasses to implement deploy.
207
208 Args:
209 dry_run: If True, prints the command instead of actually running it.
210 command: A tuple of command-line arguments.
211 """
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500212 real_command = (('echo',) + command) if dry_run else command
213 subprocess.check_call(real_command, stdin=open(os.devnull, 'r'))
Brian Silvermana29ebf92014-04-23 13:08:49 -0500214
Brian Silvermane6bada62014-05-04 16:16:54 -0700215 def deploy(self, dry_run):
216 """Downloads the compiled code to the target computer."""
217 raise NotImplementedError('deploy should be overriden')
218 def outname(self):
219 """Returns:
220 The name of the directory the code will be compiled to.
221 """
222 raise NotImplementedError('outname should be overriden')
223 def os(self):
224 """Returns:
225 The name of the operating system this platform is for.
226
227 This will be used as the value of the OS gyp variable.
228 """
229 raise NotImplementedError('os should be overriden')
230 def gyp_platform(self):
231 """Returns:
232 The platform name the .gyp files know.
233
234 This will be used as the value of the PLATFORM gyp variable.
235 """
236 raise NotImplementedError('gyp_platform should be overriden')
237 def architecture(self):
238 """Returns:
239 The processor architecture for this platform.
240
241 This will be used as the value of the ARCHITECTURE gyp variable.
242 """
243 raise NotImplementedError('architecture should be overriden')
244 def compiler(self):
245 """Returns:
246 The compiler used for this platform.
247
248 Everything before the first _ will be used as the value of the
249 COMPILER gyp variable and the whole thing will be used as the value
250 of the FULL_COMPILER gyp variable.
251 """
252 raise NotImplementedError('compiler should be overriden')
Brian Silverman452aaec2014-05-05 16:52:18 -0700253 def sanitizer(self):
254 """Returns:
255 The sanitizer used on this platform.
256
257 This will be used as the value of the SANITIZER gyp variable.
258
259 "none" if there isn't one.
260 """
261 raise NotImplementedError('sanitizer should be overriden')
Brian Silvermane6bada62014-05-04 16:16:54 -0700262 def debug(self):
263 """Returns:
264 Whether or not this platform compiles with debugging information.
265
266 The DEBUG gyp variable will be set to "yes" or "no" based on this.
267 """
268 raise NotImplementedError('debug should be overriden')
269 def build_env(self):
270 """Returns:
271 A map of environment variables to set while building this platform.
272 """
273 raise NotImplementedError('build_env should be overriden')
Brian Silvermanbd380fd2014-05-13 16:55:24 -0700274 def priority(self):
275 """Returns:
276 A relative priority for this platform relative to other ones.
277
278 Higher priority platforms will get built, tested, etc first. Generally,
279 platforms which give higher-quality compiler errors etc should come first.
280 """
281 return 0
Brian Silvermane6bada62014-05-04 16:16:54 -0700282
Brian Silverman9b7a6842014-05-05 16:19:11 -0700283 def check_installed(self, platforms, is_deploy):
284 """Makes sure that everything necessary to build platforms are installed."""
Brian Silvermane6bada62014-05-04 16:16:54 -0700285 raise NotImplementedError('check_installed should be overriden')
Brian Silverman452aaec2014-05-05 16:52:18 -0700286 def parse_platforms(self, platforms_string):
Brian Silvermane6bada62014-05-04 16:16:54 -0700287 """Args:
288 string: A user-supplied string saying which platforms to select.
289
290 Returns:
291 A tuple of Platform objects.
292
293 Raises:
294 Processor.UnknownPlatform: Parsing string didn't work out.
295 """
296 raise NotImplementedError('parse_platforms should be overriden')
297 def extra_gyp_flags(self):
298 """Returns:
299 A tuple of extra flags to pass to gyp (if any).
300 """
301 return ()
302 def modify_ninja_file(self, ninja_file):
303 """Modifies a freshly generated ninja file as necessary.
304
305 Args:
306 ninja_file: Path to the file to modify.
307 """
308 pass
309 def download_externals(self, platforms):
310 """Calls download_externals as appropriate to build platforms.
311
312 Args:
313 platforms: A list of platforms to download external libraries for.
314 """
315 raise NotImplementedError('download_externals should be overriden')
316
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700317 def do_check_installed(self, other_packages):
Brian Silvermane6bada62014-05-04 16:16:54 -0700318 """Helper for subclasses to implement check_installed.
319
320 Args:
321 other_packages: A tuple of platform-specific packages to check for."""
Brian Silverman9b7a6842014-05-05 16:19:11 -0700322 all_packages = other_packages
323 # Necessary to build stuff.
324 all_packages += ('ccache', 'make')
325 # Necessary to download stuff to build.
326 all_packages += ('wget', 'git', 'subversion', 'patch', 'unzip', 'bzip2')
327 # Necessary to build externals stuff.
328 all_packages += ('python', 'gcc', 'g++')
Brian Silverman5e94a442014-12-15 15:21:20 -0500329 not_found = []
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700330 try:
Brian Silverman452aaec2014-05-05 16:52:18 -0700331 # TODO(brians): Check versions too.
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700332 result = subprocess.check_output(
Brian Silverman5e94a442014-12-15 15:21:20 -0500333 ('dpkg-query',
334 r"--showformat='${binary:Package}\t${db:Status-Abbrev}\n'",
335 '--show') + all_packages,
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700336 stdin=open(os.devnull, 'r'),
337 stderr=subprocess.STDOUT)
Brian Silverman5e94a442014-12-15 15:21:20 -0500338 for line in result.decode('utf-8').rstrip().splitlines(True):
339 match = re.match('^([^\t]+)\t[^i][^i]$', line)
340 if match:
341 not_found.append(match.group(1))
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700342 except subprocess.CalledProcessError as e:
Brian Silverman9b7a6842014-05-05 16:19:11 -0700343 output = e.output.decode('utf-8').rstrip()
Brian Silverman9b7a6842014-05-05 16:19:11 -0700344 for line in output.splitlines(True):
345 match = re.match(r'dpkg-query: no packages found matching (.*)',
346 line)
347 if match:
348 not_found.append(match.group(1))
Brian Silverman5e94a442014-12-15 15:21:20 -0500349 if not_found:
Brian Silverman9b7a6842014-05-05 16:19:11 -0700350 user_output('Some packages not installed: %s.' % ', '.join(not_found))
351 user_output('Try something like `sudo apt-get install %s`.' %
Brian Silverman452aaec2014-05-05 16:52:18 -0700352 ' '.join(not_found))
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700353 exit(1)
354
Brian Silvermana29ebf92014-04-23 13:08:49 -0500355class PrimeProcessor(Processor):
Brian Silvermane6bada62014-05-04 16:16:54 -0700356 """A Processor subclass for building prime code."""
357
Brian Silvermanb3d50542014-04-23 14:28:55 -0500358 class Platform(Processor.Platform):
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700359 def __init__(self, architecture, compiler, debug, sanitizer):
Brian Silvermanb3d50542014-04-23 14:28:55 -0500360 super(PrimeProcessor.Platform, self).__init__()
361
Brian Silvermane6bada62014-05-04 16:16:54 -0700362 self.__architecture = architecture
363 self.__compiler = compiler
364 self.__debug = debug
365 self.__sanitizer = sanitizer
Brian Silvermana29ebf92014-04-23 13:08:49 -0500366
367 def __repr__(self):
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700368 return 'PrimeProcessor.Platform(architecture=%s, compiler=%s, debug=%s' \
369 ', sanitizer=%s)' \
Brian Silvermane6bada62014-05-04 16:16:54 -0700370 % (self.architecture(), self.compiler(), self.debug(),
371 self.sanitizer())
Brian Silvermana29ebf92014-04-23 13:08:49 -0500372 def __str__(self):
Brian Silvermane6bada62014-05-04 16:16:54 -0700373 return '%s-%s%s-%s' % (self.architecture(), self.compiler(),
Brian Silverman452aaec2014-05-05 16:52:18 -0700374 '-debug' if self.debug() else '', self.sanitizer())
Brian Silvermana29ebf92014-04-23 13:08:49 -0500375
376 def os(self):
377 return 'linux'
378 def gyp_platform(self):
Brian Silvermane6bada62014-05-04 16:16:54 -0700379 return '%s-%s-%s' % (self.os(), self.architecture(), self.compiler())
380 def architecture(self):
381 return self.__architecture
382 def compiler(self):
383 return self.__compiler
384 def sanitizer(self):
385 return self.__sanitizer
386 def debug(self):
387 return self.__debug
Brian Silvermana29ebf92014-04-23 13:08:49 -0500388
Brian Silvermana29ebf92014-04-23 13:08:49 -0500389 def outname(self):
390 return str(self)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500391
Brian Silvermanbd380fd2014-05-13 16:55:24 -0700392 def priority(self):
393 r = 0
Brian Silverman99d22092015-02-18 01:10:05 -0500394 if self.compiler() == 'clang':
Brian Silvermanbd380fd2014-05-13 16:55:24 -0700395 r += 100
396 if self.sanitizer() != 'none':
397 r -= 50
398 elif self.debug():
399 r -= 10
400 if self.architecture() == 'amd64':
401 r += 5
402 return r
403
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500404 def deploy(self, dry_run):
Brian Silverman5e8dd492015-03-01 17:53:59 -0500405 """Downloads code to the prime in a way that avoids clashing too badly with
406 starter (like the naive download everything one at a time)."""
407 if not self.architecture().endswith('_frc'):
408 raise Exception("Don't know how to download code to a %s." %
409 self.architecture())
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500410 SUM = 'md5sum'
Brian Silverman5e8dd492015-03-01 17:53:59 -0500411 TARGET_DIR = get_target_dir()
412 TEMP_DIR = get_temp_dir()
413 TARGET = 'admin@' + get_ip()
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500414
415 from_dir = os.path.join(self.outdir(), 'outputs')
416 sums = subprocess.check_output((SUM,) + tuple(os.listdir(from_dir)),
417 stdin=open(os.devnull, 'r'),
418 cwd=from_dir)
419 to_download = subprocess.check_output(
420 ('ssh', TARGET,
Austin Schuhe77e9812015-02-16 02:58:17 -0800421 """rm -rf {TMPDIR} && mkdir -p {TMPDIR} && \\
422 mkdir -p {TO_DIR} && cd {TO_DIR} \\
Austin Schuh93426072014-10-21 22:22:06 -0700423 && echo '{SUMS}' | {SUM} -c \\
Brian Silvermanff485782014-06-18 19:59:09 -0700424 |& grep -F FAILED | sed 's/^\\(.*\\): FAILED.*$/\\1/g'""".
425 format(TMPDIR=TEMP_DIR, TO_DIR=TARGET_DIR, SUMS=sums.decode('utf-8'),
426 SUM=SUM)))
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500427 if not to_download:
Brian Silvermana9b1e5c2014-04-30 18:08:04 -0700428 user_output("Nothing to download")
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500429 return
430 self.do_deploy(
431 dry_run,
Brian Silvermanff485782014-06-18 19:59:09 -0700432 ('scp', '-o', 'Compression yes')
433 + tuple([os.path.join(from_dir, f) for f in to_download.decode('utf-8').split('\n')[:-1]])
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500434 + (('%s:%s' % (TARGET, TEMP_DIR)),))
435 if not dry_run:
Austin Schuhd3680052014-10-25 17:52:18 -0700436 mv_cmd = ['mv {TMPDIR}/* {TO_DIR} ']
Brian Silverman5e8dd492015-03-01 17:53:59 -0500437 mv_cmd.append('&& chmod u+s {TO_DIR}/starter_exe ')
Austin Schuhd3680052014-10-25 17:52:18 -0700438 mv_cmd.append('&& echo \'Done moving new executables into place\' ')
439 mv_cmd.append('&& bash -c \'sync && sync && sync\'')
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500440 subprocess.check_call(
441 ('ssh', TARGET,
Austin Schuhd3680052014-10-25 17:52:18 -0700442 ''.join(mv_cmd).format(TMPDIR=TEMP_DIR, TO_DIR=TARGET_DIR)))
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500443
Brian Silvermana4aff562014-05-02 17:43:50 -0700444 def build_env(self):
Brian Silvermanc9570932015-03-29 17:26:51 -0400445 OTHER_SYSROOT = '/usr/lib/llvm-3.5/'
Brian Silvermane6bada62014-05-04 16:16:54 -0700446 SYMBOLIZER_PATH = OTHER_SYSROOT + 'bin/llvm-symbolizer'
Brian Silvermana4aff562014-05-02 17:43:50 -0700447 r = {}
Brian Silvermane6bada62014-05-04 16:16:54 -0700448 if self.compiler() == 'clang' or self.compiler() == 'gcc_4.8':
Brian Silverman20141f92015-01-05 17:39:01 -0800449 r['LD_LIBRARY_PATH'] = OTHER_SYSROOT + 'lib'
Brian Silvermane6bada62014-05-04 16:16:54 -0700450 if self.sanitizer() == 'address':
451 r['ASAN_SYMBOLIZER_PATH'] = SYMBOLIZER_PATH
Brian Silverman452aaec2014-05-05 16:52:18 -0700452 r['ASAN_OPTIONS'] = \
Brian Silverman407ca822014-06-05 18:36:41 -0700453 'detect_leaks=1:check_initialization_order=1:strict_init_order=1' \
Brian Silverman415e65d2014-06-21 22:39:28 -0700454 ':detect_stack_use_after_return=1:detect_odr_violation=2' \
455 ':allow_user_segv_handler=1'
Brian Silvermane6bada62014-05-04 16:16:54 -0700456 elif self.sanitizer() == 'memory':
457 r['MSAN_SYMBOLIZER_PATH'] = SYMBOLIZER_PATH
458 elif self.sanitizer() == 'thread':
459 r['TSAN_OPTIONS'] = 'external_symbolizer_path=' + SYMBOLIZER_PATH
Brian Silvermand3fac732014-05-03 16:03:46 -0700460
461 r['CCACHE_COMPRESS'] = 'yes'
Brian Silverman452aaec2014-05-05 16:52:18 -0700462 r['CCACHE_DIR'] = os.path.abspath(os.path.join(aos_path(), '..', 'output',
463 'ccache_dir'))
Brian Silvermand3fac732014-05-03 16:03:46 -0700464 r['CCACHE_HASHDIR'] = 'yes'
Brian Silverman20141f92015-01-05 17:39:01 -0800465 if self.compiler().startswith('clang'):
Brian Silvermand3fac732014-05-03 16:03:46 -0700466 # clang doesn't like being run directly on the preprocessed files.
467 r['CCACHE_CPP2'] = 'yes'
468 # Without this, ccache slows down because of the generated header files.
469 # The race condition that this opens up isn't a problem because the build
470 # system finishes modifying header files before compiling anything that
471 # uses them.
472 r['CCACHE_SLOPPINESS'] = 'include_file_mtime'
Brian Silvermand3fac732014-05-03 16:03:46 -0700473
Brian Silvermane6bada62014-05-04 16:16:54 -0700474 if self.architecture() == 'amd64':
Brian Silvermand3fac732014-05-03 16:03:46 -0700475 r['PATH'] = os.path.join(aos_path(), 'build', 'bin-ld.gold') + \
476 ':' + os.environ['PATH']
477
Brian Silvermana4aff562014-05-02 17:43:50 -0700478 return r
479
Brian Silverman9f330492015-03-01 17:37:02 -0500480 ARCHITECTURES = ('arm_frc', 'amd64')
481 COMPILERS = ('clang', 'gcc')
Brian Silverman47cd6f62014-05-03 10:35:52 -0700482 SANITIZERS = ('address', 'undefined', 'integer', 'memory', 'thread', 'none')
483 SANITIZER_TEST_WARNINGS = {
484 'memory': (True,
485"""We don't have all of the libraries instrumented which leads to lots of false
Brian Silvermanc3740c32014-05-04 12:42:47 -0700486 errors with msan (especially stdlibc++).
487 TODO(brians): Figure out a way to deal with it."""),
Brian Silverman47cd6f62014-05-03 10:35:52 -0700488 }
Brian Silvermana5301e32014-05-03 10:51:49 -0700489 PIE_SANITIZERS = ('memory', 'thread')
Brian Silvermana29ebf92014-04-23 13:08:49 -0500490
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500491 def __init__(self, is_test, is_deploy):
Brian Silverman452aaec2014-05-05 16:52:18 -0700492 super(PrimeProcessor, self).__init__()
Brian Silvermana29ebf92014-04-23 13:08:49 -0500493
494 platforms = []
495 for architecture in PrimeProcessor.ARCHITECTURES:
496 for compiler in PrimeProcessor.COMPILERS:
497 for debug in [True, False]:
Brian Silverman9f330492015-03-01 17:37:02 -0500498 if architecture == 'amd64' and compiler == 'gcc':
Brian Silverman47cd6f62014-05-03 10:35:52 -0700499 # We don't have a compiler to use here.
500 continue
Brian Silvermana29ebf92014-04-23 13:08:49 -0500501 platforms.append(
Daniel Pettiaece37f2014-10-25 17:13:44 -0700502 self.Platform(architecture, compiler, debug, 'none'))
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700503 for sanitizer in PrimeProcessor.SANITIZERS:
Brian Silverman20141f92015-01-05 17:39:01 -0800504 for compiler in ('clang',):
Brian Silverman47cd6f62014-05-03 10:35:52 -0700505 if compiler == 'gcc_4.8' and (sanitizer == 'undefined' or
506 sanitizer == 'integer' or
507 sanitizer == 'memory'):
508 # GCC 4.8 doesn't support these sanitizers.
509 continue
Brian Silvermane6bada62014-05-04 16:16:54 -0700510 if sanitizer == 'none':
511 # We already added sanitizer == 'none' above.
512 continue
513 platforms.append(
Daniel Pettiaece37f2014-10-25 17:13:44 -0700514 self.Platform('amd64', compiler, True, sanitizer))
Brian Silvermane6bada62014-05-04 16:16:54 -0700515 self.__platforms = frozenset(platforms)
516
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500517 if is_test:
Brian Silvermane6bada62014-05-04 16:16:54 -0700518 default_platforms = self.select_platforms(architecture='amd64',
519 debug=True)
Brian Silvermanc3740c32014-05-04 12:42:47 -0700520 for sanitizer, warning in PrimeProcessor.SANITIZER_TEST_WARNINGS.items():
521 if warning[0]:
Brian Silvermane6bada62014-05-04 16:16:54 -0700522 default_platforms -= self.select_platforms(sanitizer=sanitizer)
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500523 elif is_deploy:
Brian Silverman9f330492015-03-01 17:37:02 -0500524 default_platforms = self.select_platforms(architecture='arm_frc',
525 compiler='gcc',
Brian Silvermane6bada62014-05-04 16:16:54 -0700526 debug=False)
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500527 else:
Brian Silvermane6bada62014-05-04 16:16:54 -0700528 default_platforms = self.select_platforms(debug=False)
529 self.__default_platforms = frozenset(default_platforms)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500530
Brian Silvermane6bada62014-05-04 16:16:54 -0700531 def platforms(self):
532 return self.__platforms
533 def default_platforms(self):
534 return self.__default_platforms
535
536 def download_externals(self, platforms):
537 to_download = set()
538 for architecture in PrimeProcessor.ARCHITECTURES:
Brian Silverman99895b92014-09-14 01:01:15 -0400539 pie_sanitizers = set()
Brian Silvermane6bada62014-05-04 16:16:54 -0700540 for sanitizer in PrimeProcessor.PIE_SANITIZERS:
Brian Silverman99895b92014-09-14 01:01:15 -0400541 pie_sanitizers.update(self.select_platforms(architecture=architecture,
542 sanitizer=sanitizer))
543 if platforms & pie_sanitizers:
544 to_download.add(architecture + '-fPIE')
545
Brian Silvermanc5f56952015-01-07 21:20:47 -0800546 if platforms & (self.select_platforms(architecture=architecture) -
Brian Silverman9f330492015-03-01 17:37:02 -0500547 pie_sanitizers):
Brian Silverman99895b92014-09-14 01:01:15 -0400548 to_download.add(architecture)
549
Brian Silvermane6bada62014-05-04 16:16:54 -0700550 for download_target in to_download:
551 call_download_externals(download_target)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500552
Brian Silverman452aaec2014-05-05 16:52:18 -0700553 def parse_platforms(self, platform_string):
554 if platform_string is None:
Brian Silvermane6bada62014-05-04 16:16:54 -0700555 return self.default_platforms()
556 r = self.default_platforms()
Brian Silverman452aaec2014-05-05 16:52:18 -0700557 for part in platform_string.split(','):
Brian Silverman1867aae2014-05-05 17:16:34 -0700558 if part == 'all':
559 r = self.platforms()
560 elif part[0] == '+':
Brian Silvermana29ebf92014-04-23 13:08:49 -0500561 r = r | self.select_platforms_string(part[1:])
562 elif part[0] == '-':
563 r = r - self.select_platforms_string(part[1:])
564 elif part[0] == '=':
565 r = self.select_platforms_string(part[1:])
566 else:
Brian Silverman7cd5ad42014-04-27 08:11:30 -0500567 selected = self.select_platforms_string(part)
Brian Silvermane6bada62014-05-04 16:16:54 -0700568 r = r - (self.platforms() - selected)
Brian Silverman7cd5ad42014-04-27 08:11:30 -0500569 if not r:
570 r = selected
Brian Silvermana29ebf92014-04-23 13:08:49 -0500571 return r
572
Brian Silverman452aaec2014-05-05 16:52:18 -0700573 def select_platforms(self, architecture=None, compiler=None, debug=None,
574 sanitizer=None):
Brian Silvermana29ebf92014-04-23 13:08:49 -0500575 r = []
Brian Silvermane6bada62014-05-04 16:16:54 -0700576 for platform in self.platforms():
577 if architecture is None or platform.architecture() == architecture:
578 if compiler is None or platform.compiler() == compiler:
579 if debug is None or platform.debug() == debug:
580 if sanitizer is None or platform.sanitizer() == sanitizer:
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700581 r.append(platform)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500582 return set(r)
583
Brian Silverman452aaec2014-05-05 16:52:18 -0700584 def select_platforms_string(self, platforms_string):
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700585 architecture, compiler, debug, sanitizer = None, None, None, None
Brian Silverman452aaec2014-05-05 16:52:18 -0700586 for part in platforms_string.split('-'):
Brian Silvermana29ebf92014-04-23 13:08:49 -0500587 if part in PrimeProcessor.ARCHITECTURES:
588 architecture = part
589 elif part in PrimeProcessor.COMPILERS:
590 compiler = part
591 elif part in ['debug', 'dbg']:
592 debug = True
593 elif part in ['release', 'nodebug', 'ndb']:
594 debug = False
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700595 elif part in PrimeProcessor.SANITIZERS:
596 sanitizer = part
Brian Silverman415e65d2014-06-21 22:39:28 -0700597 elif part == 'all':
598 architecture = compiler = debug = sanitizer = None
Brian Silvermana29ebf92014-04-23 13:08:49 -0500599 else:
Brian Silverman452aaec2014-05-05 16:52:18 -0700600 raise Processor.UnknownPlatform(
Brian Silvermandf5348a2014-06-12 23:25:08 -0700601 '"%s" not recognized as a platform string component.' % part)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500602 return self.select_platforms(
603 architecture=architecture,
604 compiler=compiler,
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700605 debug=debug,
606 sanitizer=sanitizer)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500607
Brian Silverman9b7a6842014-05-05 16:19:11 -0700608 def check_installed(self, platforms, is_deploy):
609 packages = set(('lzip', 'm4', 'realpath'))
610 packages.add('ruby')
Brian Silverman9b7a6842014-05-05 16:19:11 -0700611 packages.add('clang-3.5')
Brian Silverman718bca52015-01-07 21:23:36 -0800612 packages.add('clang-format-3.5')
Brian Silverman9b7a6842014-05-05 16:19:11 -0700613 for platform in platforms:
Brian Silverman9f330492015-03-01 17:37:02 -0500614 if platform.compiler() == 'clang' or platform.compiler() == 'gcc_4.8':
Brian Silverman9b7a6842014-05-05 16:19:11 -0700615 packages.add('clang-3.5')
Brian Silverman1867aae2014-05-05 17:16:34 -0700616 if platform.compiler() == 'gcc_4.8':
617 packages.add('libcloog-isl3:amd64')
Brian Silverman9b7a6842014-05-05 16:19:11 -0700618 if is_deploy:
619 packages.add('openssh-client')
Brian Silverman9f330492015-03-01 17:37:02 -0500620 elif platform.architecture == 'arm_frc':
Brian Silvermanbae86d62014-09-14 01:05:31 -0400621 packages.add('gcc-4.9-arm-frc-linux-gnueabi')
622 packages.add('g++-4.9-arm-frc-linux-gnueabi')
Brian Silverman9b7a6842014-05-05 16:19:11 -0700623
624 self.do_check_installed(tuple(packages))
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700625
Daniel Pettiaece37f2014-10-25 17:13:44 -0700626class Bot3PrimeProcessor(PrimeProcessor):
627 """A very simple subclass of PrimeProcessor whose main function is to allow
628 the building of third robot targets in separate directories from those of
629 the main robot."""
630 class Platform(PrimeProcessor.Platform):
631 def __str__(self):
632 return 'bot3-%s' % (super(Bot3PrimeProcessor.Platform, self).__str__())
633
634
Brian Silverman6bca4722014-05-20 17:02:49 -0700635def strsignal(num):
636 # It ends up with SIGIOT instead otherwise, which is weird.
637 if num == signal.SIGABRT:
638 return 'SIGABRT'
639 # SIGCLD is a weird way to spell it.
640 if num == signal.SIGCHLD:
641 return 'SIGCHLD'
642
643 SIGNALS_TO_NAMES = dict((getattr(signal, n), n)
644 for n in dir(signal) if n.startswith('SIG')
645 and '_' not in n)
646 return SIGNALS_TO_NAMES.get(num, 'Unknown signal %d' % num)
647
Brian Silvermana29ebf92014-04-23 13:08:49 -0500648def main():
Brian Silvermandf5348a2014-06-12 23:25:08 -0700649 sys.argv.pop(0)
650 exec_name = sys.argv.pop(0)
651 def print_help(exit_status=None, message=None):
652 if message:
653 print(message)
654 sys.stdout.write(
Brian Silvermanb9e89602014-06-27 14:21:08 -0500655"""Usage: {name} [-j n] [action] [-n] [platform] [target|extra_flag]...
Brian Silvermandf5348a2014-06-12 23:25:08 -0700656Arguments:
657 -j, --jobs Explicitly specify how many jobs to run at a time.
658 Defaults to the number of processors + 2.
659 -n, --dry-run Don't actually do whatever.
660 Currently only meaningful for deploy.
661 action What to do. Defaults to build.
662 build: Build the code.
663 clean: Remove all the built output.
664 tests: Build and then run tests.
665 deploy: Build and then download.
666 platform What variants of the code to build.
667 Defaults to something reasonable.
668 See below for details.
669 target... Which targets to build/test/etc.
670 Defaults to everything.
Brian Silvermanb9e89602014-06-27 14:21:08 -0500671 extra_flag... Extra flags associated with the targets.
672 --gtest_*: Arguments to pass on to tests.
Brian Silverman09480362015-03-29 17:42:24 -0400673 --print_logs, --log_file=*: More test arguments.
Brian Silvermana29ebf92014-04-23 13:08:49 -0500674
Brian Silvermandf5348a2014-06-12 23:25:08 -0700675Specifying targets:
676 Targets are combinations of architecture, compiler, and debug flags. Which
677 ones actually get run is built up as a set. It defaults to something
678 reasonable for the action (specified below).
679 The platform specification (the argument given to this script) is a comma-
680 separated sequence of hyphen-separated platforms, each with an optional
681 prefix.
682 Each selector (the things separated by commas) selects all of the platforms
683 which match all of its components. Its effect on the set of current platforms
684 depends on the prefix character.
685 Here are the prefix characters:
686 + Adds the selected platforms.
687 - Removes the selected platforms.
688 = Sets the current set to the selected platforms.
689 [none] Removes all non-selected platforms.
690 If this makes the current set empty, acts like =.
691 There is also the special psuedo-platform "all" which selects all platforms.
692 All of the available platforms:
693 {all_platforms}
694 Default platforms for deploying:
695 {deploy_platforms}
696 Default platforms for testing:
697 {test_platforms}
698 Default platforms for everything else:
699 {default_platforms}
Brian Silvermana29ebf92014-04-23 13:08:49 -0500700
Brian Silvermandf5348a2014-06-12 23:25:08 -0700701Examples of specifying targets:
702 build everything: "all"
703 only build things with clang: "clang"
704 build everything that uses GCC 4.8 (not just the defaults): "=gcc_4.8"
705 build all of the arm targets that use clang: "clang-arm" or "arm-clang"
706""".format(
707 name=exec_name,
708 all_platforms=str_platforms(PrimeProcessor(False, False).platforms()),
709 deploy_platforms=str_platforms(PrimeProcessor(False, True).default_platforms()),
710 test_platforms=str_platforms(PrimeProcessor(True, False).default_platforms()),
711 default_platforms=str_platforms(PrimeProcessor(False, False).default_platforms()),
712 ))
713 if exit_status is not None:
714 sys.exit(exit_status)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500715
Brian Silvermandf5348a2014-06-12 23:25:08 -0700716 def sort_platforms(platforms):
717 return sorted(
718 platforms, key=lambda platform: (-platform.priority(), str(platform)))
Brian Silvermana29ebf92014-04-23 13:08:49 -0500719
Brian Silvermandf5348a2014-06-12 23:25:08 -0700720 def str_platforms(platforms):
721 r = []
722 for platform in sort_platforms(platforms):
723 r.append(str(platform))
724 if len(r) > 1:
725 r[-1] = 'and ' + r[-1]
726 return ', '.join(r)
Brian Silverman20141f92015-01-05 17:39:01 -0800727
Brian Silvermandf5348a2014-06-12 23:25:08 -0700728 class Arguments(object):
729 def __init__(self):
730 self.jobs = os.sysconf('SC_NPROCESSORS_ONLN') + 2
731 self.action_name = 'build'
732 self.dry_run = False
733 self.targets = []
734 self.platform = None
Brian Silvermanb9e89602014-06-27 14:21:08 -0500735 self.extra_flags = []
Brian Silvermana29ebf92014-04-23 13:08:49 -0500736
Brian Silvermandf5348a2014-06-12 23:25:08 -0700737 args = Arguments()
Brian Silvermana29ebf92014-04-23 13:08:49 -0500738
Brian Silvermandf5348a2014-06-12 23:25:08 -0700739 if len(sys.argv) < 2:
740 print_help(1, 'Not enough arguments')
741 args.processor = sys.argv.pop(0)
742 args.main_gyp = sys.argv.pop(0)
743 VALID_ACTIONS = ['build', 'clean', 'deploy', 'tests']
744 while sys.argv:
745 arg = sys.argv.pop(0)
746 if arg == '-j' or arg == '--jobs':
747 args.jobs = int(sys.argv.pop(0))
748 continue
749 if arg in VALID_ACTIONS:
750 args.action_name = arg
751 continue
752 if arg == '-n' or arg == '--dry-run':
753 if args.action_name != 'deploy':
754 print_help(1, '--dry-run is only valid for deploy')
755 args.dry_run = True
756 continue
757 if arg == '-h' or arg == '--help':
758 print_help(0)
Brian Silverman09480362015-03-29 17:42:24 -0400759 if (re.match('^--gtest_.*$', arg) or arg == '--print-logs' or
760 re.match('^--log_file=.*$', arg)):
Brian Silvermanb9e89602014-06-27 14:21:08 -0500761 if args.action_name == 'tests':
762 args.extra_flags.append(arg)
763 continue
764 else:
Brian Silverman09480362015-03-29 17:42:24 -0400765 print_help(1, '%s is only valid for tests' % arg)
Brian Silvermandf5348a2014-06-12 23:25:08 -0700766 if args.platform:
767 args.targets.append(arg)
768 else:
769 args.platform = arg
Brian Silvermana29ebf92014-04-23 13:08:49 -0500770
Brian Silverman20141f92015-01-05 17:39:01 -0800771 if args.processor == 'prime':
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500772 processor = PrimeProcessor(args.action_name == 'tests',
773 args.action_name == 'deploy')
Daniel Pettiaece37f2014-10-25 17:13:44 -0700774 elif args.processor == 'bot3_prime':
775 processor = Bot3PrimeProcessor(args.action_name == 'tests',
776 args.action_name == 'deploy')
Brian Silvermana29ebf92014-04-23 13:08:49 -0500777 else:
Brian Silvermandf5348a2014-06-12 23:25:08 -0700778 print_help(1, message='Unknown processor "%s".' % args.processor)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500779
Brian Silvermana29ebf92014-04-23 13:08:49 -0500780 unknown_platform_error = None
781 try:
Brian Silvermandf5348a2014-06-12 23:25:08 -0700782 platforms = processor.parse_platforms(args.platform)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500783 except Processor.UnknownPlatform as e:
784 unknown_platform_error = e.message
Brian Silvermandf5348a2014-06-12 23:25:08 -0700785 args.targets.insert(0, args.platform)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500786 platforms = processor.parse_platforms(None)
787 if not platforms:
Brian Silvermandf5348a2014-06-12 23:25:08 -0700788 print_help(1, 'No platforms selected')
Brian Silvermana29ebf92014-04-23 13:08:49 -0500789
Brian Silverman9b7a6842014-05-05 16:19:11 -0700790 processor.check_installed(platforms, args.action_name == 'deploy')
Brian Silvermane6bada62014-05-04 16:16:54 -0700791 processor.download_externals(platforms)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500792
793 class ToolsConfig(object):
794 def __init__(self):
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500795 self.variables = {'AOS': aos_path()}
796 with open(os.path.join(aos_path(), 'build', 'tools_config'), 'r') as f:
Brian Silvermana29ebf92014-04-23 13:08:49 -0500797 for line in f:
798 if line[0] == '#':
799 pass
800 elif line.isspace():
801 pass
802 else:
803 new_name, new_value = line.rstrip().split('=')
804 for name, value in self.variables.items():
805 new_value = new_value.replace('${%s}' % name, value)
806 self.variables[new_name] = new_value
807 def __getitem__(self, key):
808 return self.variables[key]
809
810 tools_config = ToolsConfig()
811
812 def handle_clean_error(function, path, excinfo):
Brian Silverman452aaec2014-05-05 16:52:18 -0700813 _, _ = function, path
Brian Silvermana29ebf92014-04-23 13:08:49 -0500814 if issubclass(OSError, excinfo[0]):
815 if excinfo[1].errno == errno.ENOENT:
816 # Who cares if the file we're deleting isn't there?
817 return
818 raise excinfo[1]
819
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700820 def need_to_run_gyp(platform):
Brian Silvermane6bada62014-05-04 16:16:54 -0700821 """Determines if we need to run gyp again or not.
822
823 The generated build files are supposed to re-run gyp again themselves, but
824 that doesn't work (or at least it used to not) and we sometimes want to
825 modify the results anyways.
826
827 Args:
828 platform: The platform to check for.
829 """
Brian Silvermanf0d3c782014-05-02 23:56:32 -0700830 if not os.path.exists(platform.build_ninja()):
831 return True
Brian Silvermane6bada62014-05-04 16:16:54 -0700832 if os.path.getmtime(__file__) > os.path.getmtime(platform.build_ninja()):
833 return True
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700834 dirs = os.listdir(os.path.join(aos_path(), '..'))
Brian Silvermana4aff562014-05-02 17:43:50 -0700835 # Looking through these folders takes a long time and isn't useful.
Brian Silverman452aaec2014-05-05 16:52:18 -0700836 if dirs.count('output'):
837 dirs.remove('output')
838 if dirs.count('.git'):
839 dirs.remove('.git')
Brian Silvermana4aff562014-05-02 17:43:50 -0700840 return not not subprocess.check_output(
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700841 ('find',) + tuple(os.path.join(aos_path(), '..', d) for d in dirs)
Brian Silverman452aaec2014-05-05 16:52:18 -0700842 + ('-newer', platform.build_ninja(),
843 '(', '-name', '*.gyp', '-or', '-name', '*.gypi', ')'),
Brian Silvermana4aff562014-05-02 17:43:50 -0700844 stdin=open(os.devnull, 'r'))
845
846 def env(platform):
Brian Silvermane6bada62014-05-04 16:16:54 -0700847 """Makes sure we pass through important environmental variables.
848
849 Returns:
850 An environment suitable for passing to subprocess.Popen and friends.
851 """
Brian Silvermana4aff562014-05-02 17:43:50 -0700852 build_env = dict(platform.build_env())
Brian Silvermand3fac732014-05-03 16:03:46 -0700853 if not 'TERM' in build_env:
854 build_env['TERM'] = os.environ['TERM']
855 if not 'PATH' in build_env:
856 build_env['PATH'] = os.environ['PATH']
Brian Silvermana4aff562014-05-02 17:43:50 -0700857 return build_env
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700858
Brian Silvermandf5348a2014-06-12 23:25:08 -0700859 sorted_platforms = sort_platforms(platforms)
860 user_output('Building %s...' % str_platforms(sorted_platforms))
Brian Silverman47cd6f62014-05-03 10:35:52 -0700861
862 if args.action_name == 'tests':
863 for sanitizer, warning in PrimeProcessor.SANITIZER_TEST_WARNINGS.items():
864 warned_about = platforms & processor.select_platforms(sanitizer=sanitizer)
865 if warned_about:
866 user_output(warning[1])
867 if warning[0]:
Brian Silvermane6bada62014-05-04 16:16:54 -0700868 # TODO(brians): Add a --force flag or something to override this?
Brian Silverman47cd6f62014-05-03 10:35:52 -0700869 user_output('Refusing to run tests for sanitizer %s.' % sanitizer)
870 exit(1)
871
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700872 num = 1
Brian Silvermanbd380fd2014-05-13 16:55:24 -0700873 for platform in sorted_platforms:
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700874 user_output('Building %s (%d/%d)...' % (platform, num, len(platforms)))
Brian Silvermana29ebf92014-04-23 13:08:49 -0500875 if args.action_name == 'clean':
876 shutil.rmtree(platform.outdir(), onerror=handle_clean_error)
877 else:
878 if need_to_run_gyp(platform):
Brian Silvermana9b1e5c2014-04-30 18:08:04 -0700879 user_output('Running gyp...')
Brian Silvermana29ebf92014-04-23 13:08:49 -0500880 gyp = subprocess.Popen(
881 (tools_config['GYP'],
882 '--check',
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500883 '--depth=%s' % os.path.join(aos_path(), '..'),
Brian Silvermana29ebf92014-04-23 13:08:49 -0500884 '--no-circular-check',
885 '-f', 'ninja',
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500886 '-I%s' % os.path.join(aos_path(), 'build', 'aos.gypi'),
Brian Silvermana29ebf92014-04-23 13:08:49 -0500887 '-I/dev/stdin', '-Goutput_dir=output',
888 '-DOS=%s' % platform.os(),
889 '-DPLATFORM=%s' % platform.gyp_platform(),
Brian Silvermane6bada62014-05-04 16:16:54 -0700890 '-DARCHITECTURE=%s' % platform.architecture(),
891 '-DCOMPILER=%s' % platform.compiler().split('_')[0],
892 '-DFULL_COMPILER=%s' % platform.compiler(),
893 '-DDEBUG=%s' % ('yes' if platform.debug() else 'no'),
894 '-DSANITIZER=%s' % platform.sanitizer(),
Brian Silverman99895b92014-09-14 01:01:15 -0400895 '-DEXTERNALS_EXTRA=%s' %
Brian Silverman452aaec2014-05-05 16:52:18 -0700896 ('-fPIE' if platform.sanitizer() in PrimeProcessor.PIE_SANITIZERS
Brian Silverman9f330492015-03-01 17:37:02 -0500897 else '')) +
Brian Silvermanb3d50542014-04-23 14:28:55 -0500898 processor.extra_gyp_flags() + (args.main_gyp,),
Brian Silvermana29ebf92014-04-23 13:08:49 -0500899 stdin=subprocess.PIPE)
900 gyp.communicate(("""
901{
902 'target_defaults': {
903 'configurations': {
904 '%s': {}
905 }
906 }
907}""" % platform.outname()).encode())
908 if gyp.returncode:
Brian Silvermana9b1e5c2014-04-30 18:08:04 -0700909 user_output("Running gyp failed!")
Brian Silvermana29ebf92014-04-23 13:08:49 -0500910 exit(1)
Brian Silvermane6bada62014-05-04 16:16:54 -0700911 processor.modify_ninja_file(platform.build_ninja())
Brian Silverman47cd6f62014-05-03 10:35:52 -0700912 user_output('Done running gyp')
Brian Silvermana29ebf92014-04-23 13:08:49 -0500913 else:
Brian Silverman47cd6f62014-05-03 10:35:52 -0700914 user_output("Not running gyp")
Brian Silvermana29ebf92014-04-23 13:08:49 -0500915
916 try:
Brian Silvermanc3740c32014-05-04 12:42:47 -0700917 call = (tools_config['NINJA'],
Brian Silvermandf5348a2014-06-12 23:25:08 -0700918 '-C', platform.outdir()) + tuple(args.targets)
Brian Silvermanc3740c32014-05-04 12:42:47 -0700919 if args.jobs:
920 call += ('-j', str(args.jobs))
921 subprocess.check_call(call,
Brian Silverman452aaec2014-05-05 16:52:18 -0700922 stdin=open(os.devnull, 'r'),
923 env=env(platform))
Brian Silvermana29ebf92014-04-23 13:08:49 -0500924 except subprocess.CalledProcessError as e:
925 if unknown_platform_error is not None:
Brian Silvermana9b1e5c2014-04-30 18:08:04 -0700926 user_output(unknown_platform_error)
Brian Silvermana29ebf92014-04-23 13:08:49 -0500927 raise e
928
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500929 if args.action_name == 'deploy':
930 platform.deploy(args.dry_run)
Brian Silvermane48c09a2014-04-30 18:04:58 -0700931 elif args.action_name == 'tests':
932 dirname = os.path.join(platform.outdir(), 'tests')
Brian Silvermanc3740c32014-05-04 12:42:47 -0700933 done_queue = queue.Queue()
934 running = []
Brian Silvermandf5348a2014-06-12 23:25:08 -0700935 test_start_semaphore = threading.Semaphore(args.jobs)
936 if args.targets:
Brian Silvermanc3740c32014-05-04 12:42:47 -0700937 to_run = []
Brian Silvermandf5348a2014-06-12 23:25:08 -0700938 for target in args.targets:
Brian Silvermanc3740c32014-05-04 12:42:47 -0700939 if target.endswith('_test'):
940 to_run.append(target)
941 else:
942 to_run = os.listdir(dirname)
943 for f in to_run:
Brian Silvermanb9e89602014-06-27 14:21:08 -0500944 thread = TestThread(os.path.join(dirname, f), tuple(args.extra_flags),
945 env(platform), done_queue,
Brian Silvermanc3740c32014-05-04 12:42:47 -0700946 test_start_semaphore)
947 running.append(thread)
948 thread.start()
949 try:
950 while running:
951 done = done_queue.get()
952 running.remove(done)
953 with test_output_lock:
954 test_output('Output from test %s:' % done.name)
Brian Silverman730bb012014-06-08 13:05:20 -0700955 try:
956 while True:
957 line = done.output.get(False)
958 if not sys.stdout.isatty():
959 # Remove color escape codes.
960 line = re.sub(r'\x1B\[[0-9;]*[a-zA-Z]', '', line)
961 sys.stdout.write(line)
962 except queue.Empty:
963 pass
964 if not done.returncode:
965 test_output('Test %s succeeded' % done.name)
966 else:
967 if done.returncode < 0:
968 sig = -done.returncode
969 test_output('Test %s was killed by signal %d (%s)' % \
970 (done.name, sig, strsignal(sig)))
971 elif done.returncode != 1:
972 test_output('Test %s exited with %d' % \
973 (done.name, done.returncode))
Brian Silvermanf2bbe092014-05-13 16:55:03 -0700974 else:
Brian Silverman730bb012014-06-08 13:05:20 -0700975 test_output('Test %s failed' % done.name)
976 user_output('Aborting because of test failure for %s.' % \
977 platform)
978 exit(1)
Brian Silvermanc3740c32014-05-04 12:42:47 -0700979 finally:
980 if running:
981 test_output('Killing other tests...')
Brian Silvermanbf0e1db2014-05-10 22:13:15 -0700982# Stop all of them before killing processes because otherwise stopping some of
983# them tends to let other ones that are waiting to start go.
984 for thread in running:
985 thread.stop()
Brian Silvermanc3740c32014-05-04 12:42:47 -0700986 for thread in running:
Brian Silverman48766e42014-12-29 21:37:04 -0800987 test_output('\tKilling %s' % thread.name)
988 thread.kill_process()
989 thread.kill_process()
990 test_output('Waiting for other tests to die')
Brian Silvermanc3740c32014-05-04 12:42:47 -0700991 for thread in running:
Brian Silvermanc3740c32014-05-04 12:42:47 -0700992 thread.kill_process()
993 thread.join()
994 test_output('Done killing other tests')
Brian Silvermanbe6cfe22014-04-27 08:06:27 -0500995
Brian Silvermanc2d8e5a2014-05-01 18:33:12 -0700996 user_output('Done building %s (%d/%d)' % (platform, num, len(platforms)))
997 num += 1
Brian Silvermana29ebf92014-04-23 13:08:49 -0500998
999if __name__ == '__main__':
1000 main()