blob: bd2dceb32599a60d0fdb85bd9b1e6a518d9b2334 [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
61from . import lldbtest_config
62from . import lldbutil
63from . import test_categories
Siva Chandra8af91662015-06-05 00:22:49 +000064
Vince Harron85d19652015-05-21 19:09:29 +000065# dosep.py starts lots and lots of dotest instances
66# This option helps you find if two (or more) dotest instances are using the same
67# directory at the same time
68# Enable it to cause test failures and stderr messages if dotest instances try to run in
69# the same directory simultaneously
70# it is disabled by default because it litters the test directories with ".dirlock" files
71debug_confirm_directory_exclusivity = False
72
Johnny Chen707b3c92010-10-11 22:25:46 +000073# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000074# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000075
76# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000077if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
78 traceAlways = True
79else:
80 traceAlways = False
81
Johnny Chen707b3c92010-10-11 22:25:46 +000082# By default, doCleanup is True.
83if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
84 doCleanup = False
85else:
86 doCleanup = True
87
Johnny Chen8d55a342010-08-31 17:42:54 +000088
Johnny Chen00778092010-08-09 22:01:17 +000089#
90# Some commonly used assert messages.
91#
92
Johnny Chenaa902922010-09-17 22:45:27 +000093COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
94
Johnny Chen00778092010-08-09 22:01:17 +000095CURRENT_EXECUTABLE_SET = "Current executable set successfully"
96
Johnny Chen7d1d7532010-09-02 21:23:12 +000097PROCESS_IS_VALID = "Process is valid"
98
99PROCESS_KILLED = "Process is killed successfully"
100
Johnny Chend5f66fc2010-12-23 01:12:19 +0000101PROCESS_EXITED = "Process exited successfully"
102
103PROCESS_STOPPED = "Process status should be stopped"
104
Sean Callanan05834cd2015-07-01 23:56:30 +0000105RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000106
Johnny Chen17941842010-08-09 23:44:24 +0000107RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000108
Johnny Chen67af43f2010-10-05 19:27:32 +0000109BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
110
Johnny Chen17941842010-08-09 23:44:24 +0000111BREAKPOINT_CREATED = "Breakpoint created successfully"
112
Johnny Chenf10af382010-12-04 00:07:24 +0000113BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
114
Johnny Chene76896c2010-08-17 21:33:31 +0000115BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
116
Johnny Chen17941842010-08-09 23:44:24 +0000117BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000118
Johnny Chen703dbd02010-09-30 17:06:24 +0000119BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
120
Johnny Chen164f1e12010-10-15 18:07:09 +0000121BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
122
Greg Clayton5db6b792012-10-24 18:24:14 +0000123MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
124
Johnny Chen89109ed12011-06-27 20:05:23 +0000125OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
126
Johnny Chen5b3a3572010-12-09 18:22:12 +0000127SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
128
Johnny Chenc70b02a2010-09-22 23:00:20 +0000129STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
130
Johnny Chen1691a162011-04-15 16:44:48 +0000131STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
132
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000133STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
134
Johnny Chen5d6c4642010-11-10 23:46:38 +0000135STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000136
Johnny Chen5d6c4642010-11-10 23:46:38 +0000137STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
138 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000139
Johnny Chen2e431ce2010-10-20 18:38:48 +0000140STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
141
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000142STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
143
Johnny Chenc066ab42010-10-14 01:22:03 +0000144STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
145
Johnny Chen00778092010-08-09 22:01:17 +0000146STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
147
Johnny Chenf68cc122011-09-15 21:09:59 +0000148STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
149
Johnny Chen3c884a02010-08-24 22:07:56 +0000150DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
151
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000152VALID_BREAKPOINT = "Got a valid breakpoint"
153
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000154VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
155
Johnny Chen7209d84f2011-05-06 23:26:12 +0000156VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
157
Johnny Chen5ee88192010-08-27 23:47:36 +0000158VALID_FILESPEC = "Got a valid filespec"
159
Johnny Chen025d1b82010-12-08 01:25:21 +0000160VALID_MODULE = "Got a valid module"
161
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000162VALID_PROCESS = "Got a valid process"
163
Johnny Chen025d1b82010-12-08 01:25:21 +0000164VALID_SYMBOL = "Got a valid symbol"
165
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000166VALID_TARGET = "Got a valid target"
167
Matthew Gardinerc928de32014-10-22 07:22:56 +0000168VALID_PLATFORM = "Got a valid platform"
169
Johnny Chen15f247a2012-02-03 20:43:00 +0000170VALID_TYPE = "Got a valid type"
171
Johnny Chen5819ab42011-07-15 22:28:10 +0000172VALID_VARIABLE = "Got a valid variable"
173
Johnny Chen981463d2010-08-25 19:00:04 +0000174VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000175
Johnny Chenf68cc122011-09-15 21:09:59 +0000176WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000177
Sean Callanan05834cd2015-07-01 23:56:30 +0000178def CMD_MSG(str):
179 '''A generic "Command '%s' returns successfully" message generator.'''
180 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000181
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000182def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000183 '''A generic message generator for the completion mechanism.'''
184 return "'%s' successfully completes to '%s'" % (str_before, str_after)
185
Johnny Chenc0c67f22010-11-09 18:42:22 +0000186def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000187 '''A generic "'%s' returns expected result" message generator if exe.
188 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000189 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000190
Johnny Chen3343f042010-10-19 19:11:38 +0000191def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000192 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000193 return "Value of setting '%s' is correct" % setting
194
Johnny Chen27c41232010-08-26 21:49:29 +0000195def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000196 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000197 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000198
Johnny Chen47ceb032010-10-11 23:52:19 +0000199def line_number(filename, string_to_match):
200 """Helper function to return the line number of the first matched string."""
201 with open(filename, 'r') as f:
202 for i, line in enumerate(f):
203 if line.find(string_to_match) != -1:
204 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000205 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000206 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000207
Johnny Chen67af43f2010-10-05 19:27:32 +0000208def pointer_size():
209 """Return the pointer size of the host system."""
210 import ctypes
211 a_pointer = ctypes.c_void_p(0xffff)
212 return 8 * ctypes.sizeof(a_pointer)
213
Johnny Chen57816732012-02-09 02:01:59 +0000214def is_exe(fpath):
215 """Returns true if fpath is an executable."""
216 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
217
218def which(program):
219 """Returns the full path to a program; None otherwise."""
220 fpath, fname = os.path.split(program)
221 if fpath:
222 if is_exe(program):
223 return program
224 else:
225 for path in os.environ["PATH"].split(os.pathsep):
226 exe_file = os.path.join(path, program)
227 if is_exe(exe_file):
228 return exe_file
229 return None
230
Zachary Turner814236d2015-10-21 17:48:52 +0000231class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000232 """
233 A nice little context manager for recording the debugger interactions into
234 our session object. If trace flag is ON, it also emits the interactions
235 into the stderr.
236 """
237 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000238 """Create a SixStringIO instance; record the session obj and trace flag."""
239 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000240 # The test might not have undergone the 'setUp(self)' phase yet, so that
241 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000242 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000243 self.trace = trace
244
245 def __enter__(self):
246 """
247 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000248 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000249 """
250 return self
251
252 def __exit__(self, type, value, tb):
253 """
254 Context management protocol on exit from the body of the with statement.
255 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000256 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000257 """
258 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000259 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000260 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000261 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000262 self.close()
263
Zachary Turner43a01e42015-10-20 21:06:05 +0000264@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000265class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000266
267 @abc.abstractproperty
268 def pid(self):
269 """Returns process PID if has been launched already."""
270
271 @abc.abstractmethod
272 def launch(self, executable, args):
273 """Launches new process with given executable and args."""
274
275 @abc.abstractmethod
276 def terminate(self):
277 """Terminates previously launched process.."""
278
279class _LocalProcess(_BaseProcess):
280
281 def __init__(self, trace_on):
282 self._proc = None
283 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000284 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000285
286 @property
287 def pid(self):
288 return self._proc.pid
289
290 def launch(self, executable, args):
291 self._proc = Popen([executable] + args,
292 stdout = open(os.devnull) if not self._trace_on else None,
293 stdin = PIPE)
294
295 def terminate(self):
296 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000297 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000298 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
299 for sig in signals_to_try:
300 try:
301 self._proc.send_signal(getattr(signal, sig))
302 time.sleep(self._delayafterterminate)
303 if self._proc.poll() != None:
304 return
305 except ValueError:
306 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000307 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000308 time.sleep(self._delayafterterminate)
309 if self._proc.poll() != None:
310 return
311 self._proc.kill()
312 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000313
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000314 def poll(self):
315 return self._proc.poll()
316
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000317class _RemoteProcess(_BaseProcess):
318
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000319 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000320 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000321 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000322
323 @property
324 def pid(self):
325 return self._pid
326
327 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000328 if self._install_remote:
329 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000330 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000331
332 dst_file_spec = lldb.SBFileSpec(dst_path, False)
333 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
334 if err.Fail():
335 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
336 else:
337 dst_path = executable
338 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000339
340 launch_info = lldb.SBLaunchInfo(args)
341 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000342 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000343
344 # Redirect stdout and stderr to /dev/null
345 launch_info.AddSuppressFileAction(1, False, True)
346 launch_info.AddSuppressFileAction(2, False, True)
347
348 err = lldb.remote_platform.Launch(launch_info)
349 if err.Fail():
350 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
351 self._pid = launch_info.GetProcessID()
352
353 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000354 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000355
Johnny Chen690fcef2010-10-15 23:55:05 +0000356# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000357# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000358def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000359 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000360
361 If the exit code was non-zero it raises a CalledProcessError. The
362 CalledProcessError object will have the return code in the returncode
363 attribute and output in the output attribute.
364
365 The arguments are the same as for the Popen constructor. Example:
366
367 >>> check_output(["ls", "-l", "/dev/null"])
368 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
369
370 The stdout argument is not allowed as it is used internally.
371 To capture standard error in the result, use stderr=STDOUT.
372
373 >>> check_output(["/bin/sh", "-c",
374 ... "ls -l non_existent_file ; exit 0"],
375 ... stderr=STDOUT)
376 'ls: non_existent_file: No such file or directory\n'
377 """
378
379 # Assign the sender object to variable 'test' and remove it from kwargs.
380 test = kwargs.pop('sender', None)
381
Zachary Turner9ef307b2014-07-22 16:19:29 +0000382 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
383 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000384 output = ""
385 error = ""
386 for shellCommand in commandList:
387 if 'stdout' in kwargs:
388 raise ValueError('stdout argument not allowed, it will be overridden.')
389 if 'shell' in kwargs and kwargs['shell']==False:
390 raise ValueError('shell=False not allowed')
Zachary Turner48ef8d4c2015-11-18 18:40:16 +0000391 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, **kwargs)
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000392 pid = process.pid
393 this_output, this_error = process.communicate()
394 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000395
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000396 # Enable trace on failure return while tracking down FreeBSD buildbot issues
397 trace = traceAlways
398 if not trace and retcode and sys.platform.startswith("freebsd"):
399 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000400
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000401 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000402 print(file=sbuf)
403 print("os command:", shellCommand, file=sbuf)
404 print("with pid:", pid, file=sbuf)
405 print("stdout:", this_output, file=sbuf)
406 print("stderr:", this_error, file=sbuf)
407 print("retcode:", retcode, file=sbuf)
408 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000409
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000410 if retcode:
411 cmd = kwargs.get("args")
412 if cmd is None:
413 cmd = shellCommand
414 raise CalledProcessError(retcode, cmd)
415 output = output + this_output
416 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000417 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000418
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000419def getsource_if_available(obj):
420 """
421 Return the text of the source code for an object if available. Otherwise,
422 a print representation is returned.
423 """
424 import inspect
425 try:
426 return inspect.getsource(obj)
427 except:
428 return repr(obj)
429
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000430def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000431 if sys.platform.startswith("freebsd"):
432 return __import__("builder_freebsd")
Kamil Rytarowski0b655da2015-12-05 18:46:56 +0000433 if sys.platform.startswith("netbsd"):
434 return __import__("builder_netbsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000435 return __import__("builder_" + sys.platform)
436
Siva Chandra8af91662015-06-05 00:22:49 +0000437def run_adb_command(cmd, device_id):
438 device_id_args = []
439 if device_id:
440 device_id_args = ["-s", device_id]
441 full_cmd = ["adb"] + device_id_args + cmd
442 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
443 stdout, stderr = p.communicate()
444 return p.returncode, stdout, stderr
445
Chaoren Line9bbabc2015-07-18 00:37:55 +0000446def append_android_envs(dictionary):
447 if dictionary is None:
448 dictionary = {}
449 dictionary["OS"] = "Android"
450 if android_device_api() >= 16:
451 dictionary["PIE"] = 1
452 return dictionary
453
Chaoren Lin9070f532015-07-17 22:13:29 +0000454def target_is_android():
455 if not hasattr(target_is_android, 'result'):
456 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
457 match = re.match(".*-.*-.*-android", triple)
458 target_is_android.result = match is not None
459 return target_is_android.result
460
Siva Chandra8af91662015-06-05 00:22:49 +0000461def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000462 if not hasattr(android_device_api, 'result'):
463 assert lldb.platform_url is not None
464 device_id = None
465 parsed_url = urlparse.urlparse(lldb.platform_url)
Ying Chenca922bb2015-11-18 19:03:20 +0000466 host_name = parsed_url.netloc.split(":")[0]
467 if host_name != 'localhost':
468 device_id = host_name
469 if device_id.startswith('[') and device_id.endswith(']'):
470 device_id = device_id[1:-1]
Chaoren Lin9070f532015-07-17 22:13:29 +0000471 retcode, stdout, stderr = run_adb_command(
472 ["shell", "getprop", "ro.build.version.sdk"], device_id)
473 if retcode == 0:
474 android_device_api.result = int(stdout)
475 else:
476 raise LookupError(
477 ">>> Unable to determine the API level of the Android device.\n"
478 ">>> stdout:\n%s\n"
479 ">>> stderr:\n%s\n" % (stdout, stderr))
480 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000481
Zachary Turnerabdb8392015-11-16 22:40:30 +0000482def check_expected_version(comparison, expected, actual):
483 def fn_leq(x,y): return x <= y
484 def fn_less(x,y): return x < y
485 def fn_geq(x,y): return x >= y
486 def fn_greater(x,y): return x > y
487 def fn_eq(x,y): return x == y
488 def fn_neq(x,y): return x != y
489
490 op_lookup = {
491 "==": fn_eq,
492 "=": fn_eq,
493 "!=": fn_neq,
494 "<>": fn_neq,
495 ">": fn_greater,
496 "<": fn_less,
497 ">=": fn_geq,
498 "<=": fn_leq
499 }
500 expected_str = '.'.join([str(x) for x in expected])
501 actual_str = '.'.join([str(x) for x in actual])
502
503 return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str))
504
Johnny Chena74bb0a2011-08-01 18:46:13 +0000505#
506# Decorators for categorizing test cases.
507#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000508from functools import wraps
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000509def add_test_categories(cat):
510 """Decorate an item with test categories"""
511 cat = test_categories.validate(cat, True)
512 def impl(func):
513 func.getCategories = lambda test: cat
514 return func
515 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000516
Johnny Chena74bb0a2011-08-01 18:46:13 +0000517def benchmarks_test(func):
518 """Decorate the item as a benchmarks test."""
519 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
520 raise Exception("@benchmarks_test can only be used to decorate a test method")
521 @wraps(func)
522 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000523 if not lldb.just_do_benchmarks_test:
524 self.skipTest("benchmarks tests")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000525 return func(self, *args, **kwargs)
526
527 # Mark this function as such to separate them from the regular tests.
528 wrapper.__benchmarks_test__ = True
529 return wrapper
530
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000531def no_debug_info_test(func):
532 """Decorate the item as a test what don't use any debug info. If this annotation is specified
533 then the test runner won't generate a separate test for each debug info format. """
534 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
535 raise Exception("@no_debug_info_test can only be used to decorate a test method")
536 @wraps(func)
537 def wrapper(self, *args, **kwargs):
538 return func(self, *args, **kwargs)
539
540 # Mark this function as such to separate them from the regular tests.
541 wrapper.__no_debug_info_test__ = True
542 return wrapper
543
Johnny Chenf1548d42012-04-06 00:56:05 +0000544def dsym_test(func):
545 """Decorate the item as a dsym test."""
546 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
547 raise Exception("@dsym_test can only be used to decorate a test method")
548 @wraps(func)
549 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000550 if lldb.dont_do_dsym_test:
551 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000552 return func(self, *args, **kwargs)
553
554 # Mark this function as such to separate them from the regular tests.
555 wrapper.__dsym_test__ = True
556 return wrapper
557
558def dwarf_test(func):
559 """Decorate the item as a dwarf test."""
560 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
561 raise Exception("@dwarf_test can only be used to decorate a test method")
562 @wraps(func)
563 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000564 if lldb.dont_do_dwarf_test:
565 self.skipTest("dwarf tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000566 return func(self, *args, **kwargs)
567
568 # Mark this function as such to separate them from the regular tests.
569 wrapper.__dwarf_test__ = True
570 return wrapper
571
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000572def dwo_test(func):
573 """Decorate the item as a dwo test."""
574 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
575 raise Exception("@dwo_test can only be used to decorate a test method")
576 @wraps(func)
577 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000578 if lldb.dont_do_dwo_test:
579 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000580 return func(self, *args, **kwargs)
581
582 # Mark this function as such to separate them from the regular tests.
583 wrapper.__dwo_test__ = True
584 return wrapper
585
Todd Fialaa41d48c2014-04-28 04:49:40 +0000586def debugserver_test(func):
587 """Decorate the item as a debugserver test."""
588 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
589 raise Exception("@debugserver_test can only be used to decorate a test method")
590 @wraps(func)
591 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000592 if lldb.dont_do_debugserver_test:
593 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000594 return func(self, *args, **kwargs)
595
596 # Mark this function as such to separate them from the regular tests.
597 wrapper.__debugserver_test__ = True
598 return wrapper
599
600def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000601 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000602 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
603 raise Exception("@llgs_test can only be used to decorate a test method")
604 @wraps(func)
605 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000606 if lldb.dont_do_llgs_test:
607 self.skipTest("llgs tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000608 return func(self, *args, **kwargs)
609
610 # Mark this function as such to separate them from the regular tests.
611 wrapper.__llgs_test__ = True
612 return wrapper
613
Daniel Maleae0f8f572013-08-26 23:57:52 +0000614def not_remote_testsuite_ready(func):
615 """Decorate the item as a test which is not ready yet for remote testsuite."""
616 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
617 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
618 @wraps(func)
619 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000620 if lldb.lldbtest_remote_sandbox or lldb.remote_platform:
621 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000622 return func(self, *args, **kwargs)
623
624 # Mark this function as such to separate them from the regular tests.
625 wrapper.__not_ready_for_remote_testsuite_test__ = True
626 return wrapper
627
Ed Maste433790a2014-04-23 12:55:41 +0000628def expectedFailure(expected_fn, bugnumber=None):
629 def expectedFailure_impl(func):
630 @wraps(func)
631 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000632 from unittest2 import case
633 self = args[0]
Ed Maste433790a2014-04-23 12:55:41 +0000634 if expected_fn(self):
Zachary Turner5cb8e672015-11-06 18:14:42 +0000635 xfail_func = unittest2.expectedFailure(func)
636 xfail_func(*args, **kwargs)
637 else:
638 func(*args, **kwargs)
Ed Maste433790a2014-04-23 12:55:41 +0000639 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000640 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
641 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000642 if six.callable(bugnumber):
Ying Chen464d1e12015-03-27 00:26:52 +0000643 return expectedFailure_impl(bugnumber)
644 else:
645 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000646
Ying Chen0c352822015-11-16 23:41:02 +0000647# You can also pass not_in(list) to reverse the sense of the test for the arguments that
648# are simple lists, namely oslist, compiler, and debug_info.
649
650def not_in (iterable):
651 return lambda x : x not in iterable
652
Siva Chandra7dcad312015-11-20 20:30:36 +0000653def check_list_or_lambda (list_or_lambda, value):
654 if six.callable(list_or_lambda):
655 return list_or_lambda(value)
656 else:
657 return list_or_lambda is None or value is None or value in list_or_lambda
Ying Chen0c352822015-11-16 23:41:02 +0000658
Ying Chen7091c2c2015-04-21 01:15:47 +0000659# provide a function to xfail on defined oslist, compiler version, and archs
660# if none is specified for any argument, that argument won't be checked and thus means for all
661# for example,
662# @expectedFailureAll, xfail for all platform/compiler/arch,
663# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
664# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Zachary Turnerabdb8392015-11-16 22:40:30 +0000665def 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 +0000666 def fn(self):
Siva Chandra7dcad312015-11-20 20:30:36 +0000667 oslist_passes = check_list_or_lambda(oslist, self.getPlatform())
668 compiler_passes = check_list_or_lambda(self.getCompiler(), compiler) and self.expectedCompilerVersion(compiler_version)
Zachary Turnerabdb8392015-11-16 22:40:30 +0000669 arch_passes = self.expectedArch(archs)
670 triple_passes = triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())
Siva Chandra7dcad312015-11-20 20:30:36 +0000671 debug_info_passes = check_list_or_lambda(debug_info, self.debug_info)
Zachary Turnerabdb8392015-11-16 22:40:30 +0000672 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))
673 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
674
675 return (oslist_passes and
676 compiler_passes and
677 arch_passes and
678 triple_passes and
679 debug_info_passes and
680 swig_version_passes and
681 py_version_passes)
Ying Chen7091c2c2015-04-21 01:15:47 +0000682 return expectedFailure(fn, bugnumber)
683
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000684def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000685 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
686
687def expectedFailureDwo(bugnumber=None):
688 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000689
690def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000691 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000692
693def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
694 if compiler_version is None:
695 compiler_version=['=', None]
696 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
697
Vince Harron8974ce22015-03-13 19:54:54 +0000698# to XFAIL a specific clang versions, try this
699# @expectedFailureClang('bugnumber', ['<=', '3.4'])
700def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000701 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000702
703def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000704 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000705
Matt Kopec0de53f02013-03-15 19:10:12 +0000706def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000707 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000708
Ed Maste433790a2014-04-23 12:55:41 +0000709def expectedFailureArch(arch, bugnumber=None):
710 def fn(self):
711 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000712 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000713
Enrico Granatae6cedc12013-02-23 01:05:23 +0000714def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000715 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000716
Matt Kopecee969f92013-09-26 23:30:59 +0000717def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000718 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000719
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000720def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000721 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000722 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000723 self.expectedCompiler(compilers) and
724 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000725 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000726
Chaoren Linf7160f32015-06-09 17:39:27 +0000727def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
728 def fn(self):
729 return (getHostPlatform() in oslist and
730 self.expectedCompiler(compilers))
731 return expectedFailure(fn, bugnumber)
732
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000733def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000734 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000735 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000736
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000737def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
738 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000739
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000740def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
741 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000742
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000743def expectedFailureNetBSD(bugnumber=None, compilers=None, debug_info=None):
744 return expectedFailureOS(['netbsd'], bugnumber, compilers, debug_info=debug_info)
745
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000746def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
747 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000748
Chaoren Linf7160f32015-06-09 17:39:27 +0000749def expectedFailureHostWindows(bugnumber=None, compilers=None):
750 return expectedFailureHostOS(['windows'], bugnumber, compilers)
751
Pavel Labath090152b2015-08-20 11:37:19 +0000752def matchAndroid(api_levels=None, archs=None):
753 def match(self):
754 if not target_is_android():
755 return False
756 if archs is not None and self.getArchitecture() not in archs:
757 return False
758 if api_levels is not None and android_device_api() not in api_levels:
759 return False
760 return True
761 return match
762
763
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000764def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000765 """ Mark a test as xfail for Android.
766
767 Arguments:
768 bugnumber - The LLVM pr associated with the problem.
769 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000770 for which a test is expected to fail. None means all API level.
771 arch - A sequence of architecture names specifying the architectures
772 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000773 """
Pavel Labath090152b2015-08-20 11:37:19 +0000774 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000775
Vince Harron7ac3ea42015-06-26 15:13:21 +0000776# if the test passes on the first try, we're done (success)
777# if the test fails once, then passes on the second try, raise an ExpectedFailure
778# if the test fails twice in a row, re-throw the exception from the second test run
779def expectedFlakey(expected_fn, bugnumber=None):
780 def expectedFailure_impl(func):
781 @wraps(func)
782 def wrapper(*args, **kwargs):
783 from unittest2 import case
784 self = args[0]
785 try:
786 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000787 # don't retry if the test case is already decorated with xfail or skip
788 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
789 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000790 except Exception:
791 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000792 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000793 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000794 self.tearDown()
795 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000796 func(*args, **kwargs)
797 except Exception:
798 # oh snap! two failures in a row, record a failure/error
799 raise
800 # record the expected failure
801 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
802 else:
803 raise
804 return wrapper
805 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
806 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000807 if six.callable(bugnumber):
Vince Harron7ac3ea42015-06-26 15:13:21 +0000808 return expectedFailure_impl(bugnumber)
809 else:
810 return expectedFailure_impl
811
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000812def expectedFlakeyDwarf(bugnumber=None):
813 def fn(self):
814 return self.debug_info == "dwarf"
815 return expectedFlakey(fn, bugnumber)
816
817def expectedFlakeyDsym(bugnumber=None):
818 def fn(self):
819 return self.debug_info == "dwarf"
820 return expectedFlakey(fn, bugnumber)
821
Vince Harron7ac3ea42015-06-26 15:13:21 +0000822def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
823 def fn(self):
824 return (self.getPlatform() in oslist and
825 self.expectedCompiler(compilers))
826 return expectedFlakey(fn, bugnumber)
827
828def expectedFlakeyDarwin(bugnumber=None, compilers=None):
829 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
830 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
831
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000832def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
833 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
834
Vince Harron7ac3ea42015-06-26 15:13:21 +0000835def expectedFlakeyLinux(bugnumber=None, compilers=None):
836 return expectedFlakeyOS(['linux'], bugnumber, compilers)
837
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000838def expectedFlakeyNetBSD(bugnumber=None, compilers=None):
839 return expectedFlakeyOS(['netbsd'], bugnumber, compilers)
Vince Harron7ac3ea42015-06-26 15:13:21 +0000840
841def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
842 if compiler_version is None:
843 compiler_version=['=', None]
844 def fn(self):
845 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
846 return expectedFlakey(fn, bugnumber)
847
848# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
849def expectedFlakeyClang(bugnumber=None, compiler_version=None):
850 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
851
852# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
853def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
854 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
855
Pavel Labath63a579c2015-09-07 12:15:27 +0000856def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
857 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
858
Greg Clayton12514562013-12-05 22:22:32 +0000859def skipIfRemote(func):
860 """Decorate the item to skip tests if testing remotely."""
861 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
862 raise Exception("@skipIfRemote can only be used to decorate a test method")
863 @wraps(func)
864 def wrapper(*args, **kwargs):
865 from unittest2 import case
866 if lldb.remote_platform:
867 self = args[0]
868 self.skipTest("skip on remote platform")
869 else:
870 func(*args, **kwargs)
871 return wrapper
872
Siva Chandra4470f382015-06-17 22:32:27 +0000873def skipUnlessListedRemote(remote_list=None):
874 def myImpl(func):
875 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
876 raise Exception("@skipIfRemote can only be used to decorate a "
877 "test method")
878
879 @wraps(func)
880 def wrapper(*args, **kwargs):
881 if remote_list and lldb.remote_platform:
882 self = args[0]
883 triple = self.dbg.GetSelectedPlatform().GetTriple()
884 for r in remote_list:
885 if r in triple:
886 func(*args, **kwargs)
887 return
888 self.skipTest("skip on remote platform %s" % str(triple))
889 else:
890 func(*args, **kwargs)
891 return wrapper
892
893 return myImpl
894
Greg Clayton12514562013-12-05 22:22:32 +0000895def skipIfRemoteDueToDeadlock(func):
896 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
897 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
898 raise Exception("@skipIfRemote can only be used to decorate a test method")
899 @wraps(func)
900 def wrapper(*args, **kwargs):
901 from unittest2 import case
902 if lldb.remote_platform:
903 self = args[0]
904 self.skipTest("skip on remote platform (deadlocks)")
905 else:
906 func(*args, **kwargs)
907 return wrapper
908
Enrico Granatab633e432014-10-06 21:37:06 +0000909def skipIfNoSBHeaders(func):
910 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
911 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000912 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000913 @wraps(func)
914 def wrapper(*args, **kwargs):
915 from unittest2 import case
916 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000917 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000918 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000919 else:
920 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000921 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000922 if not os.path.exists(header):
923 self.skipTest("skip because LLDB.h header not found")
924 else:
925 func(*args, **kwargs)
926 return wrapper
927
Enrico Granata5f92a132015-11-05 00:46:25 +0000928def skipIfiOSSimulator(func):
929 """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
930 return unittest2.skipIf(hasattr(lldb, 'remote_platform_name') and lldb.remote_platform_name == 'ios-simulator', 'skip on the iOS Simulator')(func)
931
Robert Flack13c7ad92015-03-30 14:12:17 +0000932def skipIfFreeBSD(func):
933 """Decorate the item to skip tests that should be skipped on FreeBSD."""
934 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000935
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000936def skipIfNetBSD(func):
937 """Decorate the item to skip tests that should be skipped on NetBSD."""
938 return skipIfPlatform(["netbsd"])(func)
939
Greg Claytone0d0a762015-04-02 18:24:03 +0000940def getDarwinOSTriples():
941 return ['darwin', 'macosx', 'ios']
942
Daniel Maleab3d41a22013-07-09 00:08:01 +0000943def skipIfDarwin(func):
944 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000945 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000946
Robert Flack13c7ad92015-03-30 14:12:17 +0000947def skipIfLinux(func):
948 """Decorate the item to skip tests that should be skipped on Linux."""
949 return skipIfPlatform(["linux"])(func)
950
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000951def skipUnlessHostLinux(func):
952 """Decorate the item to skip tests that should be skipped on any non Linux host."""
953 return skipUnlessHostPlatform(["linux"])(func)
954
Robert Flack13c7ad92015-03-30 14:12:17 +0000955def skipIfWindows(func):
956 """Decorate the item to skip tests that should be skipped on Windows."""
957 return skipIfPlatform(["windows"])(func)
958
Chaoren Line6eea5d2015-06-08 22:13:28 +0000959def skipIfHostWindows(func):
960 """Decorate the item to skip tests that should be skipped on Windows."""
961 return skipIfHostPlatform(["windows"])(func)
962
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000963def skipUnlessWindows(func):
964 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
965 return skipUnlessPlatform(["windows"])(func)
966
Robert Flack13c7ad92015-03-30 14:12:17 +0000967def skipUnlessDarwin(func):
968 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000969 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000970
Ryan Brown57bee1e2015-09-14 22:45:11 +0000971def skipUnlessGoInstalled(func):
972 """Decorate the item to skip tests when no Go compiler is available."""
973 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
974 raise Exception("@skipIfGcc can only be used to decorate a test method")
975 @wraps(func)
976 def wrapper(*args, **kwargs):
977 from unittest2 import case
978 self = args[0]
979 compiler = self.getGoCompilerVersion()
980 if not compiler:
981 self.skipTest("skipping because go compiler not found")
982 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000983 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +0000984 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +0000985 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
986 if not match_version:
987 # Couldn't determine version.
988 self.skipTest(
989 "skipping because go version could not be parsed "
990 "out of {}".format(compiler))
991 else:
992 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +0000993 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +0000994 compiler_strict_version = StrictVersion(match_version.group(1))
995 if compiler_strict_version < min_strict_version:
996 self.skipTest(
997 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +0000998 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +0000999 compiler_strict_version,
1000 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +00001001 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +00001002 return wrapper
1003
Robert Flack068898c2015-04-09 18:07:58 +00001004def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +00001005 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001006 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
1007 if platform.startswith('freebsd'):
1008 platform = 'freebsd'
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001009 elif platform.startswith('netbsd'):
1010 platform = 'netbsd'
Robert Flack068898c2015-04-09 18:07:58 +00001011 return platform
1012
Robert Flack6e1fd352015-05-15 12:39:33 +00001013def getHostPlatform():
1014 """Returns the host platform running the test suite."""
1015 # Attempts to return a platform name matching a target Triple platform.
1016 if sys.platform.startswith('linux'):
1017 return 'linux'
1018 elif sys.platform.startswith('win32'):
1019 return 'windows'
1020 elif sys.platform.startswith('darwin'):
1021 return 'darwin'
1022 elif sys.platform.startswith('freebsd'):
1023 return 'freebsd'
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001024 elif sys.platform.startswith('netbsd'):
1025 return 'netbsd'
Robert Flack6e1fd352015-05-15 12:39:33 +00001026 else:
1027 return sys.platform
1028
Robert Flackfb2f6c62015-04-17 08:02:18 +00001029def platformIsDarwin():
1030 """Returns true if the OS triple for the selected platform is any valid apple OS"""
1031 return getPlatform() in getDarwinOSTriples()
1032
Robert Flack6e1fd352015-05-15 12:39:33 +00001033def skipIfHostIncompatibleWithRemote(func):
1034 """Decorate the item to skip tests if binaries built on this host are incompatible."""
1035 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1036 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
1037 @wraps(func)
1038 def wrapper(*args, **kwargs):
1039 from unittest2 import case
1040 self = args[0]
1041 host_arch = self.getLldbArchitecture()
1042 host_platform = getHostPlatform()
1043 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +00001044 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +00001045 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
1046 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
1047 elif target_platform != host_platform:
1048 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
1049 else:
1050 func(*args, **kwargs)
1051 return wrapper
1052
Chaoren Line6eea5d2015-06-08 22:13:28 +00001053def skipIfHostPlatform(oslist):
1054 """Decorate the item to skip tests if running on one of the listed host platforms."""
1055 return unittest2.skipIf(getHostPlatform() in oslist,
1056 "skip on %s" % (", ".join(oslist)))
1057
1058def skipUnlessHostPlatform(oslist):
1059 """Decorate the item to skip tests unless running on one of the listed host platforms."""
1060 return unittest2.skipUnless(getHostPlatform() in oslist,
1061 "requires on of %s" % (", ".join(oslist)))
1062
Zachary Turner793d9972015-08-14 23:29:24 +00001063def skipUnlessArch(archlist):
1064 """Decorate the item to skip tests unless running on one of the listed architectures."""
1065 def myImpl(func):
1066 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1067 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1068
1069 @wraps(func)
1070 def wrapper(*args, **kwargs):
1071 self = args[0]
1072 if self.getArchitecture() not in archlist:
1073 self.skipTest("skipping for architecture %s (requires one of %s)" %
1074 (self.getArchitecture(), ", ".join(archlist)))
1075 else:
1076 func(*args, **kwargs)
1077 return wrapper
1078
1079 return myImpl
1080
Robert Flack13c7ad92015-03-30 14:12:17 +00001081def skipIfPlatform(oslist):
1082 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001083 return unittest2.skipIf(getPlatform() in oslist,
1084 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001085
1086def skipUnlessPlatform(oslist):
1087 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001088 return unittest2.skipUnless(getPlatform() in oslist,
1089 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001090
Daniel Malea48359902013-05-14 20:48:54 +00001091def skipIfLinuxClang(func):
1092 """Decorate the item to skip tests that should be skipped if building on
1093 Linux with clang.
1094 """
1095 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1096 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1097 @wraps(func)
1098 def wrapper(*args, **kwargs):
1099 from unittest2 import case
1100 self = args[0]
1101 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001102 platform = self.getPlatform()
1103 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001104 self.skipTest("skipping because Clang is used on Linux")
1105 else:
1106 func(*args, **kwargs)
1107 return wrapper
1108
Ying Chen7091c2c2015-04-21 01:15:47 +00001109# provide a function to skip on defined oslist, compiler version, and archs
1110# if none is specified for any argument, that argument won't be checked and thus means for all
1111# for example,
1112# @skipIf, skip for all platform/compiler/arch,
1113# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1114# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1115
1116# TODO: refactor current code, to make skipIfxxx functions to call this function
Zachary Turnerabdb8392015-11-16 22:40:30 +00001117def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None, swig_version=None, py_version=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001118 def fn(self):
Siva Chandra7dcad312015-11-20 20:30:36 +00001119 oslist_passes = oslist is None or self.getPlatform() in oslist
1120 compiler_passes = compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))
Zachary Turnerabdb8392015-11-16 22:40:30 +00001121 arch_passes = self.expectedArch(archs)
Siva Chandra7dcad312015-11-20 20:30:36 +00001122 debug_info_passes = debug_info is None or self.debug_info in debug_info
Zachary Turnerabdb8392015-11-16 22:40:30 +00001123 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))
1124 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
1125
1126 return (oslist_passes and
1127 compiler_passes and
1128 arch_passes and
1129 debug_info_passes and
1130 swig_version_passes and
1131 py_version_passes)
Zachary Turnerba105702015-11-16 23:58:20 +00001132
1133 local_vars = locals()
1134 args = [x for x in inspect.getargspec(skipIf).args]
1135 arg_vals = [eval(x, globals(), local_vars) for x in args]
1136 args = [x for x in zip(args, arg_vals) if x[1] is not None]
1137 reasons = ['%s=%s' % (x, str(y)) for (x,y) in args]
1138 return skipTestIfFn(fn, bugnumber, skipReason='skipping because ' + ' && '.join(reasons))
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001139
1140def skipIfDebugInfo(bugnumber=None, debug_info=None):
1141 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1142
Greg Claytonedea2372015-10-07 20:01:13 +00001143def skipIfDWO(bugnumber=None):
1144 return skipIfDebugInfo(bugnumber, ["dwo"])
1145
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001146def skipIfDwarf(bugnumber=None):
1147 return skipIfDebugInfo(bugnumber, ["dwarf"])
1148
1149def skipIfDsym(bugnumber=None):
1150 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001151
1152def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1153 def skipTestIfFn_impl(func):
1154 @wraps(func)
1155 def wrapper(*args, **kwargs):
1156 from unittest2 import case
1157 self = args[0]
1158 if expected_fn(self):
1159 self.skipTest(skipReason)
1160 else:
1161 func(*args, **kwargs)
1162 return wrapper
Zachary Turnercd236b82015-10-26 18:48:24 +00001163 if six.callable(bugnumber):
Ying Chen7091c2c2015-04-21 01:15:47 +00001164 return skipTestIfFn_impl(bugnumber)
1165 else:
1166 return skipTestIfFn_impl
1167
Daniel Maleabe230792013-01-24 23:52:09 +00001168def skipIfGcc(func):
1169 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1170 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001171 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001172 @wraps(func)
1173 def wrapper(*args, **kwargs):
1174 from unittest2 import case
1175 self = args[0]
1176 compiler = self.getCompiler()
1177 if "gcc" in compiler:
1178 self.skipTest("skipping because gcc is the test compiler")
1179 else:
1180 func(*args, **kwargs)
1181 return wrapper
1182
Matt Kopec0de53f02013-03-15 19:10:12 +00001183def skipIfIcc(func):
1184 """Decorate the item to skip tests that should be skipped if building with icc ."""
1185 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1186 raise Exception("@skipIfIcc can only be used to decorate a test method")
1187 @wraps(func)
1188 def wrapper(*args, **kwargs):
1189 from unittest2 import case
1190 self = args[0]
1191 compiler = self.getCompiler()
1192 if "icc" in compiler:
1193 self.skipTest("skipping because icc is the test compiler")
1194 else:
1195 func(*args, **kwargs)
1196 return wrapper
1197
Daniel Malea55faa402013-05-02 21:44:31 +00001198def skipIfi386(func):
1199 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1200 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1201 raise Exception("@skipIfi386 can only be used to decorate a test method")
1202 @wraps(func)
1203 def wrapper(*args, **kwargs):
1204 from unittest2 import case
1205 self = args[0]
1206 if "i386" == self.getArchitecture():
1207 self.skipTest("skipping because i386 is not a supported architecture")
1208 else:
1209 func(*args, **kwargs)
1210 return wrapper
1211
Pavel Labath090152b2015-08-20 11:37:19 +00001212def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001213 """Decorator to skip tests when the target is Android.
1214
1215 Arguments:
1216 api_levels - The API levels for which the test should be skipped. If
1217 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001218 arch - A sequence of architecture names specifying the architectures
1219 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001220 """
1221 def myImpl(func):
1222 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1223 raise Exception("@skipIfTargetAndroid can only be used to "
1224 "decorate a test method")
1225 @wraps(func)
1226 def wrapper(*args, **kwargs):
1227 from unittest2 import case
1228 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001229 if matchAndroid(api_levels, archs)(self):
1230 self.skipTest("skiped on Android target with API %d and architecture %s" %
1231 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001232 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001233 return wrapper
1234 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001235
Ilia Kd9953052015-03-12 07:19:41 +00001236def skipUnlessCompilerRt(func):
1237 """Decorate the item to skip tests if testing remotely."""
1238 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1239 raise Exception("@skipUnless can only be used to decorate a test method")
1240 @wraps(func)
1241 def wrapper(*args, **kwargs):
1242 from unittest2 import case
1243 import os.path
Enrico Granata55d99f02015-11-19 21:45:07 +00001244 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "llvm","projects","compiler-rt")
1245 print(compilerRtPath)
Ilia Kd9953052015-03-12 07:19:41 +00001246 if not os.path.exists(compilerRtPath):
1247 self = args[0]
1248 self.skipTest("skip if compiler-rt not found")
1249 else:
1250 func(*args, **kwargs)
1251 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001252
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001253class _PlatformContext(object):
1254 """Value object class which contains platform-specific options."""
1255
1256 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1257 self.shlib_environment_var = shlib_environment_var
1258 self.shlib_prefix = shlib_prefix
1259 self.shlib_extension = shlib_extension
1260
1261
Johnny Chena74bb0a2011-08-01 18:46:13 +00001262class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001263 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001264 Abstract base for performing lldb (see TestBase) or other generic tests (see
1265 BenchBase for one example). lldbtest.Base works with the test driver to
1266 accomplish things.
1267
Johnny Chen8334dad2010-10-22 23:15:46 +00001268 """
Enrico Granata5020f952012-10-24 21:42:49 +00001269
Enrico Granata19186272012-10-24 21:44:48 +00001270 # The concrete subclass should override this attribute.
1271 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001272
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001273 # Keep track of the old current working directory.
1274 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001275
Greg Clayton4570d3e2013-12-10 23:19:29 +00001276 @staticmethod
1277 def compute_mydir(test_file):
1278 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1279
1280 mydir = TestBase.compute_mydir(__file__)'''
1281 test_dir = os.path.dirname(test_file)
1282 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1283
Johnny Chenfb4264c2011-08-01 19:50:58 +00001284 def TraceOn(self):
1285 """Returns True if we are in trace mode (tracing detailed test execution)."""
1286 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001287
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001288 @classmethod
1289 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001290 """
1291 Python unittest framework class setup fixture.
1292 Do current directory manipulation.
1293 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001294 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001295 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001296 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001297
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001298 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001299 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001300
1301 # Change current working directory if ${LLDB_TEST} is defined.
1302 # See also dotest.py which sets up ${LLDB_TEST}.
1303 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001304 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001305 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001306 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001307 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1308
Vince Harron85d19652015-05-21 19:09:29 +00001309 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001310 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001311 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1312 try:
1313 cls.dir_lock.try_acquire()
1314 # write the class that owns the lock into the lock file
1315 cls.dir_lock.handle.write(cls.__name__)
1316 except IOError as ioerror:
1317 # nothing else should have this directory lock
1318 # wait here until we get a lock
1319 cls.dir_lock.acquire()
1320 # read the previous owner from the lock file
1321 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001322 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 +00001323 raise ioerror
1324
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001325 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001326 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001327 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001328 elif getPlatform() in ("freebsd", "linux", "netbsd"):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001329 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001330 else:
1331 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001332
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001333 @classmethod
1334 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001335 """
1336 Python unittest framework class teardown fixture.
1337 Do class-wide cleanup.
1338 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001339
Johnny Chen0fddfb22011-11-17 19:57:27 +00001340 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001341 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001342 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001343 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001344
Johnny Chen707b3c92010-10-11 22:25:46 +00001345 # Subclass might have specific cleanup function defined.
1346 if getattr(cls, "classCleanup", None):
1347 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001348 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001349 try:
1350 cls.classCleanup()
1351 except:
1352 exc_type, exc_value, exc_tb = sys.exc_info()
1353 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001354
Vince Harron85d19652015-05-21 19:09:29 +00001355 if debug_confirm_directory_exclusivity:
1356 cls.dir_lock.release()
1357 del cls.dir_lock
1358
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001359 # Restore old working directory.
1360 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001361 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001362 os.chdir(cls.oldcwd)
1363
Johnny Chena74bb0a2011-08-01 18:46:13 +00001364 @classmethod
1365 def skipLongRunningTest(cls):
1366 """
1367 By default, we skip long running test case.
1368 This can be overridden by passing '-l' to the test driver (dotest.py).
1369 """
1370 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1371 return False
1372 else:
1373 return True
Johnny Chened492022011-06-21 00:53:00 +00001374
Vince Harron6d3d0f12015-05-10 22:01:59 +00001375 def enableLogChannelsForCurrentTest(self):
1376 if len(lldbtest_config.channels) == 0:
1377 return
1378
1379 # if debug channels are specified in lldbtest_config.channels,
1380 # create a new set of log files for every test
1381 log_basename = self.getLogBasenameForCurrentTest()
1382
1383 # confirm that the file is writeable
1384 host_log_path = "{}-host.log".format(log_basename)
1385 open(host_log_path, 'w').close()
1386
1387 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1388 for channel_with_categories in lldbtest_config.channels:
1389 channel_then_categories = channel_with_categories.split(' ', 1)
1390 channel = channel_then_categories[0]
1391 if len(channel_then_categories) > 1:
1392 categories = channel_then_categories[1]
1393 else:
1394 categories = "default"
1395
1396 if channel == "gdb-remote":
1397 # communicate gdb-remote categories to debugserver
1398 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1399
1400 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1401 if not self.res.Succeeded():
1402 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1403
1404 # Communicate log path name to debugserver & lldb-server
1405 server_log_path = "{}-server.log".format(log_basename)
1406 open(server_log_path, 'w').close()
1407 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1408
1409 # Communicate channels to lldb-server
1410 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1411
1412 if len(lldbtest_config.channels) == 0:
1413 return
1414
1415 def disableLogChannelsForCurrentTest(self):
1416 # close all log files that we opened
1417 for channel_and_categories in lldbtest_config.channels:
1418 # channel format - <channel-name> [<category0> [<category1> ...]]
1419 channel = channel_and_categories.split(' ', 1)[0]
1420 self.ci.HandleCommand("log disable " + channel, self.res)
1421 if not self.res.Succeeded():
1422 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1423
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001424 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001425 """Fixture for unittest test case setup.
1426
1427 It works with the test driver to conditionally skip tests and does other
1428 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001429 #import traceback
1430 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001431
Daniel Malea9115f072013-08-06 15:02:32 +00001432 if "LIBCXX_PATH" in os.environ:
1433 self.libcxxPath = os.environ["LIBCXX_PATH"]
1434 else:
1435 self.libcxxPath = None
1436
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001437 if "LLDBMI_EXEC" in os.environ:
1438 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1439 else:
1440 self.lldbMiExec = None
Vince Harron790d95c2015-05-18 19:39:03 +00001441
Johnny Chenebe51722011-10-07 19:21:09 +00001442 # If we spawn an lldb process for test (via pexpect), do not load the
1443 # init file unless told otherwise.
1444 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1445 self.lldbOption = ""
1446 else:
1447 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001448
Johnny Chen985e7402011-08-01 21:13:26 +00001449 # Assign the test method name to self.testMethodName.
1450 #
1451 # For an example of the use of this attribute, look at test/types dir.
1452 # There are a bunch of test cases under test/types and we don't want the
1453 # module cacheing subsystem to be confused with executable name "a.out"
1454 # used for all the test cases.
1455 self.testMethodName = self._testMethodName
1456
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001457 # Benchmarks test is decorated with @benchmarks_test,
1458 # which also sets the "__benchmarks_test__" attribute of the
1459 # function object to True.
1460 try:
1461 if lldb.just_do_benchmarks_test:
1462 testMethod = getattr(self, self._testMethodName)
1463 if getattr(testMethod, "__benchmarks_test__", False):
1464 pass
1465 else:
1466 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +00001467 except AttributeError:
1468 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001469
Johnny Chen985e7402011-08-01 21:13:26 +00001470 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1471 # with it using pexpect.
1472 self.child = None
1473 self.child_prompt = "(lldb) "
1474 # If the child is interacting with the embedded script interpreter,
1475 # there are two exits required during tear down, first to quit the
1476 # embedded script interpreter and second to quit the lldb command
1477 # interpreter.
1478 self.child_in_script_interpreter = False
1479
Johnny Chenfb4264c2011-08-01 19:50:58 +00001480 # These are for customized teardown cleanup.
1481 self.dict = None
1482 self.doTearDownCleanup = False
1483 # And in rare cases where there are multiple teardown cleanups.
1484 self.dicts = []
1485 self.doTearDownCleanups = False
1486
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001487 # List of spawned subproces.Popen objects
1488 self.subprocesses = []
1489
Daniel Malea69207462013-06-05 21:07:02 +00001490 # List of forked process PIDs
1491 self.forkedProcessPids = []
1492
Johnny Chenfb4264c2011-08-01 19:50:58 +00001493 # Create a string buffer to record the session info, to be dumped into a
1494 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001495 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001496
Vince Harron1f160372015-05-21 18:51:20 +00001497 session_file = "{}.log".format(self.log_basename)
Zachary Turner8d13fab2015-11-07 01:08:15 +00001498 # Python 3 doesn't support unbuffered I/O in text mode. Open buffered.
1499 self.session = open(session_file, "w")
Johnny Chenfb4264c2011-08-01 19:50:58 +00001500
1501 # Optimistically set __errored__, __failed__, __expected__ to False
1502 # initially. If the test errored/failed, the session info
1503 # (self.session) is then dumped into a session specific file for
1504 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001505 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001506 self.__errored__ = False
1507 self.__failed__ = False
1508 self.__expected__ = False
1509 # We are also interested in unexpected success.
1510 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001511 # And skipped tests.
1512 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001513
1514 # See addTearDownHook(self, hook) which allows the client to add a hook
1515 # function to be run during tearDown() time.
1516 self.hooks = []
1517
1518 # See HideStdout(self).
1519 self.sys_stdout_hidden = False
1520
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001521 if self.platformContext:
1522 # set environment variable names for finding shared libraries
1523 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001524
Vince Harron6d3d0f12015-05-10 22:01:59 +00001525 # Create the debugger instance if necessary.
1526 try:
1527 self.dbg = lldb.DBG
1528 except AttributeError:
1529 self.dbg = lldb.SBDebugger.Create()
1530
1531 if not self.dbg:
1532 raise Exception('Invalid debugger instance')
1533
1534 # Retrieve the associated command interpreter instance.
1535 self.ci = self.dbg.GetCommandInterpreter()
1536 if not self.ci:
1537 raise Exception('Could not get the command interpreter')
1538
1539 # And the result object.
1540 self.res = lldb.SBCommandReturnObject()
1541
1542 self.enableLogChannelsForCurrentTest()
1543
Ying Chen0c352822015-11-16 23:41:02 +00001544 #Initialize debug_info
1545 self.debug_info = None
1546
Johnny Chen2a808582011-10-19 16:48:07 +00001547 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001548 """Perform the run hooks to bring lldb debugger to the desired state.
1549
Johnny Chen2a808582011-10-19 16:48:07 +00001550 By default, expect a pexpect spawned child and child prompt to be
1551 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1552 and child prompt and use self.runCmd() to run the hooks one by one.
1553
Johnny Chena737ba52011-10-19 01:06:21 +00001554 Note that child is a process spawned by pexpect.spawn(). If not, your
1555 test case is mostly likely going to fail.
1556
1557 See also dotest.py where lldb.runHooks are processed/populated.
1558 """
1559 if not lldb.runHooks:
1560 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001561 if use_cmd_api:
1562 for hook in lldb.runhooks:
1563 self.runCmd(hook)
1564 else:
1565 if not child or not child_prompt:
1566 self.fail("Both child and child_prompt need to be defined.")
1567 for hook in lldb.runHooks:
1568 child.sendline(hook)
1569 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001570
Daniel Malea249287a2013-02-19 16:08:57 +00001571 def setAsync(self, value):
1572 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1573 old_async = self.dbg.GetAsync()
1574 self.dbg.SetAsync(value)
1575 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1576
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001577 def cleanupSubprocesses(self):
1578 # Ensure any subprocesses are cleaned up
1579 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001580 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001581 del p
1582 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001583 # Ensure any forked processes are cleaned up
1584 for pid in self.forkedProcessPids:
1585 if os.path.exists("/proc/" + str(pid)):
1586 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001587
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001588 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001589 """ Creates a subprocess.Popen object with the specified executable and arguments,
1590 saves it in self.subprocesses, and returns the object.
1591 NOTE: if using this function, ensure you also call:
1592
1593 self.addTearDownHook(self.cleanupSubprocesses)
1594
1595 otherwise the test suite will leak processes.
1596 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001597 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001598 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001599 self.subprocesses.append(proc)
1600 return proc
1601
Daniel Malea69207462013-06-05 21:07:02 +00001602 def forkSubprocess(self, executable, args=[]):
1603 """ Fork a subprocess with its own group ID.
1604 NOTE: if using this function, ensure you also call:
1605
1606 self.addTearDownHook(self.cleanupSubprocesses)
1607
1608 otherwise the test suite will leak processes.
1609 """
1610 child_pid = os.fork()
1611 if child_pid == 0:
1612 # If more I/O support is required, this can be beefed up.
1613 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001614 os.dup2(fd, 1)
1615 os.dup2(fd, 2)
1616 # This call causes the child to have its of group ID
1617 os.setpgid(0,0)
1618 os.execvp(executable, [executable] + args)
1619 # Give the child time to get through the execvp() call
1620 time.sleep(0.1)
1621 self.forkedProcessPids.append(child_pid)
1622 return child_pid
1623
Johnny Chenfb4264c2011-08-01 19:50:58 +00001624 def HideStdout(self):
1625 """Hide output to stdout from the user.
1626
1627 During test execution, there might be cases where we don't want to show the
1628 standard output to the user. For example,
1629
Zachary Turner35d017f2015-10-23 17:04:29 +00001630 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001631
1632 tests whether command abbreviation for 'script' works or not. There is no
1633 need to show the 'Hello' output to the user as long as the 'script' command
1634 succeeds and we are not in TraceOn() mode (see the '-t' option).
1635
1636 In this case, the test method calls self.HideStdout(self) to redirect the
1637 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1638
1639 Note that you should only call this method at most once during a test case
1640 execution. Any subsequent call has no effect at all."""
1641 if self.sys_stdout_hidden:
1642 return
1643
1644 self.sys_stdout_hidden = True
1645 old_stdout = sys.stdout
1646 sys.stdout = open(os.devnull, 'w')
1647 def restore_stdout():
1648 sys.stdout = old_stdout
1649 self.addTearDownHook(restore_stdout)
1650
1651 # =======================================================================
1652 # Methods for customized teardown cleanups as well as execution of hooks.
1653 # =======================================================================
1654
1655 def setTearDownCleanup(self, dictionary=None):
1656 """Register a cleanup action at tearDown() time with a dictinary"""
1657 self.dict = dictionary
1658 self.doTearDownCleanup = True
1659
1660 def addTearDownCleanup(self, dictionary):
1661 """Add a cleanup action at tearDown() time with a dictinary"""
1662 self.dicts.append(dictionary)
1663 self.doTearDownCleanups = True
1664
1665 def addTearDownHook(self, hook):
1666 """
1667 Add a function to be run during tearDown() time.
1668
1669 Hooks are executed in a first come first serve manner.
1670 """
Zachary Turnercd236b82015-10-26 18:48:24 +00001671 if six.callable(hook):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001672 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001673 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001674 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001675
1676 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001677
Jim Inghamda3a3862014-10-16 23:02:14 +00001678 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001679 # This is for the case of directly spawning 'lldb' and interacting with it
1680 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001681 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001682 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001683 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001684 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001685 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001686 if self.child_in_script_interpreter:
1687 self.child.sendline('quit()')
1688 self.child.expect_exact(self.child_prompt)
1689 self.child.sendline('settings set interpreter.prompt-on-quit false')
1690 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001691 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001692 except (ValueError, pexpect.ExceptionPexpect):
1693 # child is already terminated
1694 pass
1695 except OSError as exception:
1696 import errno
1697 if exception.errno != errno.EIO:
1698 # unexpected error
1699 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001700 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001701 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001702 finally:
1703 # Give it one final blow to make sure the child is terminated.
1704 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001705
1706 def tearDown(self):
1707 """Fixture for unittest test case teardown."""
1708 #import traceback
1709 #traceback.print_stack()
1710
1711 self.deletePexpectChild()
1712
Johnny Chenfb4264c2011-08-01 19:50:58 +00001713 # Check and run any hook functions.
1714 for hook in reversed(self.hooks):
1715 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001716 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001717 import inspect
1718 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001719 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001720 hook()
1721 elif hook_argc == 1:
1722 hook(self)
1723 else:
1724 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001725
1726 del self.hooks
1727
1728 # Perform registered teardown cleanup.
1729 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001730 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001731
1732 # In rare cases where there are multiple teardown cleanups added.
1733 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001734 if self.dicts:
1735 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001736 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001737
Vince Harron9753dd92015-05-10 15:22:09 +00001738 self.disableLogChannelsForCurrentTest()
1739
Johnny Chenfb4264c2011-08-01 19:50:58 +00001740 # =========================================================
1741 # Various callbacks to allow introspection of test progress
1742 # =========================================================
1743
1744 def markError(self):
1745 """Callback invoked when an error (unexpected exception) errored."""
1746 self.__errored__ = True
1747 with recording(self, False) as sbuf:
1748 # False because there's no need to write "ERROR" to the stderr twice.
1749 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001750 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001751
Zachary Turnerb1490b62015-08-26 19:44:56 +00001752 def markCleanupError(self):
1753 """Callback invoked when an error occurs while a test is cleaning up."""
1754 self.__cleanup_errored__ = True
1755 with recording(self, False) as sbuf:
1756 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1757 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001758 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001759
Johnny Chenfb4264c2011-08-01 19:50:58 +00001760 def markFailure(self):
1761 """Callback invoked when a failure (test assertion failure) occurred."""
1762 self.__failed__ = True
1763 with recording(self, False) as sbuf:
1764 # False because there's no need to write "FAIL" to the stderr twice.
1765 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001766 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001767
Enrico Granatae6cedc12013-02-23 01:05:23 +00001768 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001769 """Callback invoked when an expected failure/error occurred."""
1770 self.__expected__ = True
1771 with recording(self, False) as sbuf:
1772 # False because there's no need to write "expected failure" to the
1773 # stderr twice.
1774 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001775 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001776 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001777 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001778 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001779
Johnny Chenc5cc6252011-08-15 23:09:08 +00001780 def markSkippedTest(self):
1781 """Callback invoked when a test is skipped."""
1782 self.__skipped__ = True
1783 with recording(self, False) as sbuf:
1784 # False because there's no need to write "skipped test" to the
1785 # stderr twice.
1786 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001787 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001788
Enrico Granatae6cedc12013-02-23 01:05:23 +00001789 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001790 """Callback invoked when an unexpected success occurred."""
1791 self.__unexpected__ = True
1792 with recording(self, False) as sbuf:
1793 # False because there's no need to write "unexpected success" to the
1794 # stderr twice.
1795 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001796 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001797 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001798 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001799 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001800
Greg Clayton70995582015-01-07 22:25:50 +00001801 def getRerunArgs(self):
1802 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001803
1804 def getLogBasenameForCurrentTest(self, prefix=None):
1805 """
1806 returns a partial path that can be used as the beginning of the name of multiple
1807 log files pertaining to this test
1808
1809 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1810 """
1811 dname = os.path.join(os.environ["LLDB_TEST"],
1812 os.environ["LLDB_SESSION_DIRNAME"])
1813 if not os.path.isdir(dname):
1814 os.mkdir(dname)
1815
1816 compiler = self.getCompiler()
1817
1818 if compiler[1] == ':':
1819 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001820 if os.path.altsep is not None:
1821 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001822
Vince Harron19e300f2015-05-12 00:50:54 +00001823 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001824 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001825 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001826
1827 if prefix is not None:
1828 fname = "{}-{}".format(prefix, fname)
1829
1830 return os.path.join(dname, fname)
1831
Johnny Chenfb4264c2011-08-01 19:50:58 +00001832 def dumpSessionInfo(self):
1833 """
1834 Dump the debugger interactions leading to a test error/failure. This
1835 allows for more convenient postmortem analysis.
1836
1837 See also LLDBTestResult (dotest.py) which is a singlton class derived
1838 from TextTestResult and overwrites addError, addFailure, and
1839 addExpectedFailure methods to allow us to to mark the test instance as
1840 such.
1841 """
1842
1843 # We are here because self.tearDown() detected that this test instance
1844 # either errored or failed. The lldb.test_result singleton contains
1845 # two lists (erros and failures) which get populated by the unittest
1846 # framework. Look over there for stack trace information.
1847 #
1848 # The lists contain 2-tuples of TestCase instances and strings holding
1849 # formatted tracebacks.
1850 #
1851 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001852
Vince Harron35b17dc2015-05-21 18:20:21 +00001853 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001854 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001855 if self.__errored__:
1856 pairs = lldb.test_result.errors
1857 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001858 elif self.__cleanup_errored__:
Zachary Turnerb1490b62015-08-26 19:44:56 +00001859 pairs = lldb.test_result.cleanup_errors
1860 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001861 elif self.__failed__:
1862 pairs = lldb.test_result.failures
1863 prefix = 'Failure'
1864 elif self.__expected__:
1865 pairs = lldb.test_result.expectedFailures
1866 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001867 elif self.__skipped__:
1868 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001869 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001870 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001871 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001872 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001873
Johnny Chenc5cc6252011-08-15 23:09:08 +00001874 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001875 for test, traceback in pairs:
1876 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001877 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001878
Vince Harron35b17dc2015-05-21 18:20:21 +00001879 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001880 testMethod = getattr(self, self._testMethodName)
1881 if getattr(testMethod, "__benchmarks_test__", False):
1882 benchmarks = True
1883 else:
1884 benchmarks = False
1885
Vince Harron35b17dc2015-05-21 18:20:21 +00001886 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001887 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1888 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1889 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001890 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001891 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001892 self.session.close()
1893 del self.session
1894
1895 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001896 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001897
1898 if prefix != 'Success' or lldbtest_config.log_success:
1899 # keep all log files, rename them to include prefix
1900 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1901 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001902 if os.path.isfile(src):
1903 dst = src.replace(self.log_basename, dst_log_basename)
1904 if os.name == "nt" and os.path.isfile(dst):
1905 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1906 # it silently replaces the destination. Ultimately this means that atomic renames are not
1907 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1908 # destination first if it already exists.
1909 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001910
Zachary Turner306278f2015-05-26 20:26:29 +00001911 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001912 else:
1913 # success! (and we don't want log files) delete log files
1914 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001915 try:
1916 os.unlink(log_file)
1917 except:
1918 # We've seen consistent unlink failures on Windows, perhaps because the
1919 # just-created log file is being scanned by anti-virus. Empirically, this
1920 # sleep-and-retry approach allows tests to succeed much more reliably.
1921 # Attempts to figure out exactly what process was still holding a file handle
1922 # have failed because running instrumentation like Process Monitor seems to
1923 # slow things down enough that the problem becomes much less consistent.
1924 time.sleep(0.5)
1925 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001926
1927 # ====================================================
1928 # Config. methods supported through a plugin interface
1929 # (enables reading of the current test configuration)
1930 # ====================================================
1931
1932 def getArchitecture(self):
1933 """Returns the architecture in effect the test suite is running with."""
1934 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001935 arch = module.getArchitecture()
1936 if arch == 'amd64':
1937 arch = 'x86_64'
1938 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001939
Vince Harron02613762015-05-04 00:17:53 +00001940 def getLldbArchitecture(self):
1941 """Returns the architecture of the lldb binary."""
1942 if not hasattr(self, 'lldbArchitecture'):
1943
1944 # spawn local process
1945 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001946 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001947 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001948 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001949 "-o",
1950 "quit"
1951 ]
1952
1953 output = check_output(command)
1954 str = output.decode("utf-8");
1955
1956 for line in str.splitlines():
1957 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1958 if m:
1959 self.lldbArchitecture = m.group(1)
1960 break
1961
1962 return self.lldbArchitecture
1963
Johnny Chenfb4264c2011-08-01 19:50:58 +00001964 def getCompiler(self):
1965 """Returns the compiler in effect the test suite is running with."""
1966 module = builder_module()
1967 return module.getCompiler()
1968
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001969 def getCompilerBinary(self):
1970 """Returns the compiler binary the test suite is running with."""
1971 return self.getCompiler().split()[0]
1972
Daniel Malea0aea0162013-02-27 17:29:46 +00001973 def getCompilerVersion(self):
1974 """ Returns a string that represents the compiler version.
1975 Supports: llvm, clang.
1976 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00001977 from .lldbutil import which
Daniel Malea0aea0162013-02-27 17:29:46 +00001978 version = 'unknown'
1979
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001980 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001981 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001982 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001983 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001984 if m:
1985 version = m.group(1)
1986 return version
1987
Ryan Brown57bee1e2015-09-14 22:45:11 +00001988 def getGoCompilerVersion(self):
1989 """ Returns a string that represents the go compiler version, or None if go is not found.
1990 """
1991 compiler = which("go")
1992 if compiler:
1993 version_output = system([[compiler, "version"]])[0]
1994 for line in version_output.split(os.linesep):
1995 m = re.search('go version (devel|go\\S+)', line)
1996 if m:
1997 return m.group(1)
1998 return None
1999
Greg Claytone0d0a762015-04-02 18:24:03 +00002000 def platformIsDarwin(self):
2001 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00002002 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00002003
Robert Flack13c7ad92015-03-30 14:12:17 +00002004 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00002005 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00002006 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00002007
Daniel Maleaadaaec92013-08-06 20:51:41 +00002008 def isIntelCompiler(self):
2009 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
2010 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
2011
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002012 def expectedCompilerVersion(self, compiler_version):
2013 """Returns True iff compiler_version[1] matches the current compiler version.
2014 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
2015 Any operator other than the following defaults to an equality test:
2016 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
2017 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002018 if (compiler_version == None):
2019 return True
2020 operator = str(compiler_version[0])
2021 version = compiler_version[1]
2022
2023 if (version == None):
2024 return True
2025 if (operator == '>'):
2026 return self.getCompilerVersion() > version
2027 if (operator == '>=' or operator == '=>'):
2028 return self.getCompilerVersion() >= version
2029 if (operator == '<'):
2030 return self.getCompilerVersion() < version
2031 if (operator == '<=' or operator == '=<'):
2032 return self.getCompilerVersion() <= version
2033 if (operator == '!=' or operator == '!' or operator == 'not'):
2034 return str(version) not in str(self.getCompilerVersion())
2035 return str(version) in str(self.getCompilerVersion())
2036
2037 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002038 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002039 if (compilers == None):
2040 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002041
2042 for compiler in compilers:
2043 if compiler in self.getCompiler():
2044 return True
2045
2046 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002047
Ying Chen7091c2c2015-04-21 01:15:47 +00002048 def expectedArch(self, archs):
2049 """Returns True iff any element of archs is a sub-string of the current architecture."""
2050 if (archs == None):
2051 return True
2052
2053 for arch in archs:
2054 if arch in self.getArchitecture():
2055 return True
2056
2057 return False
2058
Johnny Chenfb4264c2011-08-01 19:50:58 +00002059 def getRunOptions(self):
2060 """Command line option for -A and -C to run this test again, called from
2061 self.dumpSessionInfo()."""
2062 arch = self.getArchitecture()
2063 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00002064 if arch:
2065 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00002066 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00002067 option_str = ""
2068 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00002069 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00002070 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00002071
2072 # ==================================================
2073 # Build methods supported through a plugin interface
2074 # ==================================================
2075
Ed Mastec97323e2014-04-01 18:47:58 +00002076 def getstdlibFlag(self):
2077 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00002078 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00002079 stdlibflag = "-stdlib=libc++"
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002080 else: # this includes NetBSD
Ed Mastec97323e2014-04-01 18:47:58 +00002081 stdlibflag = ""
2082 return stdlibflag
2083
Matt Kopec7663b3a2013-09-25 17:44:00 +00002084 def getstdFlag(self):
2085 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002086 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002087 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002088 else:
2089 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002090 return stdflag
2091
2092 def buildDriver(self, sources, exe_name):
2093 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2094 or LLDB.framework).
2095 """
2096
2097 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002098 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002099
2100 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002101 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002102 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002103 d = {'CXX_SOURCES' : sources,
2104 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002105 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002106 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2107 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002108 }
Ed Maste372c24d2013-07-25 21:02:34 +00002109 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 +00002110 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002111 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002112 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002113 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002114 elif sys.platform.startswith('win'):
2115 d = {'CXX_SOURCES' : sources,
2116 'EXE' : exe_name,
2117 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002118 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002119 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002120 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002121
2122 self.buildDefault(dictionary=d)
2123
Matt Kopec7663b3a2013-09-25 17:44:00 +00002124 def buildLibrary(self, sources, lib_name):
2125 """Platform specific way to build a default library. """
2126
2127 stdflag = self.getstdFlag()
2128
Greg Clayton22fd3b12015-10-26 17:52:16 +00002129 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002130 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002131 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002132 d = {'DYLIB_CXX_SOURCES' : sources,
2133 'DYLIB_NAME' : lib_name,
2134 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002135 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2136 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002137 }
Robert Flack4629c4b2015-05-15 18:54:32 +00002138 elif self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux' or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002139 d = {'DYLIB_CXX_SOURCES' : sources,
2140 'DYLIB_NAME' : lib_name,
2141 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002142 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002143 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002144 d = {'DYLIB_CXX_SOURCES' : sources,
2145 'DYLIB_NAME' : lib_name,
2146 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002147 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002148 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002149 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002150
2151 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002152
Daniel Malea55faa402013-05-02 21:44:31 +00002153 def buildProgram(self, sources, exe_name):
2154 """ Platform specific way to build an executable from C/C++ sources. """
2155 d = {'CXX_SOURCES' : sources,
2156 'EXE' : exe_name}
2157 self.buildDefault(dictionary=d)
2158
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002159 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002160 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002161 if lldb.skip_build_and_cleanup:
2162 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002163 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002164 if target_is_android():
2165 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002166 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002167 raise Exception("Don't know how to build default binary")
2168
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002169 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002170 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002171 if lldb.skip_build_and_cleanup:
2172 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002173 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002174 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002175 raise Exception("Don't know how to build binary with dsym")
2176
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002177 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002178 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002179 if lldb.skip_build_and_cleanup:
2180 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002181 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002182 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002183 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002184 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002185 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002186
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002187 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2188 """Platform specific way to build binaries with dwarf maps."""
2189 if lldb.skip_build_and_cleanup:
2190 return
2191 module = builder_module()
2192 if target_is_android():
2193 dictionary = append_android_envs(dictionary)
2194 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2195 raise Exception("Don't know how to build binary with dwo")
2196
Ryan Brown57bee1e2015-09-14 22:45:11 +00002197 def buildGo(self):
2198 """Build the default go binary.
2199 """
2200 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2201
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002202 def signBinary(self, binary_path):
2203 if sys.platform.startswith("darwin"):
2204 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2205 call(codesign_cmd, shell=True)
2206
Kuba Breckabeed8212014-09-04 01:03:18 +00002207 def findBuiltClang(self):
2208 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2209 paths_to_try = [
2210 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2211 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2212 "llvm-build/Release/x86_64/Release/bin/clang",
2213 "llvm-build/Debug/x86_64/Debug/bin/clang",
2214 ]
Enrico Granata55d99f02015-11-19 21:45:07 +00002215 lldb_root_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
Kuba Breckabeed8212014-09-04 01:03:18 +00002216 for p in paths_to_try:
2217 path = os.path.join(lldb_root_path, p)
2218 if os.path.exists(path):
2219 return path
Ilia Kd9953052015-03-12 07:19:41 +00002220
2221 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002222 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002223 if os.path.exists(path):
2224 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002225
2226 return os.environ["CC"]
2227
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002228 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002229 """ Returns a dictionary (which can be provided to build* functions above) which
2230 contains OS-specific build flags.
2231 """
2232 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002233 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002234
2235 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002236 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002237 use_libcxx = True
2238
2239 if use_libcxx and self.libcxxPath:
2240 cflags += "-stdlib=libc++ "
2241 if self.libcxxPath:
2242 libcxxInclude = os.path.join(self.libcxxPath, "include")
2243 libcxxLib = os.path.join(self.libcxxPath, "lib")
2244 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2245 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2246
Andrew Kaylor93132f52013-05-28 23:04:25 +00002247 if use_cpp11:
2248 cflags += "-std="
2249 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2250 cflags += "c++0x"
2251 else:
2252 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002253 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002254 cflags += " -stdlib=libc++"
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002255 elif self.getPlatform() == "netbsd":
2256 cflags += " -stdlib=libstdc++"
Andrew Kaylor93132f52013-05-28 23:04:25 +00002257 elif "clang" in self.getCompiler():
2258 cflags += " -stdlib=libstdc++"
2259
Andrew Kaylor93132f52013-05-28 23:04:25 +00002260 return {'CFLAGS_EXTRAS' : cflags,
2261 'LD_EXTRAS' : ldflags,
2262 }
2263
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002264 def cleanup(self, dictionary=None):
2265 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002266 if lldb.skip_build_and_cleanup:
2267 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002268 module = builder_module()
2269 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002270 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002271
Daniel Malea55faa402013-05-02 21:44:31 +00002272 def getLLDBLibraryEnvVal(self):
2273 """ Returns the path that the OS-specific library search environment variable
2274 (self.dylibPath) should be set to in order for a program to find the LLDB
2275 library. If an environment variable named self.dylibPath is already set,
2276 the new path is appended to it and returned.
2277 """
2278 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002279 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002280 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002281 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002282 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002283 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002284 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002285 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002286
Ed Maste437f8f62013-09-09 14:04:04 +00002287 def getLibcPlusPlusLibs(self):
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002288 if self.getPlatform() in ('freebsd', 'linux', 'netbsd'):
Ed Maste437f8f62013-09-09 14:04:04 +00002289 return ['libc++.so.1']
2290 else:
2291 return ['libc++.1.dylib','libc++abi.dylib']
2292
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002293# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2294# We change the test methods to create a new test method for each test for each debug info we are
2295# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2296# the new test method we remove the old method at the same time.
2297class LLDBTestCaseFactory(type):
2298 def __new__(cls, name, bases, attrs):
2299 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002300 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002301 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2302 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002303 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002304 def dsym_test_method(self, attrvalue=attrvalue):
2305 self.debug_info = "dsym"
2306 return attrvalue(self)
2307 dsym_method_name = attrname + "_dsym"
2308 dsym_test_method.__name__ = dsym_method_name
2309 newattrs[dsym_method_name] = dsym_test_method
2310
2311 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002312 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002313 def dwarf_test_method(self, attrvalue=attrvalue):
2314 self.debug_info = "dwarf"
2315 return attrvalue(self)
2316 dwarf_method_name = attrname + "_dwarf"
2317 dwarf_test_method.__name__ = dwarf_method_name
2318 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002319
2320 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002321 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002322 def dwo_test_method(self, attrvalue=attrvalue):
2323 self.debug_info = "dwo"
2324 return attrvalue(self)
2325 dwo_method_name = attrname + "_dwo"
2326 dwo_test_method.__name__ = dwo_method_name
2327 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002328 else:
2329 newattrs[attrname] = attrvalue
2330 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2331
Zachary Turner43a01e42015-10-20 21:06:05 +00002332# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2333@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002334class TestBase(Base):
2335 """
2336 This abstract base class is meant to be subclassed. It provides default
2337 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2338 among other things.
2339
2340 Important things for test class writers:
2341
2342 - Overwrite the mydir class attribute, otherwise your test class won't
2343 run. It specifies the relative directory to the top level 'test' so
2344 the test harness can change to the correct working directory before
2345 running your test.
2346
2347 - The setUp method sets up things to facilitate subsequent interactions
2348 with the debugger as part of the test. These include:
2349 - populate the test method name
2350 - create/get a debugger set with synchronous mode (self.dbg)
2351 - get the command interpreter from with the debugger (self.ci)
2352 - create a result object for use with the command interpreter
2353 (self.res)
2354 - plus other stuffs
2355
2356 - The tearDown method tries to perform some necessary cleanup on behalf
2357 of the test to return the debugger to a good state for the next test.
2358 These include:
2359 - execute any tearDown hooks registered by the test method with
2360 TestBase.addTearDownHook(); examples can be found in
2361 settings/TestSettings.py
2362 - kill the inferior process associated with each target, if any,
2363 and, then delete the target from the debugger's target list
2364 - perform build cleanup before running the next test method in the
2365 same test class; examples of registering for this service can be
2366 found in types/TestIntegerTypes.py with the call:
2367 - self.setTearDownCleanup(dictionary=d)
2368
2369 - Similarly setUpClass and tearDownClass perform classwise setup and
2370 teardown fixtures. The tearDownClass method invokes a default build
2371 cleanup for the entire test class; also, subclasses can implement the
2372 classmethod classCleanup(cls) to perform special class cleanup action.
2373
2374 - The instance methods runCmd and expect are used heavily by existing
2375 test cases to send a command to the command interpreter and to perform
2376 string/pattern matching on the output of such command execution. The
2377 expect method also provides a mode to peform string/pattern matching
2378 without running a command.
2379
2380 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2381 build the binaries used during a particular test scenario. A plugin
2382 should be provided for the sys.platform running the test suite. The
2383 Mac OS X implementation is located in plugins/darwin.py.
2384 """
2385
2386 # Maximum allowed attempts when launching the inferior process.
2387 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2388 maxLaunchCount = 3;
2389
2390 # Time to wait before the next launching attempt in second(s).
2391 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2392 timeWaitNextLaunch = 1.0;
2393
2394 def doDelay(self):
2395 """See option -w of dotest.py."""
2396 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
2397 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
2398 waitTime = 1.0
2399 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
2400 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
2401 time.sleep(waitTime)
2402
Enrico Granata165f8af2012-09-21 19:10:53 +00002403 # Returns the list of categories to which this test case belongs
2404 # by default, look for a ".categories" file, and read its contents
2405 # if no such file exists, traverse the hierarchy - we guarantee
2406 # a .categories to exist at the top level directory so we do not end up
2407 # looping endlessly - subclasses are free to define their own categories
2408 # in whatever way makes sense to them
2409 def getCategories(self):
2410 import inspect
2411 import os.path
2412 folder = inspect.getfile(self.__class__)
2413 folder = os.path.dirname(folder)
2414 while folder != '/':
2415 categories_file_name = os.path.join(folder,".categories")
2416 if os.path.exists(categories_file_name):
2417 categories_file = open(categories_file_name,'r')
2418 categories = categories_file.readline()
2419 categories_file.close()
2420 categories = str.replace(categories,'\n','')
2421 categories = str.replace(categories,'\r','')
2422 return categories.split(',')
2423 else:
2424 folder = os.path.dirname(folder)
2425 continue
2426
Johnny Chena74bb0a2011-08-01 18:46:13 +00002427 def setUp(self):
2428 #import traceback
2429 #traceback.print_stack()
2430
2431 # Works with the test driver to conditionally skip tests via decorators.
2432 Base.setUp(self)
2433
Johnny Chena74bb0a2011-08-01 18:46:13 +00002434 try:
2435 if lldb.blacklist:
2436 className = self.__class__.__name__
2437 classAndMethodName = "%s.%s" % (className, self._testMethodName)
2438 if className in lldb.blacklist:
2439 self.skipTest(lldb.blacklist.get(className))
2440 elif classAndMethodName in lldb.blacklist:
2441 self.skipTest(lldb.blacklist.get(classAndMethodName))
2442 except AttributeError:
2443 pass
2444
Johnny Chened492022011-06-21 00:53:00 +00002445 # Insert some delay between successive test cases if specified.
2446 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00002447
Johnny Chenf2b70232010-08-25 18:49:48 +00002448 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2449 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2450
Johnny Chen430eb762010-10-19 16:00:42 +00002451 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002452 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002453
Daniel Maleae0f8f572013-08-26 23:57:52 +00002454 #
2455 # Warning: MAJOR HACK AHEAD!
2456 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
2457 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
2458 # command, instead. See also runCmd() where it decorates the "file filename" call
2459 # with additional functionality when running testsuite remotely.
2460 #
2461 if lldb.lldbtest_remote_sandbox:
2462 def DecoratedCreateTarget(arg):
2463 self.runCmd("file %s" % arg)
2464 target = self.dbg.GetSelectedTarget()
2465 #
Greg Claytonc6947512013-12-13 19:18:59 +00002466 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00002467 # johnny @ 04/23/2012
2468 #
2469 def DecoratedLaunchSimple(argv, envp, wd):
2470 self.runCmd("run")
2471 return target.GetProcess()
2472 target.LaunchSimple = DecoratedLaunchSimple
2473
2474 return target
2475 self.dbg.CreateTarget = DecoratedCreateTarget
2476 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002477 print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
Daniel Maleae0f8f572013-08-26 23:57:52 +00002478
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002479 # We want our debugger to be synchronous.
2480 self.dbg.SetAsync(False)
2481
2482 # Retrieve the associated command interpreter instance.
2483 self.ci = self.dbg.GetCommandInterpreter()
2484 if not self.ci:
2485 raise Exception('Could not get the command interpreter')
2486
2487 # And the result object.
2488 self.res = lldb.SBCommandReturnObject()
2489
Johnny Chen44d24972012-04-16 18:55:15 +00002490 # Run global pre-flight code, if defined via the config file.
2491 if lldb.pre_flight:
2492 lldb.pre_flight(self)
2493
Enrico Granatabd0998a2015-10-02 22:53:32 +00002494 if lldb.remote_platform and lldb.remote_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002495 remote_test_dir = lldbutil.join_remote_paths(
2496 lldb.remote_platform_working_dir,
2497 self.getArchitecture(),
2498 str(self.test_number),
2499 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002500 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002501 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002502 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002503
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002504 # This function removes all files from the current working directory while leaving
2505 # the directories in place. The cleaup is required to reduce the disk space required
2506 # by the test suit while leaving the directories untached is neccessary because
2507 # sub-directories might belong to an other test
2508 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002509 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002510 # TODO: Replace the heuristic to remove the files with a logic what collects the
2511 # list of files we have to remove during test runs.
2512 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002513 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002514 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002515 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002516 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002517
Greg Clayton35c91342014-11-17 18:40:27 +00002518 def registerSharedLibrariesWithTarget(self, target, shlibs):
2519 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2520
2521 Any modules in the target that have their remote install file specification set will
2522 get uploaded to the remote host. This function registers the local copies of the
2523 shared libraries with the target and sets their remote install locations so they will
2524 be uploaded when the target is run.
2525 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002526 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002527 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002528
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002529 shlib_environment_var = self.platformContext.shlib_environment_var
2530 shlib_prefix = self.platformContext.shlib_prefix
2531 shlib_extension = '.' + self.platformContext.shlib_extension
2532
2533 working_dir = self.get_process_working_directory()
2534 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2535 # Add any shared libraries to our target if remote so they get
2536 # uploaded into the working directory on the remote side
2537 for name in shlibs:
2538 # The path can be a full path to a shared library, or a make file name like "Foo" for
2539 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2540 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2541 # of the shared library accordingly
2542 if os.path.exists(name):
2543 local_shlib_path = name # name is the full path to the local shared library
2544 else:
2545 # Check relative names
2546 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2547 if not os.path.exists(local_shlib_path):
2548 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002549 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002550 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002551
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002552 # Make sure we found the local shared library in the above code
2553 self.assertTrue(os.path.exists(local_shlib_path))
2554
2555 # Add the shared library to our target
2556 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2557 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002558 # We must set the remote install location if we want the shared library
2559 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002560 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002561 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002562
2563 return environment
2564
Enrico Granata44818162012-10-24 01:23:57 +00002565 # utility methods that tests can use to access the current objects
2566 def target(self):
2567 if not self.dbg:
2568 raise Exception('Invalid debugger instance')
2569 return self.dbg.GetSelectedTarget()
2570
2571 def process(self):
2572 if not self.dbg:
2573 raise Exception('Invalid debugger instance')
2574 return self.dbg.GetSelectedTarget().GetProcess()
2575
2576 def thread(self):
2577 if not self.dbg:
2578 raise Exception('Invalid debugger instance')
2579 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2580
2581 def frame(self):
2582 if not self.dbg:
2583 raise Exception('Invalid debugger instance')
2584 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2585
Greg Claytonc6947512013-12-13 19:18:59 +00002586 def get_process_working_directory(self):
2587 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2588 if lldb.remote_platform:
2589 # Remote tests set the platform working directory up in TestBase.setUp()
2590 return lldb.remote_platform.GetWorkingDirectory()
2591 else:
2592 # local tests change directory into each test subdirectory
2593 return os.getcwd()
2594
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002595 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002596 #import traceback
2597 #traceback.print_stack()
2598
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002599 # Ensure all the references to SB objects have gone away so that we can
2600 # be sure that all test-specific resources have been freed before we
2601 # attempt to delete the targets.
2602 gc.collect()
2603
Johnny Chen3794ad92011-06-15 21:24:24 +00002604 # Delete the target(s) from the debugger as a general cleanup step.
2605 # This includes terminating the process for each target, if any.
2606 # We'd like to reuse the debugger for our next test without incurring
2607 # the initialization overhead.
2608 targets = []
2609 for target in self.dbg:
2610 if target:
2611 targets.append(target)
2612 process = target.GetProcess()
2613 if process:
2614 rc = self.invoke(process, "Kill")
2615 self.assertTrue(rc.Success(), PROCESS_KILLED)
2616 for target in targets:
2617 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002618
Johnny Chen44d24972012-04-16 18:55:15 +00002619 # Run global post-flight code, if defined via the config file.
2620 if lldb.post_flight:
2621 lldb.post_flight(self)
2622
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002623 # Do this last, to make sure it's in reverse order from how we setup.
2624 Base.tearDown(self)
2625
Zachary Turner95812042015-03-26 18:54:21 +00002626 # This must be the last statement, otherwise teardown hooks or other
2627 # lines might depend on this still being active.
2628 del self.dbg
2629
Johnny Chen86268e42011-09-30 21:48:35 +00002630 def switch_to_thread_with_stop_reason(self, stop_reason):
2631 """
2632 Run the 'thread list' command, and select the thread with stop reason as
2633 'stop_reason'. If no such thread exists, no select action is done.
2634 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002635 from .lldbutil import stop_reason_to_str
Johnny Chen86268e42011-09-30 21:48:35 +00002636 self.runCmd('thread list')
2637 output = self.res.GetOutput()
2638 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2639 stop_reason_to_str(stop_reason))
2640 for line in output.splitlines():
2641 matched = thread_line_pattern.match(line)
2642 if matched:
2643 self.runCmd('thread select %s' % matched.group(1))
2644
Enrico Granata7594f142013-06-17 22:51:50 +00002645 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002646 """
2647 Ask the command interpreter to handle the command and then check its
2648 return status.
2649 """
2650 # Fail fast if 'cmd' is not meaningful.
2651 if not cmd or len(cmd) == 0:
2652 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002653
Johnny Chen8d55a342010-08-31 17:42:54 +00002654 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002655
Daniel Maleae0f8f572013-08-26 23:57:52 +00002656 # This is an opportunity to insert the 'platform target-install' command if we are told so
2657 # via the settig of lldb.lldbtest_remote_sandbox.
2658 if cmd.startswith("target create "):
2659 cmd = cmd.replace("target create ", "file ")
2660 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
2661 with recording(self, trace) as sbuf:
2662 the_rest = cmd.split("file ")[1]
2663 # Split the rest of the command line.
2664 atoms = the_rest.split()
2665 #
2666 # NOTE: This assumes that the options, if any, follow the file command,
2667 # instead of follow the specified target.
2668 #
2669 target = atoms[-1]
2670 # Now let's get the absolute pathname of our target.
2671 abs_target = os.path.abspath(target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002672 print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002673 fpath, fname = os.path.split(abs_target)
2674 parent_dir = os.path.split(fpath)[0]
2675 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
Zachary Turnerff890da2015-10-19 23:45:41 +00002676 print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002677 self.ci.HandleCommand(platform_target_install_command, self.res)
2678 # And this is the file command we want to execute, instead.
2679 #
2680 # Warning: SIDE EFFECT AHEAD!!!
2681 # Populate the remote executable pathname into the lldb namespace,
2682 # so that test cases can grab this thing out of the namespace.
2683 #
2684 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
2685 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002686 print("And this is the replaced file command: %s" % cmd, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002687
Johnny Chen63dfb272010-09-01 00:15:19 +00002688 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002689
Johnny Chen63dfb272010-09-01 00:15:19 +00002690 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002691 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002692
Johnny Chen150c3cc2010-10-15 01:18:29 +00002693 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002694 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002695 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002696 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002697 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002698 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002699 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002700 print("runCmd failed!", file=sbuf)
2701 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002702
Johnny Chenff3d01d2010-08-20 21:03:09 +00002703 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002704 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002705 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002706 # For process launch, wait some time before possible next try.
2707 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002708 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002709 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002710
Johnny Chen27f212d2010-08-19 23:26:59 +00002711 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002712 self.assertTrue(self.res.Succeeded(),
2713 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002714
Jim Ingham63dfc722012-09-22 00:05:11 +00002715 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2716 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2717
2718 Otherwise, all the arguments have the same meanings as for the expect function"""
2719
2720 trace = (True if traceAlways else trace)
2721
2722 if exe:
2723 # First run the command. If we are expecting error, set check=False.
2724 # Pass the assert message along since it provides more semantic info.
2725 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2726
2727 # Then compare the output against expected strings.
2728 output = self.res.GetError() if error else self.res.GetOutput()
2729
2730 # If error is True, the API client expects the command to fail!
2731 if error:
2732 self.assertFalse(self.res.Succeeded(),
2733 "Command '" + str + "' is expected to fail!")
2734 else:
2735 # No execution required, just compare str against the golden input.
2736 output = str
2737 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002738 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002739
2740 # The heading says either "Expecting" or "Not expecting".
2741 heading = "Expecting" if matching else "Not expecting"
2742
2743 for pattern in patterns:
2744 # Match Objects always have a boolean value of True.
2745 match_object = re.search(pattern, output)
2746 matched = bool(match_object)
2747 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002748 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2749 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002750 if matched:
2751 break
2752
2753 self.assertTrue(matched if matching else not matched,
2754 msg if msg else EXP_MSG(str, exe))
2755
2756 return match_object
2757
Enrico Granata7594f142013-06-17 22:51:50 +00002758 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 +00002759 """
2760 Similar to runCmd; with additional expect style output matching ability.
2761
2762 Ask the command interpreter to handle the command and then check its
2763 return status. The 'msg' parameter specifies an informational assert
2764 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002765 'startstr', matches the substrings contained in 'substrs', and regexp
2766 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002767
2768 If the keyword argument error is set to True, it signifies that the API
2769 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002770 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002771 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002772
2773 If the keyword argument matching is set to False, it signifies that the API
2774 client is expecting the output of the command not to match the golden
2775 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002776
2777 Finally, the required argument 'str' represents the lldb command to be
2778 sent to the command interpreter. In case the keyword argument 'exe' is
2779 set to False, the 'str' is treated as a string to be matched/not-matched
2780 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002781 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002782 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002783
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002784 if exe:
2785 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002786 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002787 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002788
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002789 # Then compare the output against expected strings.
2790 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002791
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002792 # If error is True, the API client expects the command to fail!
2793 if error:
2794 self.assertFalse(self.res.Succeeded(),
2795 "Command '" + str + "' is expected to fail!")
2796 else:
2797 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002798 if isinstance(str,lldb.SBCommandReturnObject):
2799 output = str.GetOutput()
2800 else:
2801 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002802 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002803 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002804
Johnny Chenea88e942010-09-21 21:08:53 +00002805 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002806 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002807
2808 # Start from the startstr, if specified.
2809 # If there's no startstr, set the initial state appropriately.
2810 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002811
Johnny Chen150c3cc2010-10-15 01:18:29 +00002812 if startstr:
2813 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002814 print("%s start string: %s" % (heading, startstr), file=sbuf)
2815 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002816
Johnny Chen86268e42011-09-30 21:48:35 +00002817 # Look for endstr, if specified.
2818 keepgoing = matched if matching else not matched
2819 if endstr:
2820 matched = output.endswith(endstr)
2821 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002822 print("%s end string: %s" % (heading, endstr), file=sbuf)
2823 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002824
Johnny Chenea88e942010-09-21 21:08:53 +00002825 # Look for sub strings, if specified.
2826 keepgoing = matched if matching else not matched
2827 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002828 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002829 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002830 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002831 print("%s sub string: %s" % (heading, str), file=sbuf)
2832 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002833 keepgoing = matched if matching else not matched
2834 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002835 break
2836
Johnny Chenea88e942010-09-21 21:08:53 +00002837 # Search for regular expression patterns, if specified.
2838 keepgoing = matched if matching else not matched
2839 if patterns and keepgoing:
2840 for pattern in patterns:
2841 # Match Objects always have a boolean value of True.
2842 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002843 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002844 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2845 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002846 keepgoing = matched if matching else not matched
2847 if not keepgoing:
2848 break
Johnny Chenea88e942010-09-21 21:08:53 +00002849
2850 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002851 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002852
Johnny Chenf3c59232010-08-25 22:52:45 +00002853 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002854 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002855 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002856
2857 method = getattr(obj, name)
2858 import inspect
2859 self.assertTrue(inspect.ismethod(method),
2860 name + "is a method name of object: " + str(obj))
2861 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002862 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002863 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002864 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002865
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002866 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2867 """Platform specific way to build the default binaries."""
2868 if lldb.skip_build_and_cleanup:
2869 return
2870 module = builder_module()
2871 if target_is_android():
2872 dictionary = append_android_envs(dictionary)
2873 if self.debug_info is None:
2874 return self.buildDefault(architecture, compiler, dictionary, clean)
2875 elif self.debug_info == "dsym":
2876 return self.buildDsym(architecture, compiler, dictionary, clean)
2877 elif self.debug_info == "dwarf":
2878 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002879 elif self.debug_info == "dwo":
2880 return self.buildDwo(architecture, compiler, dictionary, clean)
2881 else:
2882 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002883
Johnny Chenf359cf22011-05-27 23:36:52 +00002884 # =================================================
2885 # Misc. helper methods for debugging test execution
2886 # =================================================
2887
Johnny Chen56b92a72011-07-11 19:15:11 +00002888 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002889 """Debug print a SBValue object, if traceAlways is True."""
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002890 from .lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002891
Johnny Chen8d55a342010-08-31 17:42:54 +00002892 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002893 return
2894
2895 err = sys.stderr
2896 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002897 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2898 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2899 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2900 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2901 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2902 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2903 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2904 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2905 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002906
Johnny Chen36c5eb12011-08-05 20:17:27 +00002907 def DebugSBType(self, type):
2908 """Debug print a SBType object, if traceAlways is True."""
2909 if not traceAlways:
2910 return
2911
2912 err = sys.stderr
2913 err.write(type.GetName() + ":\n")
2914 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2915 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2916 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2917
Johnny Chenb877f1e2011-03-12 01:18:19 +00002918 def DebugPExpect(self, child):
2919 """Debug the spwaned pexpect object."""
2920 if not traceAlways:
2921 return
2922
Zachary Turnerff890da2015-10-19 23:45:41 +00002923 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002924
2925 @classmethod
2926 def RemoveTempFile(cls, file):
2927 if os.path.exists(file):
2928 os.remove(file)