blob: 4b0fb37ef14dd7f235f4fdaa7d4f475db201ae49 [file] [log] [blame]
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001"""
2LLDB module which provides the abstract base class of lldb test case.
3
4The concrete subclass can override lldbtest.TesBase in order to inherit the
5common behavior for unitest.TestCase.setUp/tearDown implemented in this file.
6
7The subclass should override the attribute mydir in order for the python runtime
8to locate the individual test cases when running as part of a large test suite
9or when running each test case as a separate python invocation.
10
11./dotest.py provides a test driver which sets up the environment to run the
Johnny Chenc98892e2012-05-16 20:41:28 +000012entire of part of the test suite . Example:
Johnny Chenbf6ffa32010-07-03 03:41:59 +000013
Johnny Chenc98892e2012-05-16 20:41:28 +000014# Exercises the test suite in the types directory....
15/Volumes/data/lldb/svn/ToT/test $ ./dotest.py -A x86_64 types
Johnny Chen57b47382010-09-02 22:25:47 +000016...
Johnny Chend0190a62010-08-23 17:10:44 +000017
Johnny Chenc98892e2012-05-16 20:41:28 +000018Session logs for test failures/errors/unexpected successes will go into directory '2012-05-16-13_35_42'
19Command invoked: python ./dotest.py -A x86_64 types
20compilers=['clang']
Johnny Chend0190a62010-08-23 17:10:44 +000021
Johnny Chenc98892e2012-05-16 20:41:28 +000022Configuration: arch=x86_64 compiler=clang
Johnny Chend0190a62010-08-23 17:10:44 +000023----------------------------------------------------------------------
Johnny Chenc98892e2012-05-16 20:41:28 +000024Collected 72 tests
25
26........................................................................
27----------------------------------------------------------------------
28Ran 72 tests in 135.468s
Johnny Chend0190a62010-08-23 17:10:44 +000029
30OK
Johnny Chenbf6ffa32010-07-03 03:41:59 +000031$
32"""
33
Zachary Turnerff890da2015-10-19 23:45:41 +000034from __future__ import print_function
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000035from __future__ import absolute_import
Zachary Turnerff890da2015-10-19 23:45:41 +000036
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000037# System modules
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000038import abc
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000039import collections
Zachary Turnerabdb8392015-11-16 22:40:30 +000040from distutils.version import LooseVersion
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +000041import gc
Vince Harron9753dd92015-05-10 15:22:09 +000042import glob
Zachary Turnerba105702015-11-16 23:58:20 +000043import inspect
Johnny Chen90312a82010-09-21 22:34:45 +000044import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000045import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000046import re
Daniel Malea69207462013-06-05 21:07:02 +000047import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000048from subprocess import *
Johnny Chenf2b70232010-08-25 18:49:48 +000049import time
Johnny Chena33a93c2010-08-30 23:08:52 +000050import types
Zachary Turner43a01e42015-10-20 21:06:05 +000051
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000052# Third-party modules
53import unittest2
Zachary Turner43a01e42015-10-20 21:06:05 +000054from six import add_metaclass
Zachary Turner814236d2015-10-21 17:48:52 +000055from six import StringIO as SixStringIO
56from six.moves.urllib import parse as urlparse
Zachary Turnercd236b82015-10-26 18:48:24 +000057import six
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000058
59# LLDB modules
60import lldb
Zachary Turner606e3a52015-12-08 01:15:30 +000061from . import configuration
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000062from . import lldbtest_config
63from . import lldbutil
64from . import test_categories
Siva Chandra8af91662015-06-05 00:22:49 +000065
Vince Harron85d19652015-05-21 19:09:29 +000066# dosep.py starts lots and lots of dotest instances
67# This option helps you find if two (or more) dotest instances are using the same
68# directory at the same time
69# Enable it to cause test failures and stderr messages if dotest instances try to run in
70# the same directory simultaneously
71# it is disabled by default because it litters the test directories with ".dirlock" files
72debug_confirm_directory_exclusivity = False
73
Johnny Chen707b3c92010-10-11 22:25:46 +000074# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000075# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000076
77# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000078if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
79 traceAlways = True
80else:
81 traceAlways = False
82
Johnny Chen707b3c92010-10-11 22:25:46 +000083# By default, doCleanup is True.
84if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
85 doCleanup = False
86else:
87 doCleanup = True
88
Johnny Chen8d55a342010-08-31 17:42:54 +000089
Johnny Chen00778092010-08-09 22:01:17 +000090#
91# Some commonly used assert messages.
92#
93
Johnny Chenaa902922010-09-17 22:45:27 +000094COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
95
Johnny Chen00778092010-08-09 22:01:17 +000096CURRENT_EXECUTABLE_SET = "Current executable set successfully"
97
Johnny Chen7d1d7532010-09-02 21:23:12 +000098PROCESS_IS_VALID = "Process is valid"
99
100PROCESS_KILLED = "Process is killed successfully"
101
Johnny Chend5f66fc2010-12-23 01:12:19 +0000102PROCESS_EXITED = "Process exited successfully"
103
104PROCESS_STOPPED = "Process status should be stopped"
105
Sean Callanan05834cd2015-07-01 23:56:30 +0000106RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000107
Johnny Chen17941842010-08-09 23:44:24 +0000108RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000109
Johnny Chen67af43f2010-10-05 19:27:32 +0000110BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
111
Johnny Chen17941842010-08-09 23:44:24 +0000112BREAKPOINT_CREATED = "Breakpoint created successfully"
113
Johnny Chenf10af382010-12-04 00:07:24 +0000114BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
115
Johnny Chene76896c2010-08-17 21:33:31 +0000116BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
117
Johnny Chen17941842010-08-09 23:44:24 +0000118BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000119
Johnny Chen703dbd02010-09-30 17:06:24 +0000120BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
121
Johnny Chen164f1e12010-10-15 18:07:09 +0000122BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
123
Greg Clayton5db6b792012-10-24 18:24:14 +0000124MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
125
Johnny Chen89109ed12011-06-27 20:05:23 +0000126OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
127
Johnny Chen5b3a3572010-12-09 18:22:12 +0000128SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
129
Johnny Chenc70b02a2010-09-22 23:00:20 +0000130STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
131
Johnny Chen1691a162011-04-15 16:44:48 +0000132STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
133
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000134STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
135
Johnny Chen5d6c4642010-11-10 23:46:38 +0000136STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000137
Johnny Chen5d6c4642010-11-10 23:46:38 +0000138STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
139 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000140
Johnny Chen2e431ce2010-10-20 18:38:48 +0000141STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
142
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000143STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
144
Johnny Chenc066ab42010-10-14 01:22:03 +0000145STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
146
Johnny Chen00778092010-08-09 22:01:17 +0000147STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
148
Johnny Chenf68cc122011-09-15 21:09:59 +0000149STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
150
Johnny Chen3c884a02010-08-24 22:07:56 +0000151DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
152
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000153VALID_BREAKPOINT = "Got a valid breakpoint"
154
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000155VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
156
Johnny Chen7209d84f2011-05-06 23:26:12 +0000157VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
158
Johnny Chen5ee88192010-08-27 23:47:36 +0000159VALID_FILESPEC = "Got a valid filespec"
160
Johnny Chen025d1b82010-12-08 01:25:21 +0000161VALID_MODULE = "Got a valid module"
162
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000163VALID_PROCESS = "Got a valid process"
164
Johnny Chen025d1b82010-12-08 01:25:21 +0000165VALID_SYMBOL = "Got a valid symbol"
166
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000167VALID_TARGET = "Got a valid target"
168
Matthew Gardinerc928de32014-10-22 07:22:56 +0000169VALID_PLATFORM = "Got a valid platform"
170
Johnny Chen15f247a2012-02-03 20:43:00 +0000171VALID_TYPE = "Got a valid type"
172
Johnny Chen5819ab42011-07-15 22:28:10 +0000173VALID_VARIABLE = "Got a valid variable"
174
Johnny Chen981463d2010-08-25 19:00:04 +0000175VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000176
Johnny Chenf68cc122011-09-15 21:09:59 +0000177WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000178
Sean Callanan05834cd2015-07-01 23:56:30 +0000179def CMD_MSG(str):
180 '''A generic "Command '%s' returns successfully" message generator.'''
181 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000182
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000183def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000184 '''A generic message generator for the completion mechanism.'''
185 return "'%s' successfully completes to '%s'" % (str_before, str_after)
186
Johnny Chenc0c67f22010-11-09 18:42:22 +0000187def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000188 '''A generic "'%s' returns expected result" message generator if exe.
189 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000190 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000191
Johnny Chen3343f042010-10-19 19:11:38 +0000192def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000193 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000194 return "Value of setting '%s' is correct" % setting
195
Johnny Chen27c41232010-08-26 21:49:29 +0000196def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000197 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000198 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000199
Johnny Chen47ceb032010-10-11 23:52:19 +0000200def line_number(filename, string_to_match):
201 """Helper function to return the line number of the first matched string."""
202 with open(filename, 'r') as f:
203 for i, line in enumerate(f):
204 if line.find(string_to_match) != -1:
205 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000206 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000207 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000208
Johnny Chen67af43f2010-10-05 19:27:32 +0000209def pointer_size():
210 """Return the pointer size of the host system."""
211 import ctypes
212 a_pointer = ctypes.c_void_p(0xffff)
213 return 8 * ctypes.sizeof(a_pointer)
214
Johnny Chen57816732012-02-09 02:01:59 +0000215def is_exe(fpath):
216 """Returns true if fpath is an executable."""
217 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
218
219def which(program):
220 """Returns the full path to a program; None otherwise."""
221 fpath, fname = os.path.split(program)
222 if fpath:
223 if is_exe(program):
224 return program
225 else:
226 for path in os.environ["PATH"].split(os.pathsep):
227 exe_file = os.path.join(path, program)
228 if is_exe(exe_file):
229 return exe_file
230 return None
231
Zachary Turner814236d2015-10-21 17:48:52 +0000232class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000233 """
234 A nice little context manager for recording the debugger interactions into
235 our session object. If trace flag is ON, it also emits the interactions
236 into the stderr.
237 """
238 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000239 """Create a SixStringIO instance; record the session obj and trace flag."""
240 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000241 # The test might not have undergone the 'setUp(self)' phase yet, so that
242 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000243 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000244 self.trace = trace
245
246 def __enter__(self):
247 """
248 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000249 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000250 """
251 return self
252
253 def __exit__(self, type, value, tb):
254 """
255 Context management protocol on exit from the body of the with statement.
256 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000257 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000258 """
259 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000260 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000261 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000262 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000263 self.close()
264
Zachary Turner43a01e42015-10-20 21:06:05 +0000265@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000266class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000267
268 @abc.abstractproperty
269 def pid(self):
270 """Returns process PID if has been launched already."""
271
272 @abc.abstractmethod
273 def launch(self, executable, args):
274 """Launches new process with given executable and args."""
275
276 @abc.abstractmethod
277 def terminate(self):
278 """Terminates previously launched process.."""
279
280class _LocalProcess(_BaseProcess):
281
282 def __init__(self, trace_on):
283 self._proc = None
284 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000285 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000286
287 @property
288 def pid(self):
289 return self._proc.pid
290
291 def launch(self, executable, args):
292 self._proc = Popen([executable] + args,
293 stdout = open(os.devnull) if not self._trace_on else None,
294 stdin = PIPE)
295
296 def terminate(self):
297 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000298 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000299 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
300 for sig in signals_to_try:
301 try:
302 self._proc.send_signal(getattr(signal, sig))
303 time.sleep(self._delayafterterminate)
304 if self._proc.poll() != None:
305 return
306 except ValueError:
307 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000308 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000309 time.sleep(self._delayafterterminate)
310 if self._proc.poll() != None:
311 return
312 self._proc.kill()
313 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000314
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000315 def poll(self):
316 return self._proc.poll()
317
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000318class _RemoteProcess(_BaseProcess):
319
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000320 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000321 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000322 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000323
324 @property
325 def pid(self):
326 return self._pid
327
328 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000329 if self._install_remote:
330 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000331 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000332
333 dst_file_spec = lldb.SBFileSpec(dst_path, False)
334 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
335 if err.Fail():
336 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
337 else:
338 dst_path = executable
339 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000340
341 launch_info = lldb.SBLaunchInfo(args)
342 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000343 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000344
345 # Redirect stdout and stderr to /dev/null
346 launch_info.AddSuppressFileAction(1, False, True)
347 launch_info.AddSuppressFileAction(2, False, True)
348
349 err = lldb.remote_platform.Launch(launch_info)
350 if err.Fail():
351 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
352 self._pid = launch_info.GetProcessID()
353
354 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000355 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000356
Johnny Chen690fcef2010-10-15 23:55:05 +0000357# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000358# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000359def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000360 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000361
362 If the exit code was non-zero it raises a CalledProcessError. The
363 CalledProcessError object will have the return code in the returncode
364 attribute and output in the output attribute.
365
366 The arguments are the same as for the Popen constructor. Example:
367
368 >>> check_output(["ls", "-l", "/dev/null"])
369 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
370
371 The stdout argument is not allowed as it is used internally.
372 To capture standard error in the result, use stderr=STDOUT.
373
374 >>> check_output(["/bin/sh", "-c",
375 ... "ls -l non_existent_file ; exit 0"],
376 ... stderr=STDOUT)
377 'ls: non_existent_file: No such file or directory\n'
378 """
379
380 # Assign the sender object to variable 'test' and remove it from kwargs.
381 test = kwargs.pop('sender', None)
382
Zachary Turner9ef307b2014-07-22 16:19:29 +0000383 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
384 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000385 output = ""
386 error = ""
387 for shellCommand in commandList:
388 if 'stdout' in kwargs:
389 raise ValueError('stdout argument not allowed, it will be overridden.')
390 if 'shell' in kwargs and kwargs['shell']==False:
391 raise ValueError('shell=False not allowed')
Zachary Turner48ef8d4c2015-11-18 18:40:16 +0000392 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, **kwargs)
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000393 pid = process.pid
394 this_output, this_error = process.communicate()
395 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000396
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000397 # Enable trace on failure return while tracking down FreeBSD buildbot issues
398 trace = traceAlways
399 if not trace and retcode and sys.platform.startswith("freebsd"):
400 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000401
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000402 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000403 print(file=sbuf)
404 print("os command:", shellCommand, file=sbuf)
405 print("with pid:", pid, file=sbuf)
406 print("stdout:", this_output, file=sbuf)
407 print("stderr:", this_error, file=sbuf)
408 print("retcode:", retcode, file=sbuf)
409 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000410
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000411 if retcode:
412 cmd = kwargs.get("args")
413 if cmd is None:
414 cmd = shellCommand
415 raise CalledProcessError(retcode, cmd)
416 output = output + this_output
417 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000418 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000419
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000420def getsource_if_available(obj):
421 """
422 Return the text of the source code for an object if available. Otherwise,
423 a print representation is returned.
424 """
425 import inspect
426 try:
427 return inspect.getsource(obj)
428 except:
429 return repr(obj)
430
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000431def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000432 if sys.platform.startswith("freebsd"):
433 return __import__("builder_freebsd")
Kamil Rytarowski0b655da2015-12-05 18:46:56 +0000434 if sys.platform.startswith("netbsd"):
435 return __import__("builder_netbsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000436 return __import__("builder_" + sys.platform)
437
Siva Chandra8af91662015-06-05 00:22:49 +0000438def run_adb_command(cmd, device_id):
439 device_id_args = []
440 if device_id:
441 device_id_args = ["-s", device_id]
442 full_cmd = ["adb"] + device_id_args + cmd
443 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
444 stdout, stderr = p.communicate()
445 return p.returncode, stdout, stderr
446
Chaoren Line9bbabc2015-07-18 00:37:55 +0000447def append_android_envs(dictionary):
448 if dictionary is None:
449 dictionary = {}
450 dictionary["OS"] = "Android"
451 if android_device_api() >= 16:
452 dictionary["PIE"] = 1
453 return dictionary
454
Chaoren Lin9070f532015-07-17 22:13:29 +0000455def target_is_android():
456 if not hasattr(target_is_android, 'result'):
457 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
458 match = re.match(".*-.*-.*-android", triple)
459 target_is_android.result = match is not None
460 return target_is_android.result
461
Siva Chandra8af91662015-06-05 00:22:49 +0000462def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000463 if not hasattr(android_device_api, 'result'):
Zachary Turner606e3a52015-12-08 01:15:30 +0000464 assert configuration.lldb_platform_url is not None
Chaoren Lin9070f532015-07-17 22:13:29 +0000465 device_id = None
Zachary Turner606e3a52015-12-08 01:15:30 +0000466 parsed_url = urlparse.urlparse(configuration.lldb_platform_url)
Ying Chenca922bb2015-11-18 19:03:20 +0000467 host_name = parsed_url.netloc.split(":")[0]
468 if host_name != 'localhost':
469 device_id = host_name
470 if device_id.startswith('[') and device_id.endswith(']'):
471 device_id = device_id[1:-1]
Chaoren Lin9070f532015-07-17 22:13:29 +0000472 retcode, stdout, stderr = run_adb_command(
473 ["shell", "getprop", "ro.build.version.sdk"], device_id)
474 if retcode == 0:
475 android_device_api.result = int(stdout)
476 else:
477 raise LookupError(
478 ">>> Unable to determine the API level of the Android device.\n"
479 ">>> stdout:\n%s\n"
480 ">>> stderr:\n%s\n" % (stdout, stderr))
481 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000482
Zachary Turnerabdb8392015-11-16 22:40:30 +0000483def check_expected_version(comparison, expected, actual):
484 def fn_leq(x,y): return x <= y
485 def fn_less(x,y): return x < y
486 def fn_geq(x,y): return x >= y
487 def fn_greater(x,y): return x > y
488 def fn_eq(x,y): return x == y
489 def fn_neq(x,y): return x != y
490
491 op_lookup = {
492 "==": fn_eq,
493 "=": fn_eq,
494 "!=": fn_neq,
495 "<>": fn_neq,
496 ">": fn_greater,
497 "<": fn_less,
498 ">=": fn_geq,
499 "<=": fn_leq
500 }
501 expected_str = '.'.join([str(x) for x in expected])
502 actual_str = '.'.join([str(x) for x in actual])
503
504 return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str))
505
Johnny Chena74bb0a2011-08-01 18:46:13 +0000506#
507# Decorators for categorizing test cases.
508#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000509from functools import wraps
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000510def add_test_categories(cat):
511 """Decorate an item with test categories"""
512 cat = test_categories.validate(cat, True)
513 def impl(func):
514 func.getCategories = lambda test: cat
515 return func
516 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000517
Johnny Chena74bb0a2011-08-01 18:46:13 +0000518def benchmarks_test(func):
519 """Decorate the item as a benchmarks test."""
520 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
521 raise Exception("@benchmarks_test can only be used to decorate a test method")
522 @wraps(func)
523 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000524 if not configuration.just_do_benchmarks_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000525 self.skipTest("benchmarks tests")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000526 return func(self, *args, **kwargs)
527
528 # Mark this function as such to separate them from the regular tests.
529 wrapper.__benchmarks_test__ = True
530 return wrapper
531
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000532def no_debug_info_test(func):
533 """Decorate the item as a test what don't use any debug info. If this annotation is specified
534 then the test runner won't generate a separate test for each debug info format. """
535 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
536 raise Exception("@no_debug_info_test can only be used to decorate a test method")
537 @wraps(func)
538 def wrapper(self, *args, **kwargs):
539 return func(self, *args, **kwargs)
540
541 # Mark this function as such to separate them from the regular tests.
542 wrapper.__no_debug_info_test__ = True
543 return wrapper
544
Johnny Chenf1548d42012-04-06 00:56:05 +0000545def dsym_test(func):
546 """Decorate the item as a dsym test."""
547 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
548 raise Exception("@dsym_test can only be used to decorate a test method")
549 @wraps(func)
550 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000551 if configuration.dont_do_dsym_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000552 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000553 return func(self, *args, **kwargs)
554
555 # Mark this function as such to separate them from the regular tests.
556 wrapper.__dsym_test__ = True
557 return wrapper
558
559def dwarf_test(func):
560 """Decorate the item as a dwarf test."""
561 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
562 raise Exception("@dwarf_test can only be used to decorate a test method")
563 @wraps(func)
564 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000565 if configuration.dont_do_dwarf_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000566 self.skipTest("dwarf tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000567 return func(self, *args, **kwargs)
568
569 # Mark this function as such to separate them from the regular tests.
570 wrapper.__dwarf_test__ = True
571 return wrapper
572
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000573def dwo_test(func):
574 """Decorate the item as a dwo test."""
575 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
576 raise Exception("@dwo_test can only be used to decorate a test method")
577 @wraps(func)
578 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000579 if configuration.dont_do_dwo_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000580 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000581 return func(self, *args, **kwargs)
582
583 # Mark this function as such to separate them from the regular tests.
584 wrapper.__dwo_test__ = True
585 return wrapper
586
Todd Fialaa41d48c2014-04-28 04:49:40 +0000587def debugserver_test(func):
588 """Decorate the item as a debugserver test."""
589 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
590 raise Exception("@debugserver_test can only be used to decorate a test method")
591 @wraps(func)
592 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000593 if configuration.dont_do_debugserver_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000594 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000595 return func(self, *args, **kwargs)
596
597 # Mark this function as such to separate them from the regular tests.
598 wrapper.__debugserver_test__ = True
599 return wrapper
600
601def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000602 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000603 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
604 raise Exception("@llgs_test can only be used to decorate a test method")
605 @wraps(func)
606 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000607 if configuration.dont_do_llgs_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000608 self.skipTest("llgs tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000609 return func(self, *args, **kwargs)
610
611 # Mark this function as such to separate them from the regular tests.
612 wrapper.__llgs_test__ = True
613 return wrapper
614
Daniel Maleae0f8f572013-08-26 23:57:52 +0000615def not_remote_testsuite_ready(func):
616 """Decorate the item as a test which is not ready yet for remote testsuite."""
617 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
618 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
619 @wraps(func)
620 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000621 if configuration.lldbtest_remote_sandbox or lldb.remote_platform:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000622 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000623 return func(self, *args, **kwargs)
624
625 # Mark this function as such to separate them from the regular tests.
626 wrapper.__not_ready_for_remote_testsuite_test__ = True
627 return wrapper
628
Ed Maste433790a2014-04-23 12:55:41 +0000629def expectedFailure(expected_fn, bugnumber=None):
630 def expectedFailure_impl(func):
631 @wraps(func)
632 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000633 from unittest2 import case
634 self = args[0]
Ed Maste433790a2014-04-23 12:55:41 +0000635 if expected_fn(self):
Zachary Turner5cb8e672015-11-06 18:14:42 +0000636 xfail_func = unittest2.expectedFailure(func)
637 xfail_func(*args, **kwargs)
638 else:
639 func(*args, **kwargs)
Ed Maste433790a2014-04-23 12:55:41 +0000640 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000641 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
642 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000643 if six.callable(bugnumber):
Ying Chen464d1e12015-03-27 00:26:52 +0000644 return expectedFailure_impl(bugnumber)
645 else:
646 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000647
Ying Chen0c352822015-11-16 23:41:02 +0000648# You can also pass not_in(list) to reverse the sense of the test for the arguments that
649# are simple lists, namely oslist, compiler, and debug_info.
650
651def not_in (iterable):
652 return lambda x : x not in iterable
653
Siva Chandra7dcad312015-11-20 20:30:36 +0000654def check_list_or_lambda (list_or_lambda, value):
655 if six.callable(list_or_lambda):
656 return list_or_lambda(value)
657 else:
658 return list_or_lambda is None or value is None or value in list_or_lambda
Ying Chen0c352822015-11-16 23:41:02 +0000659
Ying Chen7091c2c2015-04-21 01:15:47 +0000660# provide a function to xfail on defined oslist, compiler version, and archs
661# if none is specified for any argument, that argument won't be checked and thus means for all
662# for example,
663# @expectedFailureAll, xfail for all platform/compiler/arch,
664# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
665# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Zachary Turnerabdb8392015-11-16 22:40:30 +0000666def expectedFailureAll(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None, swig_version=None, py_version=None):
Ying Chen7091c2c2015-04-21 01:15:47 +0000667 def fn(self):
Siva Chandra7dcad312015-11-20 20:30:36 +0000668 oslist_passes = check_list_or_lambda(oslist, self.getPlatform())
669 compiler_passes = check_list_or_lambda(self.getCompiler(), compiler) and self.expectedCompilerVersion(compiler_version)
Zachary Turnerabdb8392015-11-16 22:40:30 +0000670 arch_passes = self.expectedArch(archs)
671 triple_passes = triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())
Siva Chandra7dcad312015-11-20 20:30:36 +0000672 debug_info_passes = check_list_or_lambda(debug_info, self.debug_info)
Zachary Turnerabdb8392015-11-16 22:40:30 +0000673 swig_version_passes = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (check_expected_version(swig_version[0], swig_version[1], lldb.swig_version))
674 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
675
676 return (oslist_passes and
677 compiler_passes and
678 arch_passes and
679 triple_passes and
680 debug_info_passes and
681 swig_version_passes and
682 py_version_passes)
Ying Chen7091c2c2015-04-21 01:15:47 +0000683 return expectedFailure(fn, bugnumber)
684
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000685def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000686 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
687
688def expectedFailureDwo(bugnumber=None):
689 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000690
691def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000692 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000693
694def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
695 if compiler_version is None:
696 compiler_version=['=', None]
697 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
698
Vince Harron8974ce22015-03-13 19:54:54 +0000699# to XFAIL a specific clang versions, try this
700# @expectedFailureClang('bugnumber', ['<=', '3.4'])
701def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000702 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000703
704def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000705 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000706
Matt Kopec0de53f02013-03-15 19:10:12 +0000707def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000708 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000709
Ed Maste433790a2014-04-23 12:55:41 +0000710def expectedFailureArch(arch, bugnumber=None):
711 def fn(self):
712 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000713 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000714
Enrico Granatae6cedc12013-02-23 01:05:23 +0000715def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000716 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000717
Matt Kopecee969f92013-09-26 23:30:59 +0000718def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000719 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000720
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000721def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000722 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000723 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000724 self.expectedCompiler(compilers) and
725 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000726 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000727
Chaoren Linf7160f32015-06-09 17:39:27 +0000728def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
729 def fn(self):
730 return (getHostPlatform() in oslist and
731 self.expectedCompiler(compilers))
732 return expectedFailure(fn, bugnumber)
733
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000734def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000735 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000736 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000737
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000738def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
739 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000740
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000741def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
742 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000743
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000744def expectedFailureNetBSD(bugnumber=None, compilers=None, debug_info=None):
745 return expectedFailureOS(['netbsd'], bugnumber, compilers, debug_info=debug_info)
746
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000747def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
748 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000749
Chaoren Linf7160f32015-06-09 17:39:27 +0000750def expectedFailureHostWindows(bugnumber=None, compilers=None):
751 return expectedFailureHostOS(['windows'], bugnumber, compilers)
752
Pavel Labath090152b2015-08-20 11:37:19 +0000753def matchAndroid(api_levels=None, archs=None):
754 def match(self):
755 if not target_is_android():
756 return False
757 if archs is not None and self.getArchitecture() not in archs:
758 return False
759 if api_levels is not None and android_device_api() not in api_levels:
760 return False
761 return True
762 return match
763
764
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000765def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000766 """ Mark a test as xfail for Android.
767
768 Arguments:
769 bugnumber - The LLVM pr associated with the problem.
770 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000771 for which a test is expected to fail. None means all API level.
772 arch - A sequence of architecture names specifying the architectures
773 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000774 """
Pavel Labath090152b2015-08-20 11:37:19 +0000775 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000776
Vince Harron7ac3ea42015-06-26 15:13:21 +0000777# if the test passes on the first try, we're done (success)
778# if the test fails once, then passes on the second try, raise an ExpectedFailure
779# if the test fails twice in a row, re-throw the exception from the second test run
780def expectedFlakey(expected_fn, bugnumber=None):
781 def expectedFailure_impl(func):
782 @wraps(func)
783 def wrapper(*args, **kwargs):
784 from unittest2 import case
785 self = args[0]
786 try:
787 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000788 # don't retry if the test case is already decorated with xfail or skip
789 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
790 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000791 except Exception:
792 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000793 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000794 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000795 self.tearDown()
796 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000797 func(*args, **kwargs)
798 except Exception:
799 # oh snap! two failures in a row, record a failure/error
800 raise
801 # record the expected failure
802 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
803 else:
804 raise
805 return wrapper
806 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
807 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000808 if six.callable(bugnumber):
Vince Harron7ac3ea42015-06-26 15:13:21 +0000809 return expectedFailure_impl(bugnumber)
810 else:
811 return expectedFailure_impl
812
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000813def expectedFlakeyDwarf(bugnumber=None):
814 def fn(self):
815 return self.debug_info == "dwarf"
816 return expectedFlakey(fn, bugnumber)
817
818def expectedFlakeyDsym(bugnumber=None):
819 def fn(self):
820 return self.debug_info == "dwarf"
821 return expectedFlakey(fn, bugnumber)
822
Vince Harron7ac3ea42015-06-26 15:13:21 +0000823def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
824 def fn(self):
825 return (self.getPlatform() in oslist and
826 self.expectedCompiler(compilers))
827 return expectedFlakey(fn, bugnumber)
828
829def expectedFlakeyDarwin(bugnumber=None, compilers=None):
830 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
831 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
832
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000833def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
834 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
835
Vince Harron7ac3ea42015-06-26 15:13:21 +0000836def expectedFlakeyLinux(bugnumber=None, compilers=None):
837 return expectedFlakeyOS(['linux'], bugnumber, compilers)
838
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000839def expectedFlakeyNetBSD(bugnumber=None, compilers=None):
840 return expectedFlakeyOS(['netbsd'], bugnumber, compilers)
Vince Harron7ac3ea42015-06-26 15:13:21 +0000841
842def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
843 if compiler_version is None:
844 compiler_version=['=', None]
845 def fn(self):
846 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
847 return expectedFlakey(fn, bugnumber)
848
849# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
850def expectedFlakeyClang(bugnumber=None, compiler_version=None):
851 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
852
853# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
854def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
855 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
856
Pavel Labath63a579c2015-09-07 12:15:27 +0000857def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
858 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
859
Greg Clayton12514562013-12-05 22:22:32 +0000860def skipIfRemote(func):
861 """Decorate the item to skip tests if testing remotely."""
862 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
863 raise Exception("@skipIfRemote can only be used to decorate a test method")
864 @wraps(func)
865 def wrapper(*args, **kwargs):
866 from unittest2 import case
867 if lldb.remote_platform:
868 self = args[0]
869 self.skipTest("skip on remote platform")
870 else:
871 func(*args, **kwargs)
872 return wrapper
873
Siva Chandra4470f382015-06-17 22:32:27 +0000874def skipUnlessListedRemote(remote_list=None):
875 def myImpl(func):
876 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
877 raise Exception("@skipIfRemote can only be used to decorate a "
878 "test method")
879
880 @wraps(func)
881 def wrapper(*args, **kwargs):
882 if remote_list and lldb.remote_platform:
883 self = args[0]
884 triple = self.dbg.GetSelectedPlatform().GetTriple()
885 for r in remote_list:
886 if r in triple:
887 func(*args, **kwargs)
888 return
889 self.skipTest("skip on remote platform %s" % str(triple))
890 else:
891 func(*args, **kwargs)
892 return wrapper
893
894 return myImpl
895
Greg Clayton12514562013-12-05 22:22:32 +0000896def skipIfRemoteDueToDeadlock(func):
897 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
898 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
899 raise Exception("@skipIfRemote can only be used to decorate a test method")
900 @wraps(func)
901 def wrapper(*args, **kwargs):
902 from unittest2 import case
903 if lldb.remote_platform:
904 self = args[0]
905 self.skipTest("skip on remote platform (deadlocks)")
906 else:
907 func(*args, **kwargs)
908 return wrapper
909
Enrico Granatab633e432014-10-06 21:37:06 +0000910def skipIfNoSBHeaders(func):
911 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
912 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000913 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000914 @wraps(func)
915 def wrapper(*args, **kwargs):
916 from unittest2 import case
917 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000918 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000919 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000920 else:
921 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000922 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000923 if not os.path.exists(header):
924 self.skipTest("skip because LLDB.h header not found")
925 else:
926 func(*args, **kwargs)
927 return wrapper
928
Enrico Granata5f92a132015-11-05 00:46:25 +0000929def skipIfiOSSimulator(func):
930 """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
Zachary Turner606e3a52015-12-08 01:15:30 +0000931 return unittest2.skipIf(configuration.lldb_platform_name == 'ios-simulator', 'skip on the iOS Simulator')(func)
Enrico Granata5f92a132015-11-05 00:46:25 +0000932
Robert Flack13c7ad92015-03-30 14:12:17 +0000933def skipIfFreeBSD(func):
934 """Decorate the item to skip tests that should be skipped on FreeBSD."""
935 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000936
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000937def skipIfNetBSD(func):
938 """Decorate the item to skip tests that should be skipped on NetBSD."""
939 return skipIfPlatform(["netbsd"])(func)
940
Greg Claytone0d0a762015-04-02 18:24:03 +0000941def getDarwinOSTriples():
942 return ['darwin', 'macosx', 'ios']
943
Daniel Maleab3d41a22013-07-09 00:08:01 +0000944def skipIfDarwin(func):
945 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000946 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000947
Robert Flack13c7ad92015-03-30 14:12:17 +0000948def skipIfLinux(func):
949 """Decorate the item to skip tests that should be skipped on Linux."""
950 return skipIfPlatform(["linux"])(func)
951
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000952def skipUnlessHostLinux(func):
953 """Decorate the item to skip tests that should be skipped on any non Linux host."""
954 return skipUnlessHostPlatform(["linux"])(func)
955
Robert Flack13c7ad92015-03-30 14:12:17 +0000956def skipIfWindows(func):
957 """Decorate the item to skip tests that should be skipped on Windows."""
958 return skipIfPlatform(["windows"])(func)
959
Chaoren Line6eea5d2015-06-08 22:13:28 +0000960def skipIfHostWindows(func):
961 """Decorate the item to skip tests that should be skipped on Windows."""
962 return skipIfHostPlatform(["windows"])(func)
963
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000964def skipUnlessWindows(func):
965 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
966 return skipUnlessPlatform(["windows"])(func)
967
Robert Flack13c7ad92015-03-30 14:12:17 +0000968def skipUnlessDarwin(func):
969 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000970 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000971
Ryan Brown57bee1e2015-09-14 22:45:11 +0000972def skipUnlessGoInstalled(func):
973 """Decorate the item to skip tests when no Go compiler is available."""
974 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
975 raise Exception("@skipIfGcc can only be used to decorate a test method")
976 @wraps(func)
977 def wrapper(*args, **kwargs):
978 from unittest2 import case
979 self = args[0]
980 compiler = self.getGoCompilerVersion()
981 if not compiler:
982 self.skipTest("skipping because go compiler not found")
983 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000984 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +0000985 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +0000986 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
987 if not match_version:
988 # Couldn't determine version.
989 self.skipTest(
990 "skipping because go version could not be parsed "
991 "out of {}".format(compiler))
992 else:
993 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +0000994 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +0000995 compiler_strict_version = StrictVersion(match_version.group(1))
996 if compiler_strict_version < min_strict_version:
997 self.skipTest(
998 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +0000999 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +00001000 compiler_strict_version,
1001 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +00001002 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +00001003 return wrapper
1004
Robert Flack068898c2015-04-09 18:07:58 +00001005def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +00001006 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001007 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
1008 if platform.startswith('freebsd'):
1009 platform = 'freebsd'
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001010 elif platform.startswith('netbsd'):
1011 platform = 'netbsd'
Robert Flack068898c2015-04-09 18:07:58 +00001012 return platform
1013
Robert Flack6e1fd352015-05-15 12:39:33 +00001014def getHostPlatform():
1015 """Returns the host platform running the test suite."""
1016 # Attempts to return a platform name matching a target Triple platform.
1017 if sys.platform.startswith('linux'):
1018 return 'linux'
1019 elif sys.platform.startswith('win32'):
1020 return 'windows'
1021 elif sys.platform.startswith('darwin'):
1022 return 'darwin'
1023 elif sys.platform.startswith('freebsd'):
1024 return 'freebsd'
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001025 elif sys.platform.startswith('netbsd'):
1026 return 'netbsd'
Robert Flack6e1fd352015-05-15 12:39:33 +00001027 else:
1028 return sys.platform
1029
Robert Flackfb2f6c62015-04-17 08:02:18 +00001030def platformIsDarwin():
1031 """Returns true if the OS triple for the selected platform is any valid apple OS"""
1032 return getPlatform() in getDarwinOSTriples()
1033
Robert Flack6e1fd352015-05-15 12:39:33 +00001034def skipIfHostIncompatibleWithRemote(func):
1035 """Decorate the item to skip tests if binaries built on this host are incompatible."""
1036 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1037 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
1038 @wraps(func)
1039 def wrapper(*args, **kwargs):
1040 from unittest2 import case
1041 self = args[0]
1042 host_arch = self.getLldbArchitecture()
1043 host_platform = getHostPlatform()
1044 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +00001045 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +00001046 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
1047 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
1048 elif target_platform != host_platform:
1049 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
1050 else:
1051 func(*args, **kwargs)
1052 return wrapper
1053
Chaoren Line6eea5d2015-06-08 22:13:28 +00001054def skipIfHostPlatform(oslist):
1055 """Decorate the item to skip tests if running on one of the listed host platforms."""
1056 return unittest2.skipIf(getHostPlatform() in oslist,
1057 "skip on %s" % (", ".join(oslist)))
1058
1059def skipUnlessHostPlatform(oslist):
1060 """Decorate the item to skip tests unless running on one of the listed host platforms."""
1061 return unittest2.skipUnless(getHostPlatform() in oslist,
1062 "requires on of %s" % (", ".join(oslist)))
1063
Zachary Turner793d9972015-08-14 23:29:24 +00001064def skipUnlessArch(archlist):
1065 """Decorate the item to skip tests unless running on one of the listed architectures."""
1066 def myImpl(func):
1067 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1068 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1069
1070 @wraps(func)
1071 def wrapper(*args, **kwargs):
1072 self = args[0]
1073 if self.getArchitecture() not in archlist:
1074 self.skipTest("skipping for architecture %s (requires one of %s)" %
1075 (self.getArchitecture(), ", ".join(archlist)))
1076 else:
1077 func(*args, **kwargs)
1078 return wrapper
1079
1080 return myImpl
1081
Robert Flack13c7ad92015-03-30 14:12:17 +00001082def skipIfPlatform(oslist):
1083 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001084 return unittest2.skipIf(getPlatform() in oslist,
1085 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001086
1087def skipUnlessPlatform(oslist):
1088 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001089 return unittest2.skipUnless(getPlatform() in oslist,
1090 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001091
Daniel Malea48359902013-05-14 20:48:54 +00001092def skipIfLinuxClang(func):
1093 """Decorate the item to skip tests that should be skipped if building on
1094 Linux with clang.
1095 """
1096 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1097 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1098 @wraps(func)
1099 def wrapper(*args, **kwargs):
1100 from unittest2 import case
1101 self = args[0]
1102 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001103 platform = self.getPlatform()
1104 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001105 self.skipTest("skipping because Clang is used on Linux")
1106 else:
1107 func(*args, **kwargs)
1108 return wrapper
1109
Ying Chen7091c2c2015-04-21 01:15:47 +00001110# provide a function to skip on defined oslist, compiler version, and archs
1111# if none is specified for any argument, that argument won't be checked and thus means for all
1112# for example,
1113# @skipIf, skip for all platform/compiler/arch,
1114# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1115# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1116
1117# TODO: refactor current code, to make skipIfxxx functions to call this function
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001118def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None, swig_version=None, py_version=None, remote=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001119 def fn(self):
Siva Chandra7dcad312015-11-20 20:30:36 +00001120 oslist_passes = oslist is None or self.getPlatform() in oslist
1121 compiler_passes = compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))
Zachary Turnerabdb8392015-11-16 22:40:30 +00001122 arch_passes = self.expectedArch(archs)
Siva Chandra7dcad312015-11-20 20:30:36 +00001123 debug_info_passes = debug_info is None or self.debug_info in debug_info
Zachary Turnerabdb8392015-11-16 22:40:30 +00001124 swig_version_passes = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (check_expected_version(swig_version[0], swig_version[1], lldb.swig_version))
1125 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001126 remote_passes = (remote is None) or (remote == (lldb.remote_platform is not None))
Zachary Turnerabdb8392015-11-16 22:40:30 +00001127
1128 return (oslist_passes and
1129 compiler_passes and
1130 arch_passes and
1131 debug_info_passes and
1132 swig_version_passes and
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001133 py_version_passes and
1134 remote_passes)
Zachary Turnerba105702015-11-16 23:58:20 +00001135
1136 local_vars = locals()
1137 args = [x for x in inspect.getargspec(skipIf).args]
1138 arg_vals = [eval(x, globals(), local_vars) for x in args]
1139 args = [x for x in zip(args, arg_vals) if x[1] is not None]
1140 reasons = ['%s=%s' % (x, str(y)) for (x,y) in args]
1141 return skipTestIfFn(fn, bugnumber, skipReason='skipping because ' + ' && '.join(reasons))
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001142
1143def skipIfDebugInfo(bugnumber=None, debug_info=None):
1144 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1145
Greg Claytonedea2372015-10-07 20:01:13 +00001146def skipIfDWO(bugnumber=None):
1147 return skipIfDebugInfo(bugnumber, ["dwo"])
1148
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001149def skipIfDwarf(bugnumber=None):
1150 return skipIfDebugInfo(bugnumber, ["dwarf"])
1151
1152def skipIfDsym(bugnumber=None):
1153 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001154
1155def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1156 def skipTestIfFn_impl(func):
1157 @wraps(func)
1158 def wrapper(*args, **kwargs):
1159 from unittest2 import case
1160 self = args[0]
1161 if expected_fn(self):
1162 self.skipTest(skipReason)
1163 else:
1164 func(*args, **kwargs)
1165 return wrapper
Zachary Turnercd236b82015-10-26 18:48:24 +00001166 if six.callable(bugnumber):
Ying Chen7091c2c2015-04-21 01:15:47 +00001167 return skipTestIfFn_impl(bugnumber)
1168 else:
1169 return skipTestIfFn_impl
1170
Daniel Maleabe230792013-01-24 23:52:09 +00001171def skipIfGcc(func):
1172 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1173 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001174 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001175 @wraps(func)
1176 def wrapper(*args, **kwargs):
1177 from unittest2 import case
1178 self = args[0]
1179 compiler = self.getCompiler()
1180 if "gcc" in compiler:
1181 self.skipTest("skipping because gcc is the test compiler")
1182 else:
1183 func(*args, **kwargs)
1184 return wrapper
1185
Matt Kopec0de53f02013-03-15 19:10:12 +00001186def skipIfIcc(func):
1187 """Decorate the item to skip tests that should be skipped if building with icc ."""
1188 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1189 raise Exception("@skipIfIcc can only be used to decorate a test method")
1190 @wraps(func)
1191 def wrapper(*args, **kwargs):
1192 from unittest2 import case
1193 self = args[0]
1194 compiler = self.getCompiler()
1195 if "icc" in compiler:
1196 self.skipTest("skipping because icc is the test compiler")
1197 else:
1198 func(*args, **kwargs)
1199 return wrapper
1200
Daniel Malea55faa402013-05-02 21:44:31 +00001201def skipIfi386(func):
1202 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1203 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1204 raise Exception("@skipIfi386 can only be used to decorate a test method")
1205 @wraps(func)
1206 def wrapper(*args, **kwargs):
1207 from unittest2 import case
1208 self = args[0]
1209 if "i386" == self.getArchitecture():
1210 self.skipTest("skipping because i386 is not a supported architecture")
1211 else:
1212 func(*args, **kwargs)
1213 return wrapper
1214
Pavel Labath090152b2015-08-20 11:37:19 +00001215def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001216 """Decorator to skip tests when the target is Android.
1217
1218 Arguments:
1219 api_levels - The API levels for which the test should be skipped. If
1220 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001221 arch - A sequence of architecture names specifying the architectures
1222 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001223 """
1224 def myImpl(func):
1225 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1226 raise Exception("@skipIfTargetAndroid can only be used to "
1227 "decorate a test method")
1228 @wraps(func)
1229 def wrapper(*args, **kwargs):
1230 from unittest2 import case
1231 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001232 if matchAndroid(api_levels, archs)(self):
1233 self.skipTest("skiped on Android target with API %d and architecture %s" %
1234 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001235 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001236 return wrapper
1237 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001238
Ilia Kd9953052015-03-12 07:19:41 +00001239def skipUnlessCompilerRt(func):
1240 """Decorate the item to skip tests if testing remotely."""
1241 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1242 raise Exception("@skipUnless can only be used to decorate a test method")
1243 @wraps(func)
1244 def wrapper(*args, **kwargs):
1245 from unittest2 import case
1246 import os.path
Enrico Granata55d99f02015-11-19 21:45:07 +00001247 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "llvm","projects","compiler-rt")
1248 print(compilerRtPath)
Ilia Kd9953052015-03-12 07:19:41 +00001249 if not os.path.exists(compilerRtPath):
1250 self = args[0]
1251 self.skipTest("skip if compiler-rt not found")
1252 else:
1253 func(*args, **kwargs)
1254 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001255
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001256class _PlatformContext(object):
1257 """Value object class which contains platform-specific options."""
1258
1259 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1260 self.shlib_environment_var = shlib_environment_var
1261 self.shlib_prefix = shlib_prefix
1262 self.shlib_extension = shlib_extension
1263
1264
Johnny Chena74bb0a2011-08-01 18:46:13 +00001265class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001266 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001267 Abstract base for performing lldb (see TestBase) or other generic tests (see
1268 BenchBase for one example). lldbtest.Base works with the test driver to
1269 accomplish things.
1270
Johnny Chen8334dad2010-10-22 23:15:46 +00001271 """
Enrico Granata5020f952012-10-24 21:42:49 +00001272
Enrico Granata19186272012-10-24 21:44:48 +00001273 # The concrete subclass should override this attribute.
1274 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001275
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001276 # Keep track of the old current working directory.
1277 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001278
Greg Clayton4570d3e2013-12-10 23:19:29 +00001279 @staticmethod
1280 def compute_mydir(test_file):
1281 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1282
1283 mydir = TestBase.compute_mydir(__file__)'''
1284 test_dir = os.path.dirname(test_file)
1285 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1286
Johnny Chenfb4264c2011-08-01 19:50:58 +00001287 def TraceOn(self):
1288 """Returns True if we are in trace mode (tracing detailed test execution)."""
1289 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001290
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001291 @classmethod
1292 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001293 """
1294 Python unittest framework class setup fixture.
1295 Do current directory manipulation.
1296 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001297 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001298 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001299 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001300
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001301 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001302 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001303
1304 # Change current working directory if ${LLDB_TEST} is defined.
1305 # See also dotest.py which sets up ${LLDB_TEST}.
1306 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001307 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001308 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001309 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001310 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1311
Vince Harron85d19652015-05-21 19:09:29 +00001312 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001313 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001314 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1315 try:
1316 cls.dir_lock.try_acquire()
1317 # write the class that owns the lock into the lock file
1318 cls.dir_lock.handle.write(cls.__name__)
1319 except IOError as ioerror:
1320 # nothing else should have this directory lock
1321 # wait here until we get a lock
1322 cls.dir_lock.acquire()
1323 # read the previous owner from the lock file
1324 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001325 print("LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format(cls.__name__, full_dir, lock_id), file=sys.stderr)
Vince Harron85d19652015-05-21 19:09:29 +00001326 raise ioerror
1327
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001328 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001329 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001330 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001331 elif getPlatform() in ("freebsd", "linux", "netbsd"):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001332 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001333 else:
1334 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001335
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001336 @classmethod
1337 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001338 """
1339 Python unittest framework class teardown fixture.
1340 Do class-wide cleanup.
1341 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001342
Zachary Turner606e3a52015-12-08 01:15:30 +00001343 if doCleanup and not configuration.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001344 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001345 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001346 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001347
Johnny Chen707b3c92010-10-11 22:25:46 +00001348 # Subclass might have specific cleanup function defined.
1349 if getattr(cls, "classCleanup", None):
1350 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001351 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001352 try:
1353 cls.classCleanup()
1354 except:
1355 exc_type, exc_value, exc_tb = sys.exc_info()
1356 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001357
Vince Harron85d19652015-05-21 19:09:29 +00001358 if debug_confirm_directory_exclusivity:
1359 cls.dir_lock.release()
1360 del cls.dir_lock
1361
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001362 # Restore old working directory.
1363 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001364 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001365 os.chdir(cls.oldcwd)
1366
Johnny Chena74bb0a2011-08-01 18:46:13 +00001367 @classmethod
1368 def skipLongRunningTest(cls):
1369 """
1370 By default, we skip long running test case.
1371 This can be overridden by passing '-l' to the test driver (dotest.py).
1372 """
1373 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1374 return False
1375 else:
1376 return True
Johnny Chened492022011-06-21 00:53:00 +00001377
Vince Harron6d3d0f12015-05-10 22:01:59 +00001378 def enableLogChannelsForCurrentTest(self):
1379 if len(lldbtest_config.channels) == 0:
1380 return
1381
1382 # if debug channels are specified in lldbtest_config.channels,
1383 # create a new set of log files for every test
1384 log_basename = self.getLogBasenameForCurrentTest()
1385
1386 # confirm that the file is writeable
1387 host_log_path = "{}-host.log".format(log_basename)
1388 open(host_log_path, 'w').close()
1389
1390 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1391 for channel_with_categories in lldbtest_config.channels:
1392 channel_then_categories = channel_with_categories.split(' ', 1)
1393 channel = channel_then_categories[0]
1394 if len(channel_then_categories) > 1:
1395 categories = channel_then_categories[1]
1396 else:
1397 categories = "default"
1398
1399 if channel == "gdb-remote":
1400 # communicate gdb-remote categories to debugserver
1401 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1402
1403 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1404 if not self.res.Succeeded():
1405 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1406
1407 # Communicate log path name to debugserver & lldb-server
1408 server_log_path = "{}-server.log".format(log_basename)
1409 open(server_log_path, 'w').close()
1410 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1411
1412 # Communicate channels to lldb-server
1413 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1414
1415 if len(lldbtest_config.channels) == 0:
1416 return
1417
1418 def disableLogChannelsForCurrentTest(self):
1419 # close all log files that we opened
1420 for channel_and_categories in lldbtest_config.channels:
1421 # channel format - <channel-name> [<category0> [<category1> ...]]
1422 channel = channel_and_categories.split(' ', 1)[0]
1423 self.ci.HandleCommand("log disable " + channel, self.res)
1424 if not self.res.Succeeded():
1425 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1426
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001427 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001428 """Fixture for unittest test case setup.
1429
1430 It works with the test driver to conditionally skip tests and does other
1431 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001432 #import traceback
1433 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001434
Daniel Malea9115f072013-08-06 15:02:32 +00001435 if "LIBCXX_PATH" in os.environ:
1436 self.libcxxPath = os.environ["LIBCXX_PATH"]
1437 else:
1438 self.libcxxPath = None
1439
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001440 if "LLDBMI_EXEC" in os.environ:
1441 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1442 else:
1443 self.lldbMiExec = None
Vince Harron790d95c2015-05-18 19:39:03 +00001444
Johnny Chenebe51722011-10-07 19:21:09 +00001445 # If we spawn an lldb process for test (via pexpect), do not load the
1446 # init file unless told otherwise.
1447 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1448 self.lldbOption = ""
1449 else:
1450 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001451
Johnny Chen985e7402011-08-01 21:13:26 +00001452 # Assign the test method name to self.testMethodName.
1453 #
1454 # For an example of the use of this attribute, look at test/types dir.
1455 # There are a bunch of test cases under test/types and we don't want the
1456 # module cacheing subsystem to be confused with executable name "a.out"
1457 # used for all the test cases.
1458 self.testMethodName = self._testMethodName
1459
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001460 # Benchmarks test is decorated with @benchmarks_test,
1461 # which also sets the "__benchmarks_test__" attribute of the
1462 # function object to True.
1463 try:
Zachary Turner606e3a52015-12-08 01:15:30 +00001464 if configuration.just_do_benchmarks_test:
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001465 testMethod = getattr(self, self._testMethodName)
1466 if getattr(testMethod, "__benchmarks_test__", False):
1467 pass
1468 else:
1469 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +00001470 except AttributeError:
1471 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001472
Johnny Chen985e7402011-08-01 21:13:26 +00001473 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1474 # with it using pexpect.
1475 self.child = None
1476 self.child_prompt = "(lldb) "
1477 # If the child is interacting with the embedded script interpreter,
1478 # there are two exits required during tear down, first to quit the
1479 # embedded script interpreter and second to quit the lldb command
1480 # interpreter.
1481 self.child_in_script_interpreter = False
1482
Johnny Chenfb4264c2011-08-01 19:50:58 +00001483 # These are for customized teardown cleanup.
1484 self.dict = None
1485 self.doTearDownCleanup = False
1486 # And in rare cases where there are multiple teardown cleanups.
1487 self.dicts = []
1488 self.doTearDownCleanups = False
1489
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001490 # List of spawned subproces.Popen objects
1491 self.subprocesses = []
1492
Daniel Malea69207462013-06-05 21:07:02 +00001493 # List of forked process PIDs
1494 self.forkedProcessPids = []
1495
Johnny Chenfb4264c2011-08-01 19:50:58 +00001496 # Create a string buffer to record the session info, to be dumped into a
1497 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001498 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001499
Vince Harron1f160372015-05-21 18:51:20 +00001500 session_file = "{}.log".format(self.log_basename)
Zachary Turner8d13fab2015-11-07 01:08:15 +00001501 # Python 3 doesn't support unbuffered I/O in text mode. Open buffered.
1502 self.session = open(session_file, "w")
Johnny Chenfb4264c2011-08-01 19:50:58 +00001503
1504 # Optimistically set __errored__, __failed__, __expected__ to False
1505 # initially. If the test errored/failed, the session info
1506 # (self.session) is then dumped into a session specific file for
1507 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001508 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001509 self.__errored__ = False
1510 self.__failed__ = False
1511 self.__expected__ = False
1512 # We are also interested in unexpected success.
1513 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001514 # And skipped tests.
1515 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001516
1517 # See addTearDownHook(self, hook) which allows the client to add a hook
1518 # function to be run during tearDown() time.
1519 self.hooks = []
1520
1521 # See HideStdout(self).
1522 self.sys_stdout_hidden = False
1523
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001524 if self.platformContext:
1525 # set environment variable names for finding shared libraries
1526 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001527
Vince Harron6d3d0f12015-05-10 22:01:59 +00001528 # Create the debugger instance if necessary.
1529 try:
1530 self.dbg = lldb.DBG
1531 except AttributeError:
1532 self.dbg = lldb.SBDebugger.Create()
1533
1534 if not self.dbg:
1535 raise Exception('Invalid debugger instance')
1536
1537 # Retrieve the associated command interpreter instance.
1538 self.ci = self.dbg.GetCommandInterpreter()
1539 if not self.ci:
1540 raise Exception('Could not get the command interpreter')
1541
1542 # And the result object.
1543 self.res = lldb.SBCommandReturnObject()
1544
1545 self.enableLogChannelsForCurrentTest()
1546
Ying Chen0c352822015-11-16 23:41:02 +00001547 #Initialize debug_info
1548 self.debug_info = None
1549
Johnny Chen2a808582011-10-19 16:48:07 +00001550 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001551 """Perform the run hooks to bring lldb debugger to the desired state.
1552
Johnny Chen2a808582011-10-19 16:48:07 +00001553 By default, expect a pexpect spawned child and child prompt to be
1554 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1555 and child prompt and use self.runCmd() to run the hooks one by one.
1556
Johnny Chena737ba52011-10-19 01:06:21 +00001557 Note that child is a process spawned by pexpect.spawn(). If not, your
1558 test case is mostly likely going to fail.
1559
1560 See also dotest.py where lldb.runHooks are processed/populated.
1561 """
Zachary Turner606e3a52015-12-08 01:15:30 +00001562 if not configuration.runHooks:
Johnny Chena737ba52011-10-19 01:06:21 +00001563 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001564 if use_cmd_api:
1565 for hook in lldb.runhooks:
1566 self.runCmd(hook)
1567 else:
1568 if not child or not child_prompt:
1569 self.fail("Both child and child_prompt need to be defined.")
1570 for hook in lldb.runHooks:
1571 child.sendline(hook)
1572 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001573
Daniel Malea249287a2013-02-19 16:08:57 +00001574 def setAsync(self, value):
1575 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1576 old_async = self.dbg.GetAsync()
1577 self.dbg.SetAsync(value)
1578 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1579
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001580 def cleanupSubprocesses(self):
1581 # Ensure any subprocesses are cleaned up
1582 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001583 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001584 del p
1585 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001586 # Ensure any forked processes are cleaned up
1587 for pid in self.forkedProcessPids:
1588 if os.path.exists("/proc/" + str(pid)):
1589 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001590
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001591 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001592 """ Creates a subprocess.Popen object with the specified executable and arguments,
1593 saves it in self.subprocesses, and returns the object.
1594 NOTE: if using this function, ensure you also call:
1595
1596 self.addTearDownHook(self.cleanupSubprocesses)
1597
1598 otherwise the test suite will leak processes.
1599 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001600 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001601 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001602 self.subprocesses.append(proc)
1603 return proc
1604
Daniel Malea69207462013-06-05 21:07:02 +00001605 def forkSubprocess(self, executable, args=[]):
1606 """ Fork a subprocess with its own group ID.
1607 NOTE: if using this function, ensure you also call:
1608
1609 self.addTearDownHook(self.cleanupSubprocesses)
1610
1611 otherwise the test suite will leak processes.
1612 """
1613 child_pid = os.fork()
1614 if child_pid == 0:
1615 # If more I/O support is required, this can be beefed up.
1616 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001617 os.dup2(fd, 1)
1618 os.dup2(fd, 2)
1619 # This call causes the child to have its of group ID
1620 os.setpgid(0,0)
1621 os.execvp(executable, [executable] + args)
1622 # Give the child time to get through the execvp() call
1623 time.sleep(0.1)
1624 self.forkedProcessPids.append(child_pid)
1625 return child_pid
1626
Johnny Chenfb4264c2011-08-01 19:50:58 +00001627 def HideStdout(self):
1628 """Hide output to stdout from the user.
1629
1630 During test execution, there might be cases where we don't want to show the
1631 standard output to the user. For example,
1632
Zachary Turner35d017f2015-10-23 17:04:29 +00001633 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001634
1635 tests whether command abbreviation for 'script' works or not. There is no
1636 need to show the 'Hello' output to the user as long as the 'script' command
1637 succeeds and we are not in TraceOn() mode (see the '-t' option).
1638
1639 In this case, the test method calls self.HideStdout(self) to redirect the
1640 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1641
1642 Note that you should only call this method at most once during a test case
1643 execution. Any subsequent call has no effect at all."""
1644 if self.sys_stdout_hidden:
1645 return
1646
1647 self.sys_stdout_hidden = True
1648 old_stdout = sys.stdout
1649 sys.stdout = open(os.devnull, 'w')
1650 def restore_stdout():
1651 sys.stdout = old_stdout
1652 self.addTearDownHook(restore_stdout)
1653
1654 # =======================================================================
1655 # Methods for customized teardown cleanups as well as execution of hooks.
1656 # =======================================================================
1657
1658 def setTearDownCleanup(self, dictionary=None):
1659 """Register a cleanup action at tearDown() time with a dictinary"""
1660 self.dict = dictionary
1661 self.doTearDownCleanup = True
1662
1663 def addTearDownCleanup(self, dictionary):
1664 """Add a cleanup action at tearDown() time with a dictinary"""
1665 self.dicts.append(dictionary)
1666 self.doTearDownCleanups = True
1667
1668 def addTearDownHook(self, hook):
1669 """
1670 Add a function to be run during tearDown() time.
1671
1672 Hooks are executed in a first come first serve manner.
1673 """
Zachary Turnercd236b82015-10-26 18:48:24 +00001674 if six.callable(hook):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001675 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001676 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001677 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001678
1679 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001680
Jim Inghamda3a3862014-10-16 23:02:14 +00001681 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001682 # This is for the case of directly spawning 'lldb' and interacting with it
1683 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001684 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001685 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001686 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001687 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001688 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001689 if self.child_in_script_interpreter:
1690 self.child.sendline('quit()')
1691 self.child.expect_exact(self.child_prompt)
1692 self.child.sendline('settings set interpreter.prompt-on-quit false')
1693 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001694 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001695 except (ValueError, pexpect.ExceptionPexpect):
1696 # child is already terminated
1697 pass
1698 except OSError as exception:
1699 import errno
1700 if exception.errno != errno.EIO:
1701 # unexpected error
1702 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001703 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001704 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001705 finally:
1706 # Give it one final blow to make sure the child is terminated.
1707 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001708
1709 def tearDown(self):
1710 """Fixture for unittest test case teardown."""
1711 #import traceback
1712 #traceback.print_stack()
1713
1714 self.deletePexpectChild()
1715
Johnny Chenfb4264c2011-08-01 19:50:58 +00001716 # Check and run any hook functions.
1717 for hook in reversed(self.hooks):
1718 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001719 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001720 import inspect
1721 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001722 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001723 hook()
1724 elif hook_argc == 1:
1725 hook(self)
1726 else:
1727 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001728
1729 del self.hooks
1730
1731 # Perform registered teardown cleanup.
1732 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001733 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001734
1735 # In rare cases where there are multiple teardown cleanups added.
1736 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001737 if self.dicts:
1738 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001739 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001740
Vince Harron9753dd92015-05-10 15:22:09 +00001741 self.disableLogChannelsForCurrentTest()
1742
Johnny Chenfb4264c2011-08-01 19:50:58 +00001743 # =========================================================
1744 # Various callbacks to allow introspection of test progress
1745 # =========================================================
1746
1747 def markError(self):
1748 """Callback invoked when an error (unexpected exception) errored."""
1749 self.__errored__ = True
1750 with recording(self, False) as sbuf:
1751 # False because there's no need to write "ERROR" to the stderr twice.
1752 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001753 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001754
Zachary Turnerb1490b62015-08-26 19:44:56 +00001755 def markCleanupError(self):
1756 """Callback invoked when an error occurs while a test is cleaning up."""
1757 self.__cleanup_errored__ = True
1758 with recording(self, False) as sbuf:
1759 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1760 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001761 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001762
Johnny Chenfb4264c2011-08-01 19:50:58 +00001763 def markFailure(self):
1764 """Callback invoked when a failure (test assertion failure) occurred."""
1765 self.__failed__ = True
1766 with recording(self, False) as sbuf:
1767 # False because there's no need to write "FAIL" to the stderr twice.
1768 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001769 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001770
Enrico Granatae6cedc12013-02-23 01:05:23 +00001771 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001772 """Callback invoked when an expected failure/error occurred."""
1773 self.__expected__ = True
1774 with recording(self, False) as sbuf:
1775 # False because there's no need to write "expected failure" to the
1776 # stderr twice.
1777 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001778 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001779 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001780 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001781 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001782
Johnny Chenc5cc6252011-08-15 23:09:08 +00001783 def markSkippedTest(self):
1784 """Callback invoked when a test is skipped."""
1785 self.__skipped__ = True
1786 with recording(self, False) as sbuf:
1787 # False because there's no need to write "skipped test" to the
1788 # stderr twice.
1789 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001790 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001791
Enrico Granatae6cedc12013-02-23 01:05:23 +00001792 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001793 """Callback invoked when an unexpected success occurred."""
1794 self.__unexpected__ = True
1795 with recording(self, False) as sbuf:
1796 # False because there's no need to write "unexpected success" to the
1797 # stderr twice.
1798 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001799 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001800 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001801 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001802 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001803
Greg Clayton70995582015-01-07 22:25:50 +00001804 def getRerunArgs(self):
1805 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001806
1807 def getLogBasenameForCurrentTest(self, prefix=None):
1808 """
1809 returns a partial path that can be used as the beginning of the name of multiple
1810 log files pertaining to this test
1811
1812 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1813 """
1814 dname = os.path.join(os.environ["LLDB_TEST"],
1815 os.environ["LLDB_SESSION_DIRNAME"])
1816 if not os.path.isdir(dname):
1817 os.mkdir(dname)
1818
1819 compiler = self.getCompiler()
1820
1821 if compiler[1] == ':':
1822 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001823 if os.path.altsep is not None:
1824 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001825
Vince Harron19e300f2015-05-12 00:50:54 +00001826 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001827 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001828 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001829
1830 if prefix is not None:
1831 fname = "{}-{}".format(prefix, fname)
1832
1833 return os.path.join(dname, fname)
1834
Johnny Chenfb4264c2011-08-01 19:50:58 +00001835 def dumpSessionInfo(self):
1836 """
1837 Dump the debugger interactions leading to a test error/failure. This
1838 allows for more convenient postmortem analysis.
1839
1840 See also LLDBTestResult (dotest.py) which is a singlton class derived
1841 from TextTestResult and overwrites addError, addFailure, and
1842 addExpectedFailure methods to allow us to to mark the test instance as
1843 such.
1844 """
1845
1846 # We are here because self.tearDown() detected that this test instance
1847 # either errored or failed. The lldb.test_result singleton contains
1848 # two lists (erros and failures) which get populated by the unittest
1849 # framework. Look over there for stack trace information.
1850 #
1851 # The lists contain 2-tuples of TestCase instances and strings holding
1852 # formatted tracebacks.
1853 #
1854 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001855
Vince Harron35b17dc2015-05-21 18:20:21 +00001856 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001857 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001858 if self.__errored__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001859 pairs = configuration.test_result.errors
Johnny Chenfb4264c2011-08-01 19:50:58 +00001860 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001861 elif self.__cleanup_errored__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001862 pairs = configuration.test_result.cleanup_errors
Zachary Turnerb1490b62015-08-26 19:44:56 +00001863 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001864 elif self.__failed__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001865 pairs = configuration.test_result.failures
Johnny Chenfb4264c2011-08-01 19:50:58 +00001866 prefix = 'Failure'
1867 elif self.__expected__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001868 pairs = configuration.test_result.expectedFailures
Johnny Chenfb4264c2011-08-01 19:50:58 +00001869 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001870 elif self.__skipped__:
1871 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001872 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001873 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001874 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001875 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001876
Johnny Chenc5cc6252011-08-15 23:09:08 +00001877 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001878 for test, traceback in pairs:
1879 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001880 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001881
Vince Harron35b17dc2015-05-21 18:20:21 +00001882 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001883 testMethod = getattr(self, self._testMethodName)
1884 if getattr(testMethod, "__benchmarks_test__", False):
1885 benchmarks = True
1886 else:
1887 benchmarks = False
1888
Vince Harron35b17dc2015-05-21 18:20:21 +00001889 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001890 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1891 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1892 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001893 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001894 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001895 self.session.close()
1896 del self.session
1897
1898 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001899 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001900
1901 if prefix != 'Success' or lldbtest_config.log_success:
1902 # keep all log files, rename them to include prefix
1903 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1904 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001905 if os.path.isfile(src):
1906 dst = src.replace(self.log_basename, dst_log_basename)
1907 if os.name == "nt" and os.path.isfile(dst):
1908 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1909 # it silently replaces the destination. Ultimately this means that atomic renames are not
1910 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1911 # destination first if it already exists.
1912 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001913
Zachary Turner306278f2015-05-26 20:26:29 +00001914 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001915 else:
1916 # success! (and we don't want log files) delete log files
1917 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001918 try:
1919 os.unlink(log_file)
1920 except:
1921 # We've seen consistent unlink failures on Windows, perhaps because the
1922 # just-created log file is being scanned by anti-virus. Empirically, this
1923 # sleep-and-retry approach allows tests to succeed much more reliably.
1924 # Attempts to figure out exactly what process was still holding a file handle
1925 # have failed because running instrumentation like Process Monitor seems to
1926 # slow things down enough that the problem becomes much less consistent.
1927 time.sleep(0.5)
1928 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001929
1930 # ====================================================
1931 # Config. methods supported through a plugin interface
1932 # (enables reading of the current test configuration)
1933 # ====================================================
1934
1935 def getArchitecture(self):
1936 """Returns the architecture in effect the test suite is running with."""
1937 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001938 arch = module.getArchitecture()
1939 if arch == 'amd64':
1940 arch = 'x86_64'
1941 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001942
Vince Harron02613762015-05-04 00:17:53 +00001943 def getLldbArchitecture(self):
1944 """Returns the architecture of the lldb binary."""
1945 if not hasattr(self, 'lldbArchitecture'):
1946
1947 # spawn local process
1948 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001949 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001950 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001951 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001952 "-o",
1953 "quit"
1954 ]
1955
1956 output = check_output(command)
1957 str = output.decode("utf-8");
1958
1959 for line in str.splitlines():
1960 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1961 if m:
1962 self.lldbArchitecture = m.group(1)
1963 break
1964
1965 return self.lldbArchitecture
1966
Johnny Chenfb4264c2011-08-01 19:50:58 +00001967 def getCompiler(self):
1968 """Returns the compiler in effect the test suite is running with."""
1969 module = builder_module()
1970 return module.getCompiler()
1971
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001972 def getCompilerBinary(self):
1973 """Returns the compiler binary the test suite is running with."""
1974 return self.getCompiler().split()[0]
1975
Daniel Malea0aea0162013-02-27 17:29:46 +00001976 def getCompilerVersion(self):
1977 """ Returns a string that represents the compiler version.
1978 Supports: llvm, clang.
1979 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00001980 from .lldbutil import which
Daniel Malea0aea0162013-02-27 17:29:46 +00001981 version = 'unknown'
1982
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001983 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001984 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001985 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001986 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001987 if m:
1988 version = m.group(1)
1989 return version
1990
Ryan Brown57bee1e2015-09-14 22:45:11 +00001991 def getGoCompilerVersion(self):
1992 """ Returns a string that represents the go compiler version, or None if go is not found.
1993 """
1994 compiler = which("go")
1995 if compiler:
1996 version_output = system([[compiler, "version"]])[0]
1997 for line in version_output.split(os.linesep):
1998 m = re.search('go version (devel|go\\S+)', line)
1999 if m:
2000 return m.group(1)
2001 return None
2002
Greg Claytone0d0a762015-04-02 18:24:03 +00002003 def platformIsDarwin(self):
2004 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00002005 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00002006
Robert Flack13c7ad92015-03-30 14:12:17 +00002007 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00002008 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00002009 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00002010
Daniel Maleaadaaec92013-08-06 20:51:41 +00002011 def isIntelCompiler(self):
2012 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
2013 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
2014
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002015 def expectedCompilerVersion(self, compiler_version):
2016 """Returns True iff compiler_version[1] matches the current compiler version.
2017 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
2018 Any operator other than the following defaults to an equality test:
2019 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
2020 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002021 if (compiler_version == None):
2022 return True
2023 operator = str(compiler_version[0])
2024 version = compiler_version[1]
2025
2026 if (version == None):
2027 return True
2028 if (operator == '>'):
2029 return self.getCompilerVersion() > version
2030 if (operator == '>=' or operator == '=>'):
2031 return self.getCompilerVersion() >= version
2032 if (operator == '<'):
2033 return self.getCompilerVersion() < version
2034 if (operator == '<=' or operator == '=<'):
2035 return self.getCompilerVersion() <= version
2036 if (operator == '!=' or operator == '!' or operator == 'not'):
2037 return str(version) not in str(self.getCompilerVersion())
2038 return str(version) in str(self.getCompilerVersion())
2039
2040 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002041 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002042 if (compilers == None):
2043 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002044
2045 for compiler in compilers:
2046 if compiler in self.getCompiler():
2047 return True
2048
2049 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002050
Ying Chen7091c2c2015-04-21 01:15:47 +00002051 def expectedArch(self, archs):
2052 """Returns True iff any element of archs is a sub-string of the current architecture."""
2053 if (archs == None):
2054 return True
2055
2056 for arch in archs:
2057 if arch in self.getArchitecture():
2058 return True
2059
2060 return False
2061
Johnny Chenfb4264c2011-08-01 19:50:58 +00002062 def getRunOptions(self):
2063 """Command line option for -A and -C to run this test again, called from
2064 self.dumpSessionInfo()."""
2065 arch = self.getArchitecture()
2066 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00002067 if arch:
2068 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00002069 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00002070 option_str = ""
2071 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00002072 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00002073 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00002074
2075 # ==================================================
2076 # Build methods supported through a plugin interface
2077 # ==================================================
2078
Ed Mastec97323e2014-04-01 18:47:58 +00002079 def getstdlibFlag(self):
2080 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00002081 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00002082 stdlibflag = "-stdlib=libc++"
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002083 else: # this includes NetBSD
Ed Mastec97323e2014-04-01 18:47:58 +00002084 stdlibflag = ""
2085 return stdlibflag
2086
Matt Kopec7663b3a2013-09-25 17:44:00 +00002087 def getstdFlag(self):
2088 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002089 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002090 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002091 else:
2092 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002093 return stdflag
2094
2095 def buildDriver(self, sources, exe_name):
2096 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2097 or LLDB.framework).
2098 """
2099
2100 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002101 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002102
2103 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002104 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002105 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002106 d = {'CXX_SOURCES' : sources,
2107 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002108 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002109 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2110 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002111 }
Ed Maste372c24d2013-07-25 21:02:34 +00002112 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002113 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002114 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002115 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002116 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002117 elif sys.platform.startswith('win'):
2118 d = {'CXX_SOURCES' : sources,
2119 'EXE' : exe_name,
2120 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002121 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002122 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002123 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002124
2125 self.buildDefault(dictionary=d)
2126
Matt Kopec7663b3a2013-09-25 17:44:00 +00002127 def buildLibrary(self, sources, lib_name):
2128 """Platform specific way to build a default library. """
2129
2130 stdflag = self.getstdFlag()
2131
Greg Clayton22fd3b12015-10-26 17:52:16 +00002132 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002133 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002134 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002135 d = {'DYLIB_CXX_SOURCES' : sources,
2136 'DYLIB_NAME' : lib_name,
2137 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002138 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2139 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002140 }
Robert Flack4629c4b2015-05-15 18:54:32 +00002141 elif self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux' or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002142 d = {'DYLIB_CXX_SOURCES' : sources,
2143 'DYLIB_NAME' : lib_name,
2144 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002145 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002146 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002147 d = {'DYLIB_CXX_SOURCES' : sources,
2148 'DYLIB_NAME' : lib_name,
2149 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002150 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002151 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002152 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002153
2154 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002155
Daniel Malea55faa402013-05-02 21:44:31 +00002156 def buildProgram(self, sources, exe_name):
2157 """ Platform specific way to build an executable from C/C++ sources. """
2158 d = {'CXX_SOURCES' : sources,
2159 'EXE' : exe_name}
2160 self.buildDefault(dictionary=d)
2161
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002162 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002163 """Platform specific way to build the default binaries."""
Zachary Turner606e3a52015-12-08 01:15:30 +00002164 if configuration.skip_build_and_cleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00002165 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002166 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002167 if target_is_android():
2168 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002169 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002170 raise Exception("Don't know how to build default binary")
2171
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002172 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002173 """Platform specific way to build binaries with dsym info."""
Zachary Turner606e3a52015-12-08 01:15:30 +00002174 if configuration.skip_build_and_cleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00002175 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002176 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002177 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002178 raise Exception("Don't know how to build binary with dsym")
2179
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002180 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002181 """Platform specific way to build binaries with dwarf maps."""
Zachary Turner606e3a52015-12-08 01:15:30 +00002182 if configuration.skip_build_and_cleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00002183 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002184 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002185 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002186 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002187 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002188 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002189
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002190 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2191 """Platform specific way to build binaries with dwarf maps."""
Zachary Turner606e3a52015-12-08 01:15:30 +00002192 if configuration.skip_build_and_cleanup:
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002193 return
2194 module = builder_module()
2195 if target_is_android():
2196 dictionary = append_android_envs(dictionary)
2197 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2198 raise Exception("Don't know how to build binary with dwo")
2199
Ryan Brown57bee1e2015-09-14 22:45:11 +00002200 def buildGo(self):
2201 """Build the default go binary.
2202 """
2203 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2204
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002205 def signBinary(self, binary_path):
2206 if sys.platform.startswith("darwin"):
2207 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2208 call(codesign_cmd, shell=True)
2209
Kuba Breckabeed8212014-09-04 01:03:18 +00002210 def findBuiltClang(self):
2211 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2212 paths_to_try = [
2213 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2214 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2215 "llvm-build/Release/x86_64/Release/bin/clang",
2216 "llvm-build/Debug/x86_64/Debug/bin/clang",
2217 ]
Enrico Granata55d99f02015-11-19 21:45:07 +00002218 lldb_root_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
Kuba Breckabeed8212014-09-04 01:03:18 +00002219 for p in paths_to_try:
2220 path = os.path.join(lldb_root_path, p)
2221 if os.path.exists(path):
2222 return path
Ilia Kd9953052015-03-12 07:19:41 +00002223
2224 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002225 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002226 if os.path.exists(path):
2227 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002228
2229 return os.environ["CC"]
2230
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002231 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002232 """ Returns a dictionary (which can be provided to build* functions above) which
2233 contains OS-specific build flags.
2234 """
2235 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002236 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002237
2238 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002239 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002240 use_libcxx = True
2241
2242 if use_libcxx and self.libcxxPath:
2243 cflags += "-stdlib=libc++ "
2244 if self.libcxxPath:
2245 libcxxInclude = os.path.join(self.libcxxPath, "include")
2246 libcxxLib = os.path.join(self.libcxxPath, "lib")
2247 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2248 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2249
Andrew Kaylor93132f52013-05-28 23:04:25 +00002250 if use_cpp11:
2251 cflags += "-std="
2252 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2253 cflags += "c++0x"
2254 else:
2255 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002256 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002257 cflags += " -stdlib=libc++"
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002258 elif self.getPlatform() == "netbsd":
2259 cflags += " -stdlib=libstdc++"
Andrew Kaylor93132f52013-05-28 23:04:25 +00002260 elif "clang" in self.getCompiler():
2261 cflags += " -stdlib=libstdc++"
2262
Andrew Kaylor93132f52013-05-28 23:04:25 +00002263 return {'CFLAGS_EXTRAS' : cflags,
2264 'LD_EXTRAS' : ldflags,
2265 }
2266
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002267 def cleanup(self, dictionary=None):
2268 """Platform specific way to do cleanup after build."""
Zachary Turner606e3a52015-12-08 01:15:30 +00002269 if configuration.skip_build_and_cleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00002270 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002271 module = builder_module()
2272 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002273 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002274
Daniel Malea55faa402013-05-02 21:44:31 +00002275 def getLLDBLibraryEnvVal(self):
2276 """ Returns the path that the OS-specific library search environment variable
2277 (self.dylibPath) should be set to in order for a program to find the LLDB
2278 library. If an environment variable named self.dylibPath is already set,
2279 the new path is appended to it and returned.
2280 """
2281 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002282 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002283 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002284 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002285 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002286 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002287 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002288 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002289
Ed Maste437f8f62013-09-09 14:04:04 +00002290 def getLibcPlusPlusLibs(self):
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002291 if self.getPlatform() in ('freebsd', 'linux', 'netbsd'):
Ed Maste437f8f62013-09-09 14:04:04 +00002292 return ['libc++.so.1']
2293 else:
2294 return ['libc++.1.dylib','libc++abi.dylib']
2295
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002296# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2297# We change the test methods to create a new test method for each test for each debug info we are
2298# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2299# the new test method we remove the old method at the same time.
2300class LLDBTestCaseFactory(type):
2301 def __new__(cls, name, bases, attrs):
2302 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002303 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002304 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2305 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002306 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002307 def dsym_test_method(self, attrvalue=attrvalue):
2308 self.debug_info = "dsym"
2309 return attrvalue(self)
2310 dsym_method_name = attrname + "_dsym"
2311 dsym_test_method.__name__ = dsym_method_name
2312 newattrs[dsym_method_name] = dsym_test_method
2313
2314 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002315 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002316 def dwarf_test_method(self, attrvalue=attrvalue):
2317 self.debug_info = "dwarf"
2318 return attrvalue(self)
2319 dwarf_method_name = attrname + "_dwarf"
2320 dwarf_test_method.__name__ = dwarf_method_name
2321 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002322
2323 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002324 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002325 def dwo_test_method(self, attrvalue=attrvalue):
2326 self.debug_info = "dwo"
2327 return attrvalue(self)
2328 dwo_method_name = attrname + "_dwo"
2329 dwo_test_method.__name__ = dwo_method_name
2330 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002331 else:
2332 newattrs[attrname] = attrvalue
2333 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2334
Zachary Turner43a01e42015-10-20 21:06:05 +00002335# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2336@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002337class TestBase(Base):
2338 """
2339 This abstract base class is meant to be subclassed. It provides default
2340 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2341 among other things.
2342
2343 Important things for test class writers:
2344
2345 - Overwrite the mydir class attribute, otherwise your test class won't
2346 run. It specifies the relative directory to the top level 'test' so
2347 the test harness can change to the correct working directory before
2348 running your test.
2349
2350 - The setUp method sets up things to facilitate subsequent interactions
2351 with the debugger as part of the test. These include:
2352 - populate the test method name
2353 - create/get a debugger set with synchronous mode (self.dbg)
2354 - get the command interpreter from with the debugger (self.ci)
2355 - create a result object for use with the command interpreter
2356 (self.res)
2357 - plus other stuffs
2358
2359 - The tearDown method tries to perform some necessary cleanup on behalf
2360 of the test to return the debugger to a good state for the next test.
2361 These include:
2362 - execute any tearDown hooks registered by the test method with
2363 TestBase.addTearDownHook(); examples can be found in
2364 settings/TestSettings.py
2365 - kill the inferior process associated with each target, if any,
2366 and, then delete the target from the debugger's target list
2367 - perform build cleanup before running the next test method in the
2368 same test class; examples of registering for this service can be
2369 found in types/TestIntegerTypes.py with the call:
2370 - self.setTearDownCleanup(dictionary=d)
2371
2372 - Similarly setUpClass and tearDownClass perform classwise setup and
2373 teardown fixtures. The tearDownClass method invokes a default build
2374 cleanup for the entire test class; also, subclasses can implement the
2375 classmethod classCleanup(cls) to perform special class cleanup action.
2376
2377 - The instance methods runCmd and expect are used heavily by existing
2378 test cases to send a command to the command interpreter and to perform
2379 string/pattern matching on the output of such command execution. The
2380 expect method also provides a mode to peform string/pattern matching
2381 without running a command.
2382
2383 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2384 build the binaries used during a particular test scenario. A plugin
2385 should be provided for the sys.platform running the test suite. The
2386 Mac OS X implementation is located in plugins/darwin.py.
2387 """
2388
2389 # Maximum allowed attempts when launching the inferior process.
2390 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2391 maxLaunchCount = 3;
2392
2393 # Time to wait before the next launching attempt in second(s).
2394 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2395 timeWaitNextLaunch = 1.0;
2396
2397 def doDelay(self):
2398 """See option -w of dotest.py."""
2399 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
2400 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
2401 waitTime = 1.0
2402 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
2403 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
2404 time.sleep(waitTime)
2405
Enrico Granata165f8af2012-09-21 19:10:53 +00002406 # Returns the list of categories to which this test case belongs
2407 # by default, look for a ".categories" file, and read its contents
2408 # if no such file exists, traverse the hierarchy - we guarantee
2409 # a .categories to exist at the top level directory so we do not end up
2410 # looping endlessly - subclasses are free to define their own categories
2411 # in whatever way makes sense to them
2412 def getCategories(self):
2413 import inspect
2414 import os.path
2415 folder = inspect.getfile(self.__class__)
2416 folder = os.path.dirname(folder)
2417 while folder != '/':
2418 categories_file_name = os.path.join(folder,".categories")
2419 if os.path.exists(categories_file_name):
2420 categories_file = open(categories_file_name,'r')
2421 categories = categories_file.readline()
2422 categories_file.close()
2423 categories = str.replace(categories,'\n','')
2424 categories = str.replace(categories,'\r','')
2425 return categories.split(',')
2426 else:
2427 folder = os.path.dirname(folder)
2428 continue
2429
Johnny Chena74bb0a2011-08-01 18:46:13 +00002430 def setUp(self):
2431 #import traceback
2432 #traceback.print_stack()
2433
2434 # Works with the test driver to conditionally skip tests via decorators.
2435 Base.setUp(self)
2436
Johnny Chena74bb0a2011-08-01 18:46:13 +00002437 try:
Zachary Turner606e3a52015-12-08 01:15:30 +00002438 blacklist = configuration.blacklist
2439 if blacklist:
Johnny Chena74bb0a2011-08-01 18:46:13 +00002440 className = self.__class__.__name__
2441 classAndMethodName = "%s.%s" % (className, self._testMethodName)
Zachary Turner606e3a52015-12-08 01:15:30 +00002442 if className in blacklist:
2443 self.skipTest(blacklist.get(className))
2444 elif classAndMethodName in blacklist:
2445 self.skipTest(blacklist.get(classAndMethodName))
Johnny Chena74bb0a2011-08-01 18:46:13 +00002446 except AttributeError:
2447 pass
2448
Johnny Chened492022011-06-21 00:53:00 +00002449 # Insert some delay between successive test cases if specified.
2450 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00002451
Johnny Chenf2b70232010-08-25 18:49:48 +00002452 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2453 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2454
Johnny Chen430eb762010-10-19 16:00:42 +00002455 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002456 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002457
Daniel Maleae0f8f572013-08-26 23:57:52 +00002458 #
2459 # Warning: MAJOR HACK AHEAD!
2460 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
2461 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
2462 # command, instead. See also runCmd() where it decorates the "file filename" call
2463 # with additional functionality when running testsuite remotely.
2464 #
Zachary Turner606e3a52015-12-08 01:15:30 +00002465 if configuration.lldbtest_remote_sandbox:
Daniel Maleae0f8f572013-08-26 23:57:52 +00002466 def DecoratedCreateTarget(arg):
2467 self.runCmd("file %s" % arg)
2468 target = self.dbg.GetSelectedTarget()
2469 #
Greg Claytonc6947512013-12-13 19:18:59 +00002470 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00002471 # johnny @ 04/23/2012
2472 #
2473 def DecoratedLaunchSimple(argv, envp, wd):
2474 self.runCmd("run")
2475 return target.GetProcess()
2476 target.LaunchSimple = DecoratedLaunchSimple
2477
2478 return target
2479 self.dbg.CreateTarget = DecoratedCreateTarget
2480 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002481 print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
Daniel Maleae0f8f572013-08-26 23:57:52 +00002482
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002483 # We want our debugger to be synchronous.
2484 self.dbg.SetAsync(False)
2485
2486 # Retrieve the associated command interpreter instance.
2487 self.ci = self.dbg.GetCommandInterpreter()
2488 if not self.ci:
2489 raise Exception('Could not get the command interpreter')
2490
2491 # And the result object.
2492 self.res = lldb.SBCommandReturnObject()
2493
Johnny Chen44d24972012-04-16 18:55:15 +00002494 # Run global pre-flight code, if defined via the config file.
Zachary Turner606e3a52015-12-08 01:15:30 +00002495 if configuration.pre_flight:
2496 configuration.pre_flight(self)
Johnny Chen44d24972012-04-16 18:55:15 +00002497
Zachary Turner606e3a52015-12-08 01:15:30 +00002498 if lldb.remote_platform and configuration.lldb_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002499 remote_test_dir = lldbutil.join_remote_paths(
Zachary Turner606e3a52015-12-08 01:15:30 +00002500 configuration.lldb_platform_working_dir,
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002501 self.getArchitecture(),
2502 str(self.test_number),
2503 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002504 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002505 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002506 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002507
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002508 # This function removes all files from the current working directory while leaving
2509 # the directories in place. The cleaup is required to reduce the disk space required
2510 # by the test suit while leaving the directories untached is neccessary because
2511 # sub-directories might belong to an other test
2512 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002513 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002514 # TODO: Replace the heuristic to remove the files with a logic what collects the
2515 # list of files we have to remove during test runs.
2516 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002517 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002518 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002519 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002520 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002521
Greg Clayton35c91342014-11-17 18:40:27 +00002522 def registerSharedLibrariesWithTarget(self, target, shlibs):
2523 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2524
2525 Any modules in the target that have their remote install file specification set will
2526 get uploaded to the remote host. This function registers the local copies of the
2527 shared libraries with the target and sets their remote install locations so they will
2528 be uploaded when the target is run.
2529 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002530 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002531 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002532
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002533 shlib_environment_var = self.platformContext.shlib_environment_var
2534 shlib_prefix = self.platformContext.shlib_prefix
2535 shlib_extension = '.' + self.platformContext.shlib_extension
2536
2537 working_dir = self.get_process_working_directory()
2538 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2539 # Add any shared libraries to our target if remote so they get
2540 # uploaded into the working directory on the remote side
2541 for name in shlibs:
2542 # The path can be a full path to a shared library, or a make file name like "Foo" for
2543 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2544 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2545 # of the shared library accordingly
2546 if os.path.exists(name):
2547 local_shlib_path = name # name is the full path to the local shared library
2548 else:
2549 # Check relative names
2550 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2551 if not os.path.exists(local_shlib_path):
2552 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002553 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002554 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002555
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002556 # Make sure we found the local shared library in the above code
2557 self.assertTrue(os.path.exists(local_shlib_path))
2558
2559 # Add the shared library to our target
2560 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2561 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002562 # We must set the remote install location if we want the shared library
2563 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002564 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002565 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002566
2567 return environment
2568
Enrico Granata44818162012-10-24 01:23:57 +00002569 # utility methods that tests can use to access the current objects
2570 def target(self):
2571 if not self.dbg:
2572 raise Exception('Invalid debugger instance')
2573 return self.dbg.GetSelectedTarget()
2574
2575 def process(self):
2576 if not self.dbg:
2577 raise Exception('Invalid debugger instance')
2578 return self.dbg.GetSelectedTarget().GetProcess()
2579
2580 def thread(self):
2581 if not self.dbg:
2582 raise Exception('Invalid debugger instance')
2583 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2584
2585 def frame(self):
2586 if not self.dbg:
2587 raise Exception('Invalid debugger instance')
2588 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2589
Greg Claytonc6947512013-12-13 19:18:59 +00002590 def get_process_working_directory(self):
2591 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2592 if lldb.remote_platform:
2593 # Remote tests set the platform working directory up in TestBase.setUp()
2594 return lldb.remote_platform.GetWorkingDirectory()
2595 else:
2596 # local tests change directory into each test subdirectory
2597 return os.getcwd()
2598
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002599 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002600 #import traceback
2601 #traceback.print_stack()
2602
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002603 # Ensure all the references to SB objects have gone away so that we can
2604 # be sure that all test-specific resources have been freed before we
2605 # attempt to delete the targets.
2606 gc.collect()
2607
Johnny Chen3794ad92011-06-15 21:24:24 +00002608 # Delete the target(s) from the debugger as a general cleanup step.
2609 # This includes terminating the process for each target, if any.
2610 # We'd like to reuse the debugger for our next test without incurring
2611 # the initialization overhead.
2612 targets = []
2613 for target in self.dbg:
2614 if target:
2615 targets.append(target)
2616 process = target.GetProcess()
2617 if process:
2618 rc = self.invoke(process, "Kill")
2619 self.assertTrue(rc.Success(), PROCESS_KILLED)
2620 for target in targets:
2621 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002622
Johnny Chen44d24972012-04-16 18:55:15 +00002623 # Run global post-flight code, if defined via the config file.
Zachary Turner606e3a52015-12-08 01:15:30 +00002624 if configuration.post_flight:
2625 configuration.post_flight(self)
Johnny Chen44d24972012-04-16 18:55:15 +00002626
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002627 # Do this last, to make sure it's in reverse order from how we setup.
2628 Base.tearDown(self)
2629
Zachary Turner95812042015-03-26 18:54:21 +00002630 # This must be the last statement, otherwise teardown hooks or other
2631 # lines might depend on this still being active.
2632 del self.dbg
2633
Johnny Chen86268e42011-09-30 21:48:35 +00002634 def switch_to_thread_with_stop_reason(self, stop_reason):
2635 """
2636 Run the 'thread list' command, and select the thread with stop reason as
2637 'stop_reason'. If no such thread exists, no select action is done.
2638 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002639 from .lldbutil import stop_reason_to_str
Johnny Chen86268e42011-09-30 21:48:35 +00002640 self.runCmd('thread list')
2641 output = self.res.GetOutput()
2642 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2643 stop_reason_to_str(stop_reason))
2644 for line in output.splitlines():
2645 matched = thread_line_pattern.match(line)
2646 if matched:
2647 self.runCmd('thread select %s' % matched.group(1))
2648
Enrico Granata7594f142013-06-17 22:51:50 +00002649 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002650 """
2651 Ask the command interpreter to handle the command and then check its
2652 return status.
2653 """
2654 # Fail fast if 'cmd' is not meaningful.
2655 if not cmd or len(cmd) == 0:
2656 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002657
Johnny Chen8d55a342010-08-31 17:42:54 +00002658 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002659
Daniel Maleae0f8f572013-08-26 23:57:52 +00002660 # This is an opportunity to insert the 'platform target-install' command if we are told so
2661 # via the settig of lldb.lldbtest_remote_sandbox.
2662 if cmd.startswith("target create "):
2663 cmd = cmd.replace("target create ", "file ")
Zachary Turner606e3a52015-12-08 01:15:30 +00002664 if cmd.startswith("file ") and configuration.lldbtest_remote_sandbox:
Daniel Maleae0f8f572013-08-26 23:57:52 +00002665 with recording(self, trace) as sbuf:
2666 the_rest = cmd.split("file ")[1]
2667 # Split the rest of the command line.
2668 atoms = the_rest.split()
2669 #
2670 # NOTE: This assumes that the options, if any, follow the file command,
2671 # instead of follow the specified target.
2672 #
2673 target = atoms[-1]
2674 # Now let's get the absolute pathname of our target.
2675 abs_target = os.path.abspath(target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002676 print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002677 fpath, fname = os.path.split(abs_target)
2678 parent_dir = os.path.split(fpath)[0]
Zachary Turner606e3a52015-12-08 01:15:30 +00002679 platform_target_install_command = 'platform target-install %s %s' % (fpath, configuration.lldbtest_remote_sandbox)
Zachary Turnerff890da2015-10-19 23:45:41 +00002680 print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002681 self.ci.HandleCommand(platform_target_install_command, self.res)
2682 # And this is the file command we want to execute, instead.
2683 #
2684 # Warning: SIDE EFFECT AHEAD!!!
2685 # Populate the remote executable pathname into the lldb namespace,
2686 # so that test cases can grab this thing out of the namespace.
2687 #
Zachary Turner606e3a52015-12-08 01:15:30 +00002688 remote_sandboxed_executable = abs_target.replace(parent_dir, configuration.lldbtest_remote_sandbox)
2689 cmd = "file -P %s %s %s" % (remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002690 print("And this is the replaced file command: %s" % cmd, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002691
Johnny Chen63dfb272010-09-01 00:15:19 +00002692 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002693
Johnny Chen63dfb272010-09-01 00:15:19 +00002694 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002695 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002696
Johnny Chen150c3cc2010-10-15 01:18:29 +00002697 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002698 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002699 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002700 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002701 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002702 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002703 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002704 print("runCmd failed!", file=sbuf)
2705 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002706
Johnny Chenff3d01d2010-08-20 21:03:09 +00002707 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002708 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002709 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002710 # For process launch, wait some time before possible next try.
2711 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002712 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002713 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002714
Johnny Chen27f212d2010-08-19 23:26:59 +00002715 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002716 self.assertTrue(self.res.Succeeded(),
2717 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002718
Jim Ingham63dfc722012-09-22 00:05:11 +00002719 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2720 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2721
2722 Otherwise, all the arguments have the same meanings as for the expect function"""
2723
2724 trace = (True if traceAlways else trace)
2725
2726 if exe:
2727 # First run the command. If we are expecting error, set check=False.
2728 # Pass the assert message along since it provides more semantic info.
2729 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2730
2731 # Then compare the output against expected strings.
2732 output = self.res.GetError() if error else self.res.GetOutput()
2733
2734 # If error is True, the API client expects the command to fail!
2735 if error:
2736 self.assertFalse(self.res.Succeeded(),
2737 "Command '" + str + "' is expected to fail!")
2738 else:
2739 # No execution required, just compare str against the golden input.
2740 output = str
2741 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002742 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002743
2744 # The heading says either "Expecting" or "Not expecting".
2745 heading = "Expecting" if matching else "Not expecting"
2746
2747 for pattern in patterns:
2748 # Match Objects always have a boolean value of True.
2749 match_object = re.search(pattern, output)
2750 matched = bool(match_object)
2751 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002752 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2753 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002754 if matched:
2755 break
2756
2757 self.assertTrue(matched if matching else not matched,
2758 msg if msg else EXP_MSG(str, exe))
2759
2760 return match_object
2761
Enrico Granata7594f142013-06-17 22:51:50 +00002762 def expect(self, str, msg=None, patterns=None, startstr=None, endstr=None, substrs=None, trace=False, error=False, matching=True, exe=True, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002763 """
2764 Similar to runCmd; with additional expect style output matching ability.
2765
2766 Ask the command interpreter to handle the command and then check its
2767 return status. The 'msg' parameter specifies an informational assert
2768 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002769 'startstr', matches the substrings contained in 'substrs', and regexp
2770 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002771
2772 If the keyword argument error is set to True, it signifies that the API
2773 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002774 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002775 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002776
2777 If the keyword argument matching is set to False, it signifies that the API
2778 client is expecting the output of the command not to match the golden
2779 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002780
2781 Finally, the required argument 'str' represents the lldb command to be
2782 sent to the command interpreter. In case the keyword argument 'exe' is
2783 set to False, the 'str' is treated as a string to be matched/not-matched
2784 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002785 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002786 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002787
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002788 if exe:
2789 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002790 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002791 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002792
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002793 # Then compare the output against expected strings.
2794 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002795
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002796 # If error is True, the API client expects the command to fail!
2797 if error:
2798 self.assertFalse(self.res.Succeeded(),
2799 "Command '" + str + "' is expected to fail!")
2800 else:
2801 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002802 if isinstance(str,lldb.SBCommandReturnObject):
2803 output = str.GetOutput()
2804 else:
2805 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002806 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002807 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002808
Johnny Chenea88e942010-09-21 21:08:53 +00002809 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002810 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002811
2812 # Start from the startstr, if specified.
2813 # If there's no startstr, set the initial state appropriately.
2814 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002815
Johnny Chen150c3cc2010-10-15 01:18:29 +00002816 if startstr:
2817 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002818 print("%s start string: %s" % (heading, startstr), file=sbuf)
2819 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002820
Johnny Chen86268e42011-09-30 21:48:35 +00002821 # Look for endstr, if specified.
2822 keepgoing = matched if matching else not matched
2823 if endstr:
2824 matched = output.endswith(endstr)
2825 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002826 print("%s end string: %s" % (heading, endstr), file=sbuf)
2827 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002828
Johnny Chenea88e942010-09-21 21:08:53 +00002829 # Look for sub strings, if specified.
2830 keepgoing = matched if matching else not matched
2831 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002832 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002833 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002834 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002835 print("%s sub string: %s" % (heading, str), file=sbuf)
2836 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002837 keepgoing = matched if matching else not matched
2838 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002839 break
2840
Johnny Chenea88e942010-09-21 21:08:53 +00002841 # Search for regular expression patterns, if specified.
2842 keepgoing = matched if matching else not matched
2843 if patterns and keepgoing:
2844 for pattern in patterns:
2845 # Match Objects always have a boolean value of True.
2846 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002847 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002848 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2849 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002850 keepgoing = matched if matching else not matched
2851 if not keepgoing:
2852 break
Johnny Chenea88e942010-09-21 21:08:53 +00002853
2854 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002855 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002856
Johnny Chenf3c59232010-08-25 22:52:45 +00002857 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002858 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002859 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002860
2861 method = getattr(obj, name)
2862 import inspect
2863 self.assertTrue(inspect.ismethod(method),
2864 name + "is a method name of object: " + str(obj))
2865 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002866 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002867 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002868 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002869
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002870 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2871 """Platform specific way to build the default binaries."""
Zachary Turner606e3a52015-12-08 01:15:30 +00002872 if configuration.skip_build_and_cleanup:
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002873 return
2874 module = builder_module()
2875 if target_is_android():
2876 dictionary = append_android_envs(dictionary)
2877 if self.debug_info is None:
2878 return self.buildDefault(architecture, compiler, dictionary, clean)
2879 elif self.debug_info == "dsym":
2880 return self.buildDsym(architecture, compiler, dictionary, clean)
2881 elif self.debug_info == "dwarf":
2882 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002883 elif self.debug_info == "dwo":
2884 return self.buildDwo(architecture, compiler, dictionary, clean)
2885 else:
2886 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002887
Johnny Chenf359cf22011-05-27 23:36:52 +00002888 # =================================================
2889 # Misc. helper methods for debugging test execution
2890 # =================================================
2891
Johnny Chen56b92a72011-07-11 19:15:11 +00002892 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002893 """Debug print a SBValue object, if traceAlways is True."""
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002894 from .lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002895
Johnny Chen8d55a342010-08-31 17:42:54 +00002896 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002897 return
2898
2899 err = sys.stderr
2900 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002901 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2902 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2903 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2904 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2905 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2906 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2907 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2908 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2909 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002910
Johnny Chen36c5eb12011-08-05 20:17:27 +00002911 def DebugSBType(self, type):
2912 """Debug print a SBType object, if traceAlways is True."""
2913 if not traceAlways:
2914 return
2915
2916 err = sys.stderr
2917 err.write(type.GetName() + ":\n")
2918 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2919 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2920 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2921
Johnny Chenb877f1e2011-03-12 01:18:19 +00002922 def DebugPExpect(self, child):
2923 """Debug the spwaned pexpect object."""
2924 if not traceAlways:
2925 return
2926
Zachary Turnerff890da2015-10-19 23:45:41 +00002927 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002928
2929 @classmethod
2930 def RemoveTempFile(cls, file):
2931 if os.path.exists(file):
2932 os.remove(file)