blob: 58c2107f5ab65a97711e7b9f5cfe7f3faf157cfc [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
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000034import abc
Johnny Chen90312a82010-09-21 22:34:45 +000035import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000036import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000037import re
Daniel Malea69207462013-06-05 21:07:02 +000038import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000039from subprocess import *
Johnny Chen150c3cc2010-10-15 01:18:29 +000040import StringIO
Johnny Chenf2b70232010-08-25 18:49:48 +000041import time
Johnny Chena33a93c2010-08-30 23:08:52 +000042import types
Johnny Chen73258832010-08-05 23:42:46 +000043import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +000044import lldb
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000045from _pyio import __metaclass__
Johnny Chenbf6ffa32010-07-03 03:41:59 +000046
Johnny Chen707b3c92010-10-11 22:25:46 +000047# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000048# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000049
50# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000051if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
52 traceAlways = True
53else:
54 traceAlways = False
55
Johnny Chen707b3c92010-10-11 22:25:46 +000056# By default, doCleanup is True.
57if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
58 doCleanup = False
59else:
60 doCleanup = True
61
Johnny Chen8d55a342010-08-31 17:42:54 +000062
Johnny Chen00778092010-08-09 22:01:17 +000063#
64# Some commonly used assert messages.
65#
66
Johnny Chenaa902922010-09-17 22:45:27 +000067COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
68
Johnny Chen00778092010-08-09 22:01:17 +000069CURRENT_EXECUTABLE_SET = "Current executable set successfully"
70
Johnny Chen7d1d7532010-09-02 21:23:12 +000071PROCESS_IS_VALID = "Process is valid"
72
73PROCESS_KILLED = "Process is killed successfully"
74
Johnny Chend5f66fc2010-12-23 01:12:19 +000075PROCESS_EXITED = "Process exited successfully"
76
77PROCESS_STOPPED = "Process status should be stopped"
78
Johnny Chen5ee88192010-08-27 23:47:36 +000079RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +000080
Johnny Chen17941842010-08-09 23:44:24 +000081RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +000082
Johnny Chen67af43f2010-10-05 19:27:32 +000083BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
84
Johnny Chen17941842010-08-09 23:44:24 +000085BREAKPOINT_CREATED = "Breakpoint created successfully"
86
Johnny Chenf10af382010-12-04 00:07:24 +000087BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
88
Johnny Chene76896c2010-08-17 21:33:31 +000089BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
90
Johnny Chen17941842010-08-09 23:44:24 +000091BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +000092
Johnny Chen703dbd02010-09-30 17:06:24 +000093BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
94
Johnny Chen164f1e12010-10-15 18:07:09 +000095BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
96
Greg Clayton5db6b792012-10-24 18:24:14 +000097MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
98
Johnny Chen89109ed12011-06-27 20:05:23 +000099OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
100
Johnny Chen5b3a3572010-12-09 18:22:12 +0000101SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
102
Johnny Chenc70b02a2010-09-22 23:00:20 +0000103STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
104
Johnny Chen1691a162011-04-15 16:44:48 +0000105STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
106
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000107STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
108
Johnny Chen5d6c4642010-11-10 23:46:38 +0000109STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000110
Johnny Chen5d6c4642010-11-10 23:46:38 +0000111STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
112 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000113
Johnny Chen2e431ce2010-10-20 18:38:48 +0000114STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
115
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000116STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
117
Johnny Chenc066ab42010-10-14 01:22:03 +0000118STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
119
Johnny Chen00778092010-08-09 22:01:17 +0000120STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
121
Johnny Chenf68cc122011-09-15 21:09:59 +0000122STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
123
Johnny Chen3c884a02010-08-24 22:07:56 +0000124DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
125
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000126VALID_BREAKPOINT = "Got a valid breakpoint"
127
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000128VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
129
Johnny Chen7209d84f2011-05-06 23:26:12 +0000130VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
131
Johnny Chen5ee88192010-08-27 23:47:36 +0000132VALID_FILESPEC = "Got a valid filespec"
133
Johnny Chen025d1b82010-12-08 01:25:21 +0000134VALID_MODULE = "Got a valid module"
135
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000136VALID_PROCESS = "Got a valid process"
137
Johnny Chen025d1b82010-12-08 01:25:21 +0000138VALID_SYMBOL = "Got a valid symbol"
139
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000140VALID_TARGET = "Got a valid target"
141
Matthew Gardinerc928de32014-10-22 07:22:56 +0000142VALID_PLATFORM = "Got a valid platform"
143
Johnny Chen15f247a2012-02-03 20:43:00 +0000144VALID_TYPE = "Got a valid type"
145
Johnny Chen5819ab42011-07-15 22:28:10 +0000146VALID_VARIABLE = "Got a valid variable"
147
Johnny Chen981463d2010-08-25 19:00:04 +0000148VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000149
Johnny Chenf68cc122011-09-15 21:09:59 +0000150WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000151
Johnny Chenc0c67f22010-11-09 18:42:22 +0000152def CMD_MSG(str):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000153 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000154 return "Command '%s' returns successfully" % str
155
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000156def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000157 '''A generic message generator for the completion mechanism.'''
158 return "'%s' successfully completes to '%s'" % (str_before, str_after)
159
Johnny Chenc0c67f22010-11-09 18:42:22 +0000160def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000161 '''A generic "'%s' returns expected result" message generator if exe.
162 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000163 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000164
Johnny Chen3343f042010-10-19 19:11:38 +0000165def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000166 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000167 return "Value of setting '%s' is correct" % setting
168
Johnny Chen27c41232010-08-26 21:49:29 +0000169def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000170 """Returns an env variable array from the os.environ map object."""
Johnny Chen27c41232010-08-26 21:49:29 +0000171 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
172
Johnny Chen47ceb032010-10-11 23:52:19 +0000173def line_number(filename, string_to_match):
174 """Helper function to return the line number of the first matched string."""
175 with open(filename, 'r') as f:
176 for i, line in enumerate(f):
177 if line.find(string_to_match) != -1:
178 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000179 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000180 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000181
Johnny Chen67af43f2010-10-05 19:27:32 +0000182def pointer_size():
183 """Return the pointer size of the host system."""
184 import ctypes
185 a_pointer = ctypes.c_void_p(0xffff)
186 return 8 * ctypes.sizeof(a_pointer)
187
Johnny Chen57816732012-02-09 02:01:59 +0000188def is_exe(fpath):
189 """Returns true if fpath is an executable."""
190 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
191
192def which(program):
193 """Returns the full path to a program; None otherwise."""
194 fpath, fname = os.path.split(program)
195 if fpath:
196 if is_exe(program):
197 return program
198 else:
199 for path in os.environ["PATH"].split(os.pathsep):
200 exe_file = os.path.join(path, program)
201 if is_exe(exe_file):
202 return exe_file
203 return None
204
Johnny Chen150c3cc2010-10-15 01:18:29 +0000205class recording(StringIO.StringIO):
206 """
207 A nice little context manager for recording the debugger interactions into
208 our session object. If trace flag is ON, it also emits the interactions
209 into the stderr.
210 """
211 def __init__(self, test, trace):
Johnny Chen690fcef2010-10-15 23:55:05 +0000212 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen150c3cc2010-10-15 01:18:29 +0000213 StringIO.StringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000214 # The test might not have undergone the 'setUp(self)' phase yet, so that
215 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000216 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000217 self.trace = trace
218
219 def __enter__(self):
220 """
221 Context management protocol on entry to the body of the with statement.
222 Just return the StringIO object.
223 """
224 return self
225
226 def __exit__(self, type, value, tb):
227 """
228 Context management protocol on exit from the body of the with statement.
229 If trace is ON, it emits the recordings into stderr. Always add the
230 recordings to our session object. And close the StringIO object, too.
231 """
232 if self.trace:
Johnny Chen690fcef2010-10-15 23:55:05 +0000233 print >> sys.stderr, self.getvalue()
234 if self.session:
235 print >> self.session, self.getvalue()
Johnny Chen150c3cc2010-10-15 01:18:29 +0000236 self.close()
237
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000238class _BaseProcess(object):
239 __metaclass__ = abc.ABCMeta
240
241 @abc.abstractproperty
242 def pid(self):
243 """Returns process PID if has been launched already."""
244
245 @abc.abstractmethod
246 def launch(self, executable, args):
247 """Launches new process with given executable and args."""
248
249 @abc.abstractmethod
250 def terminate(self):
251 """Terminates previously launched process.."""
252
253class _LocalProcess(_BaseProcess):
254
255 def __init__(self, trace_on):
256 self._proc = None
257 self._trace_on = trace_on
258
259 @property
260 def pid(self):
261 return self._proc.pid
262
263 def launch(self, executable, args):
264 self._proc = Popen([executable] + args,
265 stdout = open(os.devnull) if not self._trace_on else None,
266 stdin = PIPE)
267
268 def terminate(self):
269 if self._proc.poll() == None:
270 self._proc.terminate()
271
272class _RemoteProcess(_BaseProcess):
273
274 def __init__(self):
275 self._pid = None
276
277 @property
278 def pid(self):
279 return self._pid
280
281 def launch(self, executable, args):
282 remote_work_dir = lldb.remote_platform.GetWorkingDirectory()
283 src_path = executable
284 dst_path = os.path.join(remote_work_dir, os.path.basename(executable))
285
286 dst_file_spec = lldb.SBFileSpec(dst_path, False)
287 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True),
288 dst_file_spec)
289 if err.Fail():
290 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
291
292 launch_info = lldb.SBLaunchInfo(args)
293 launch_info.SetExecutableFile(dst_file_spec, True)
294 launch_info.SetWorkingDirectory(remote_work_dir)
295
296 # Redirect stdout and stderr to /dev/null
297 launch_info.AddSuppressFileAction(1, False, True)
298 launch_info.AddSuppressFileAction(2, False, True)
299
300 err = lldb.remote_platform.Launch(launch_info)
301 if err.Fail():
302 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
303 self._pid = launch_info.GetProcessID()
304
305 def terminate(self):
306 err = lldb.remote_platform.Kill(self._pid)
307 if err.Fail():
308 raise Exception("remote_platform.Kill(%d) failed: %s" % (self._pid, err))
309
Johnny Chen690fcef2010-10-15 23:55:05 +0000310# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000311# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000312def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000313 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000314
315 If the exit code was non-zero it raises a CalledProcessError. The
316 CalledProcessError object will have the return code in the returncode
317 attribute and output in the output attribute.
318
319 The arguments are the same as for the Popen constructor. Example:
320
321 >>> check_output(["ls", "-l", "/dev/null"])
322 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
323
324 The stdout argument is not allowed as it is used internally.
325 To capture standard error in the result, use stderr=STDOUT.
326
327 >>> check_output(["/bin/sh", "-c",
328 ... "ls -l non_existent_file ; exit 0"],
329 ... stderr=STDOUT)
330 'ls: non_existent_file: No such file or directory\n'
331 """
332
333 # Assign the sender object to variable 'test' and remove it from kwargs.
334 test = kwargs.pop('sender', None)
335
Zachary Turner9ef307b2014-07-22 16:19:29 +0000336 separator = None
337 separator = " && " if os.name == "nt" else "; "
338 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
339 commandList = [' '.join(x) for x in commands]
340 # ['make clean foo', 'make foo'] -> 'make clean foo; make foo'
341 shellCommand = separator.join(commandList)
342
Johnny Chen690fcef2010-10-15 23:55:05 +0000343 if 'stdout' in kwargs:
344 raise ValueError('stdout argument not allowed, it will be overridden.')
Zachary Turner9ef307b2014-07-22 16:19:29 +0000345 if 'shell' in kwargs and kwargs['shell']==False:
346 raise ValueError('shell=False not allowed')
347 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
Johnny Chen0bd8c312011-11-16 22:41:53 +0000348 pid = process.pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000349 output, error = process.communicate()
350 retcode = process.poll()
351
Ed Maste6e496332014-08-05 20:33:17 +0000352 # Enable trace on failure return while tracking down FreeBSD buildbot issues
353 trace = traceAlways
354 if not trace and retcode and sys.platform.startswith("freebsd"):
355 trace = True
356
357 with recording(test, trace) as sbuf:
Johnny Chen690fcef2010-10-15 23:55:05 +0000358 print >> sbuf
Zachary Turner9ef307b2014-07-22 16:19:29 +0000359 print >> sbuf, "os command:", shellCommand
Johnny Chen0bd8c312011-11-16 22:41:53 +0000360 print >> sbuf, "with pid:", pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000361 print >> sbuf, "stdout:", output
362 print >> sbuf, "stderr:", error
363 print >> sbuf, "retcode:", retcode
364 print >> sbuf
365
366 if retcode:
367 cmd = kwargs.get("args")
368 if cmd is None:
Zachary Turner9ef307b2014-07-22 16:19:29 +0000369 cmd = shellCommand
Johnny Chen690fcef2010-10-15 23:55:05 +0000370 raise CalledProcessError(retcode, cmd)
Johnny Chenac77f3b2011-03-23 20:28:59 +0000371 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000372
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000373def getsource_if_available(obj):
374 """
375 Return the text of the source code for an object if available. Otherwise,
376 a print representation is returned.
377 """
378 import inspect
379 try:
380 return inspect.getsource(obj)
381 except:
382 return repr(obj)
383
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000384def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000385 if sys.platform.startswith("freebsd"):
386 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000387 return __import__("builder_" + sys.platform)
388
Johnny Chena74bb0a2011-08-01 18:46:13 +0000389#
390# Decorators for categorizing test cases.
391#
392
393from functools import wraps
394def python_api_test(func):
395 """Decorate the item as a Python API only test."""
396 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
397 raise Exception("@python_api_test can only be used to decorate a test method")
398 @wraps(func)
399 def wrapper(self, *args, **kwargs):
400 try:
401 if lldb.dont_do_python_api_test:
402 self.skipTest("python api tests")
403 except AttributeError:
404 pass
405 return func(self, *args, **kwargs)
406
407 # Mark this function as such to separate them from lldb command line tests.
408 wrapper.__python_api_test__ = True
409 return wrapper
410
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000411def lldbmi_test(func):
412 """Decorate the item as a lldb-mi only test."""
413 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
414 raise Exception("@lldbmi_test can only be used to decorate a test method")
415 @wraps(func)
416 def wrapper(self, *args, **kwargs):
417 try:
418 if lldb.dont_do_lldbmi_test:
419 self.skipTest("lldb-mi tests")
420 except AttributeError:
421 pass
422 return func(self, *args, **kwargs)
423
424 # Mark this function as such to separate them from lldb command line tests.
425 wrapper.__lldbmi_test__ = True
426 return wrapper
427
Johnny Chena74bb0a2011-08-01 18:46:13 +0000428def benchmarks_test(func):
429 """Decorate the item as a benchmarks test."""
430 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
431 raise Exception("@benchmarks_test can only be used to decorate a test method")
432 @wraps(func)
433 def wrapper(self, *args, **kwargs):
434 try:
435 if not lldb.just_do_benchmarks_test:
436 self.skipTest("benchmarks tests")
437 except AttributeError:
438 pass
439 return func(self, *args, **kwargs)
440
441 # Mark this function as such to separate them from the regular tests.
442 wrapper.__benchmarks_test__ = True
443 return wrapper
444
Johnny Chenf1548d42012-04-06 00:56:05 +0000445def dsym_test(func):
446 """Decorate the item as a dsym test."""
447 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
448 raise Exception("@dsym_test can only be used to decorate a test method")
449 @wraps(func)
450 def wrapper(self, *args, **kwargs):
451 try:
452 if lldb.dont_do_dsym_test:
453 self.skipTest("dsym tests")
454 except AttributeError:
455 pass
456 return func(self, *args, **kwargs)
457
458 # Mark this function as such to separate them from the regular tests.
459 wrapper.__dsym_test__ = True
460 return wrapper
461
462def dwarf_test(func):
463 """Decorate the item as a dwarf test."""
464 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
465 raise Exception("@dwarf_test can only be used to decorate a test method")
466 @wraps(func)
467 def wrapper(self, *args, **kwargs):
468 try:
469 if lldb.dont_do_dwarf_test:
470 self.skipTest("dwarf tests")
471 except AttributeError:
472 pass
473 return func(self, *args, **kwargs)
474
475 # Mark this function as such to separate them from the regular tests.
476 wrapper.__dwarf_test__ = True
477 return wrapper
478
Todd Fialaa41d48c2014-04-28 04:49:40 +0000479def debugserver_test(func):
480 """Decorate the item as a debugserver test."""
481 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
482 raise Exception("@debugserver_test can only be used to decorate a test method")
483 @wraps(func)
484 def wrapper(self, *args, **kwargs):
485 try:
486 if lldb.dont_do_debugserver_test:
487 self.skipTest("debugserver tests")
488 except AttributeError:
489 pass
490 return func(self, *args, **kwargs)
491
492 # Mark this function as such to separate them from the regular tests.
493 wrapper.__debugserver_test__ = True
494 return wrapper
495
496def llgs_test(func):
497 """Decorate the item as a lldb-gdbserver test."""
498 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
499 raise Exception("@llgs_test can only be used to decorate a test method")
500 @wraps(func)
501 def wrapper(self, *args, **kwargs):
502 try:
503 if lldb.dont_do_llgs_test:
504 self.skipTest("llgs tests")
505 except AttributeError:
506 pass
507 return func(self, *args, **kwargs)
508
509 # Mark this function as such to separate them from the regular tests.
510 wrapper.__llgs_test__ = True
511 return wrapper
512
Daniel Maleae0f8f572013-08-26 23:57:52 +0000513def not_remote_testsuite_ready(func):
514 """Decorate the item as a test which is not ready yet for remote testsuite."""
515 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
516 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
517 @wraps(func)
518 def wrapper(self, *args, **kwargs):
519 try:
520 if lldb.lldbtest_remote_sandbox:
521 self.skipTest("not ready for remote testsuite")
522 except AttributeError:
523 pass
524 return func(self, *args, **kwargs)
525
526 # Mark this function as such to separate them from the regular tests.
527 wrapper.__not_ready_for_remote_testsuite_test__ = True
528 return wrapper
529
Ed Maste433790a2014-04-23 12:55:41 +0000530def expectedFailure(expected_fn, bugnumber=None):
531 def expectedFailure_impl(func):
532 @wraps(func)
533 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000534 from unittest2 import case
535 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000536 try:
Ed Maste433790a2014-04-23 12:55:41 +0000537 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000538 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000539 if expected_fn(self):
540 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000541 else:
542 raise
Ed Maste433790a2014-04-23 12:55:41 +0000543 if expected_fn(self):
544 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
545 return wrapper
Enrico Granatacf3ab582014-10-17 01:11:29 +0000546 if bugnumber:
547 if callable(bugnumber):
548 return expectedFailure_impl(bugnumber)
549 else:
550 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000551
552def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
553 if compiler_version is None:
554 compiler_version=['=', None]
555 def fn(self):
556 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
Enrico Granatacf3ab582014-10-17 01:11:29 +0000557 if bugnumber: return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000558
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000559def expectedFailureClang(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000560 if bugnumber: return expectedFailureCompiler('clang', None, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000561
562def expectedFailureGcc(bugnumber=None, compiler_version=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000563 if bugnumber: return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000564
Matt Kopec0de53f02013-03-15 19:10:12 +0000565def expectedFailureIcc(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000566 if bugnumber: return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000567
Ed Maste433790a2014-04-23 12:55:41 +0000568def expectedFailureArch(arch, bugnumber=None):
569 def fn(self):
570 return arch in self.getArchitecture()
Enrico Granatacf3ab582014-10-17 01:11:29 +0000571 if bugnumber: return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000572
Enrico Granatae6cedc12013-02-23 01:05:23 +0000573def expectedFailurei386(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000574 if bugnumber: return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000575
Matt Kopecee969f92013-09-26 23:30:59 +0000576def expectedFailurex86_64(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000577 if bugnumber: return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000578
579def expectedFailureOS(os, bugnumber=None, compilers=None):
580 def fn(self):
581 return os in sys.platform and self.expectedCompiler(compilers)
Enrico Granatacf3ab582014-10-17 01:11:29 +0000582 if bugnumber: return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000583
584def expectedFailureDarwin(bugnumber=None, compilers=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000585 if bugnumber: return expectedFailureOS('darwin', bugnumber, compilers)
Matt Kopecee969f92013-09-26 23:30:59 +0000586
Ed Maste24a7f7d2013-07-24 19:47:08 +0000587def expectedFailureFreeBSD(bugnumber=None, compilers=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000588 if bugnumber: return expectedFailureOS('freebsd', bugnumber, compilers)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000589
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000590def expectedFailureLinux(bugnumber=None, compilers=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000591 if bugnumber: return expectedFailureOS('linux', bugnumber, compilers)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000592
Zachary Turner80c2c602014-12-09 19:28:00 +0000593def expectedFailureWindows(bugnumber=None, compilers=None):
594 if bugnumber: return expectedFailureOS('win32', bugnumber, compilers)
595
Chaoren Lin72b8f052015-02-03 01:51:18 +0000596def expectedFailureLLGS(bugnumber=None, compilers=None):
597 def fn(self):
598 return 'PLATFORM_LINUX_FORCE_LLGS_LOCAL' in os.environ and self.expectedCompiler(compilers)
599 if bugnumber: return expectedFailure(fn, bugnumber)
600
Greg Clayton12514562013-12-05 22:22:32 +0000601def skipIfRemote(func):
602 """Decorate the item to skip tests if testing remotely."""
603 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
604 raise Exception("@skipIfRemote can only be used to decorate a test method")
605 @wraps(func)
606 def wrapper(*args, **kwargs):
607 from unittest2 import case
608 if lldb.remote_platform:
609 self = args[0]
610 self.skipTest("skip on remote platform")
611 else:
612 func(*args, **kwargs)
613 return wrapper
614
615def skipIfRemoteDueToDeadlock(func):
616 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
617 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
618 raise Exception("@skipIfRemote can only be used to decorate a test method")
619 @wraps(func)
620 def wrapper(*args, **kwargs):
621 from unittest2 import case
622 if lldb.remote_platform:
623 self = args[0]
624 self.skipTest("skip on remote platform (deadlocks)")
625 else:
626 func(*args, **kwargs)
627 return wrapper
628
Ed Maste09617a52013-06-25 19:11:36 +0000629def skipIfFreeBSD(func):
630 """Decorate the item to skip tests that should be skipped on FreeBSD."""
631 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
632 raise Exception("@skipIfFreeBSD can only be used to decorate a test method")
633 @wraps(func)
634 def wrapper(*args, **kwargs):
635 from unittest2 import case
636 self = args[0]
637 platform = sys.platform
638 if "freebsd" in platform:
639 self.skipTest("skip on FreeBSD")
640 else:
641 func(*args, **kwargs)
642 return wrapper
643
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000644def skipIfLinux(func):
Daniel Malea93aec0f2012-11-23 21:59:29 +0000645 """Decorate the item to skip tests that should be skipped on Linux."""
646 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000647 raise Exception("@skipIfLinux can only be used to decorate a test method")
Daniel Malea93aec0f2012-11-23 21:59:29 +0000648 @wraps(func)
649 def wrapper(*args, **kwargs):
650 from unittest2 import case
651 self = args[0]
652 platform = sys.platform
653 if "linux" in platform:
654 self.skipTest("skip on linux")
655 else:
Jim Ingham9732e082012-11-27 01:21:28 +0000656 func(*args, **kwargs)
Daniel Malea93aec0f2012-11-23 21:59:29 +0000657 return wrapper
658
Enrico Granatab633e432014-10-06 21:37:06 +0000659def skipIfNoSBHeaders(func):
660 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
661 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000662 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000663 @wraps(func)
664 def wrapper(*args, **kwargs):
665 from unittest2 import case
666 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000667 if sys.platform.startswith("darwin"):
668 header = os.path.join(self.lib_dir, 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
669 else:
670 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000671 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000672 if not os.path.exists(header):
673 self.skipTest("skip because LLDB.h header not found")
674 else:
675 func(*args, **kwargs)
676 return wrapper
677
Zachary Turnerc7826522014-08-13 17:44:53 +0000678def skipIfWindows(func):
679 """Decorate the item to skip tests that should be skipped on Windows."""
680 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
681 raise Exception("@skipIfWindows can only be used to decorate a test method")
682 @wraps(func)
683 def wrapper(*args, **kwargs):
684 from unittest2 import case
685 self = args[0]
686 platform = sys.platform
687 if "win32" in platform:
688 self.skipTest("skip on Windows")
689 else:
690 func(*args, **kwargs)
691 return wrapper
692
Daniel Maleab3d41a22013-07-09 00:08:01 +0000693def skipIfDarwin(func):
694 """Decorate the item to skip tests that should be skipped on Darwin."""
695 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Mastea7f13f02013-07-09 00:24:52 +0000696 raise Exception("@skipIfDarwin can only be used to decorate a test method")
Daniel Maleab3d41a22013-07-09 00:08:01 +0000697 @wraps(func)
698 def wrapper(*args, **kwargs):
699 from unittest2 import case
700 self = args[0]
701 platform = sys.platform
702 if "darwin" in platform:
703 self.skipTest("skip on darwin")
704 else:
705 func(*args, **kwargs)
706 return wrapper
707
708
Daniel Malea48359902013-05-14 20:48:54 +0000709def skipIfLinuxClang(func):
710 """Decorate the item to skip tests that should be skipped if building on
711 Linux with clang.
712 """
713 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
714 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
715 @wraps(func)
716 def wrapper(*args, **kwargs):
717 from unittest2 import case
718 self = args[0]
719 compiler = self.getCompiler()
720 platform = sys.platform
721 if "clang" in compiler and "linux" in platform:
722 self.skipTest("skipping because Clang is used on Linux")
723 else:
724 func(*args, **kwargs)
725 return wrapper
726
Daniel Maleabe230792013-01-24 23:52:09 +0000727def skipIfGcc(func):
728 """Decorate the item to skip tests that should be skipped if building with gcc ."""
729 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +0000730 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +0000731 @wraps(func)
732 def wrapper(*args, **kwargs):
733 from unittest2 import case
734 self = args[0]
735 compiler = self.getCompiler()
736 if "gcc" in compiler:
737 self.skipTest("skipping because gcc is the test compiler")
738 else:
739 func(*args, **kwargs)
740 return wrapper
741
Matt Kopec0de53f02013-03-15 19:10:12 +0000742def skipIfIcc(func):
743 """Decorate the item to skip tests that should be skipped if building with icc ."""
744 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
745 raise Exception("@skipIfIcc can only be used to decorate a test method")
746 @wraps(func)
747 def wrapper(*args, **kwargs):
748 from unittest2 import case
749 self = args[0]
750 compiler = self.getCompiler()
751 if "icc" in compiler:
752 self.skipTest("skipping because icc is the test compiler")
753 else:
754 func(*args, **kwargs)
755 return wrapper
756
Daniel Malea55faa402013-05-02 21:44:31 +0000757def skipIfi386(func):
758 """Decorate the item to skip tests that should be skipped if building 32-bit."""
759 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
760 raise Exception("@skipIfi386 can only be used to decorate a test method")
761 @wraps(func)
762 def wrapper(*args, **kwargs):
763 from unittest2 import case
764 self = args[0]
765 if "i386" == self.getArchitecture():
766 self.skipTest("skipping because i386 is not a supported architecture")
767 else:
768 func(*args, **kwargs)
769 return wrapper
770
771
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000772class _PlatformContext(object):
773 """Value object class which contains platform-specific options."""
774
775 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
776 self.shlib_environment_var = shlib_environment_var
777 self.shlib_prefix = shlib_prefix
778 self.shlib_extension = shlib_extension
779
780
Johnny Chena74bb0a2011-08-01 18:46:13 +0000781class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000782 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000783 Abstract base for performing lldb (see TestBase) or other generic tests (see
784 BenchBase for one example). lldbtest.Base works with the test driver to
785 accomplish things.
786
Johnny Chen8334dad2010-10-22 23:15:46 +0000787 """
Enrico Granata5020f952012-10-24 21:42:49 +0000788
Enrico Granata19186272012-10-24 21:44:48 +0000789 # The concrete subclass should override this attribute.
790 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000791
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000792 # Keep track of the old current working directory.
793 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000794
Greg Clayton4570d3e2013-12-10 23:19:29 +0000795 @staticmethod
796 def compute_mydir(test_file):
797 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
798
799 mydir = TestBase.compute_mydir(__file__)'''
800 test_dir = os.path.dirname(test_file)
801 return test_dir[len(os.environ["LLDB_TEST"])+1:]
802
Johnny Chenfb4264c2011-08-01 19:50:58 +0000803 def TraceOn(self):
804 """Returns True if we are in trace mode (tracing detailed test execution)."""
805 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +0000806
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000807 @classmethod
808 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000809 """
810 Python unittest framework class setup fixture.
811 Do current directory manipulation.
812 """
813
Johnny Chenf02ec122010-07-03 20:41:42 +0000814 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000815 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000816 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +0000817
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000818 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000819 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000820
821 # Change current working directory if ${LLDB_TEST} is defined.
822 # See also dotest.py which sets up ${LLDB_TEST}.
823 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000824 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000825 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000826 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
827
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000828 # Set platform context.
829 if sys.platform.startswith('darwin'):
830 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
831 elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):
832 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +0000833 else:
834 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000835
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000836 @classmethod
837 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000838 """
839 Python unittest framework class teardown fixture.
840 Do class-wide cleanup.
841 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000842
Johnny Chen0fddfb22011-11-17 19:57:27 +0000843 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000844 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000845 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000846 if not module.cleanup():
847 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000848
Johnny Chen707b3c92010-10-11 22:25:46 +0000849 # Subclass might have specific cleanup function defined.
850 if getattr(cls, "classCleanup", None):
851 if traceAlways:
852 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
853 try:
854 cls.classCleanup()
855 except:
856 exc_type, exc_value, exc_tb = sys.exc_info()
857 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000858
859 # Restore old working directory.
860 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000861 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000862 os.chdir(cls.oldcwd)
863
Johnny Chena74bb0a2011-08-01 18:46:13 +0000864 @classmethod
865 def skipLongRunningTest(cls):
866 """
867 By default, we skip long running test case.
868 This can be overridden by passing '-l' to the test driver (dotest.py).
869 """
870 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
871 return False
872 else:
873 return True
Johnny Chened492022011-06-21 00:53:00 +0000874
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000875 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000876 """Fixture for unittest test case setup.
877
878 It works with the test driver to conditionally skip tests and does other
879 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000880 #import traceback
881 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000882
Daniel Malea9115f072013-08-06 15:02:32 +0000883 if "LIBCXX_PATH" in os.environ:
884 self.libcxxPath = os.environ["LIBCXX_PATH"]
885 else:
886 self.libcxxPath = None
887
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000888 if "LLDB_EXEC" in os.environ:
889 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000890 else:
891 self.lldbExec = None
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000892 if "LLDBMI_EXEC" in os.environ:
893 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
894 else:
895 self.lldbMiExec = None
896 self.dont_do_lldbmi_test = True
Johnny Chend890bfc2011-08-26 00:00:01 +0000897 if "LLDB_HERE" in os.environ:
898 self.lldbHere = os.environ["LLDB_HERE"]
899 else:
900 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000901 # If we spawn an lldb process for test (via pexpect), do not load the
902 # init file unless told otherwise.
903 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
904 self.lldbOption = ""
905 else:
906 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000907
Johnny Chen985e7402011-08-01 21:13:26 +0000908 # Assign the test method name to self.testMethodName.
909 #
910 # For an example of the use of this attribute, look at test/types dir.
911 # There are a bunch of test cases under test/types and we don't want the
912 # module cacheing subsystem to be confused with executable name "a.out"
913 # used for all the test cases.
914 self.testMethodName = self._testMethodName
915
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000916 # Python API only test is decorated with @python_api_test,
917 # which also sets the "__python_api_test__" attribute of the
918 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000919 try:
920 if lldb.just_do_python_api_test:
921 testMethod = getattr(self, self._testMethodName)
922 if getattr(testMethod, "__python_api_test__", False):
923 pass
924 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000925 self.skipTest("non python api test")
926 except AttributeError:
927 pass
928
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000929 # lldb-mi only test is decorated with @lldbmi_test,
930 # which also sets the "__lldbmi_test__" attribute of the
931 # function object to True.
932 try:
933 if lldb.just_do_lldbmi_test:
934 testMethod = getattr(self, self._testMethodName)
935 if getattr(testMethod, "__lldbmi_test__", False):
936 pass
937 else:
938 self.skipTest("non lldb-mi test")
939 except AttributeError:
940 pass
941
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000942 # Benchmarks test is decorated with @benchmarks_test,
943 # which also sets the "__benchmarks_test__" attribute of the
944 # function object to True.
945 try:
946 if lldb.just_do_benchmarks_test:
947 testMethod = getattr(self, self._testMethodName)
948 if getattr(testMethod, "__benchmarks_test__", False):
949 pass
950 else:
951 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000952 except AttributeError:
953 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000954
Johnny Chen985e7402011-08-01 21:13:26 +0000955 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
956 # with it using pexpect.
957 self.child = None
958 self.child_prompt = "(lldb) "
959 # If the child is interacting with the embedded script interpreter,
960 # there are two exits required during tear down, first to quit the
961 # embedded script interpreter and second to quit the lldb command
962 # interpreter.
963 self.child_in_script_interpreter = False
964
Johnny Chenfb4264c2011-08-01 19:50:58 +0000965 # These are for customized teardown cleanup.
966 self.dict = None
967 self.doTearDownCleanup = False
968 # And in rare cases where there are multiple teardown cleanups.
969 self.dicts = []
970 self.doTearDownCleanups = False
971
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000972 # List of spawned subproces.Popen objects
973 self.subprocesses = []
974
Daniel Malea69207462013-06-05 21:07:02 +0000975 # List of forked process PIDs
976 self.forkedProcessPids = []
977
Johnny Chenfb4264c2011-08-01 19:50:58 +0000978 # Create a string buffer to record the session info, to be dumped into a
979 # test case specific file if test failure is encountered.
980 self.session = StringIO.StringIO()
981
982 # Optimistically set __errored__, __failed__, __expected__ to False
983 # initially. If the test errored/failed, the session info
984 # (self.session) is then dumped into a session specific file for
985 # diagnosis.
986 self.__errored__ = False
987 self.__failed__ = False
988 self.__expected__ = False
989 # We are also interested in unexpected success.
990 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +0000991 # And skipped tests.
992 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +0000993
994 # See addTearDownHook(self, hook) which allows the client to add a hook
995 # function to be run during tearDown() time.
996 self.hooks = []
997
998 # See HideStdout(self).
999 self.sys_stdout_hidden = False
1000
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001001 if self.platformContext:
1002 # set environment variable names for finding shared libraries
1003 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001004
Johnny Chen2a808582011-10-19 16:48:07 +00001005 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001006 """Perform the run hooks to bring lldb debugger to the desired state.
1007
Johnny Chen2a808582011-10-19 16:48:07 +00001008 By default, expect a pexpect spawned child and child prompt to be
1009 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1010 and child prompt and use self.runCmd() to run the hooks one by one.
1011
Johnny Chena737ba52011-10-19 01:06:21 +00001012 Note that child is a process spawned by pexpect.spawn(). If not, your
1013 test case is mostly likely going to fail.
1014
1015 See also dotest.py where lldb.runHooks are processed/populated.
1016 """
1017 if not lldb.runHooks:
1018 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001019 if use_cmd_api:
1020 for hook in lldb.runhooks:
1021 self.runCmd(hook)
1022 else:
1023 if not child or not child_prompt:
1024 self.fail("Both child and child_prompt need to be defined.")
1025 for hook in lldb.runHooks:
1026 child.sendline(hook)
1027 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001028
Daniel Malea249287a2013-02-19 16:08:57 +00001029 def setAsync(self, value):
1030 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1031 old_async = self.dbg.GetAsync()
1032 self.dbg.SetAsync(value)
1033 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1034
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001035 def cleanupSubprocesses(self):
1036 # Ensure any subprocesses are cleaned up
1037 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001038 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001039 del p
1040 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001041 # Ensure any forked processes are cleaned up
1042 for pid in self.forkedProcessPids:
1043 if os.path.exists("/proc/" + str(pid)):
1044 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001045
1046 def spawnSubprocess(self, executable, args=[]):
1047 """ Creates a subprocess.Popen object with the specified executable and arguments,
1048 saves it in self.subprocesses, and returns the object.
1049 NOTE: if using this function, ensure you also call:
1050
1051 self.addTearDownHook(self.cleanupSubprocesses)
1052
1053 otherwise the test suite will leak processes.
1054 """
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001055 proc = _RemoteProcess() if lldb.remote_platform else _LocalProcess(self.TraceOn())
1056 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001057 self.subprocesses.append(proc)
1058 return proc
1059
Daniel Malea69207462013-06-05 21:07:02 +00001060 def forkSubprocess(self, executable, args=[]):
1061 """ Fork a subprocess with its own group ID.
1062 NOTE: if using this function, ensure you also call:
1063
1064 self.addTearDownHook(self.cleanupSubprocesses)
1065
1066 otherwise the test suite will leak processes.
1067 """
1068 child_pid = os.fork()
1069 if child_pid == 0:
1070 # If more I/O support is required, this can be beefed up.
1071 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001072 os.dup2(fd, 1)
1073 os.dup2(fd, 2)
1074 # This call causes the child to have its of group ID
1075 os.setpgid(0,0)
1076 os.execvp(executable, [executable] + args)
1077 # Give the child time to get through the execvp() call
1078 time.sleep(0.1)
1079 self.forkedProcessPids.append(child_pid)
1080 return child_pid
1081
Johnny Chenfb4264c2011-08-01 19:50:58 +00001082 def HideStdout(self):
1083 """Hide output to stdout from the user.
1084
1085 During test execution, there might be cases where we don't want to show the
1086 standard output to the user. For example,
1087
1088 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
1089
1090 tests whether command abbreviation for 'script' works or not. There is no
1091 need to show the 'Hello' output to the user as long as the 'script' command
1092 succeeds and we are not in TraceOn() mode (see the '-t' option).
1093
1094 In this case, the test method calls self.HideStdout(self) to redirect the
1095 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1096
1097 Note that you should only call this method at most once during a test case
1098 execution. Any subsequent call has no effect at all."""
1099 if self.sys_stdout_hidden:
1100 return
1101
1102 self.sys_stdout_hidden = True
1103 old_stdout = sys.stdout
1104 sys.stdout = open(os.devnull, 'w')
1105 def restore_stdout():
1106 sys.stdout = old_stdout
1107 self.addTearDownHook(restore_stdout)
1108
1109 # =======================================================================
1110 # Methods for customized teardown cleanups as well as execution of hooks.
1111 # =======================================================================
1112
1113 def setTearDownCleanup(self, dictionary=None):
1114 """Register a cleanup action at tearDown() time with a dictinary"""
1115 self.dict = dictionary
1116 self.doTearDownCleanup = True
1117
1118 def addTearDownCleanup(self, dictionary):
1119 """Add a cleanup action at tearDown() time with a dictinary"""
1120 self.dicts.append(dictionary)
1121 self.doTearDownCleanups = True
1122
1123 def addTearDownHook(self, hook):
1124 """
1125 Add a function to be run during tearDown() time.
1126
1127 Hooks are executed in a first come first serve manner.
1128 """
1129 if callable(hook):
1130 with recording(self, traceAlways) as sbuf:
1131 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
1132 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001133
1134 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001135
Jim Inghamda3a3862014-10-16 23:02:14 +00001136 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001137 # This is for the case of directly spawning 'lldb' and interacting with it
1138 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001139 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001140 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001141 with recording(self, traceAlways) as sbuf:
1142 print >> sbuf, "tearing down the child process...."
Johnny Chen985e7402011-08-01 21:13:26 +00001143 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001144 if self.child_in_script_interpreter:
1145 self.child.sendline('quit()')
1146 self.child.expect_exact(self.child_prompt)
1147 self.child.sendline('settings set interpreter.prompt-on-quit false')
1148 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001149 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001150 except (ValueError, pexpect.ExceptionPexpect):
1151 # child is already terminated
1152 pass
1153 except OSError as exception:
1154 import errno
1155 if exception.errno != errno.EIO:
1156 # unexpected error
1157 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001158 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001159 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001160 finally:
1161 # Give it one final blow to make sure the child is terminated.
1162 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001163
1164 def tearDown(self):
1165 """Fixture for unittest test case teardown."""
1166 #import traceback
1167 #traceback.print_stack()
1168
1169 self.deletePexpectChild()
1170
Johnny Chenfb4264c2011-08-01 19:50:58 +00001171 # Check and run any hook functions.
1172 for hook in reversed(self.hooks):
1173 with recording(self, traceAlways) as sbuf:
1174 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001175 import inspect
1176 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001177 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001178 hook()
1179 elif hook_argc == 1:
1180 hook(self)
1181 else:
1182 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001183
1184 del self.hooks
1185
1186 # Perform registered teardown cleanup.
1187 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001188 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001189
1190 # In rare cases where there are multiple teardown cleanups added.
1191 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001192 if self.dicts:
1193 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001194 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001195
1196 # Decide whether to dump the session info.
1197 self.dumpSessionInfo()
1198
1199 # =========================================================
1200 # Various callbacks to allow introspection of test progress
1201 # =========================================================
1202
1203 def markError(self):
1204 """Callback invoked when an error (unexpected exception) errored."""
1205 self.__errored__ = True
1206 with recording(self, False) as sbuf:
1207 # False because there's no need to write "ERROR" to the stderr twice.
1208 # Once by the Python unittest framework, and a second time by us.
1209 print >> sbuf, "ERROR"
1210
1211 def markFailure(self):
1212 """Callback invoked when a failure (test assertion failure) occurred."""
1213 self.__failed__ = True
1214 with recording(self, False) as sbuf:
1215 # False because there's no need to write "FAIL" to the stderr twice.
1216 # Once by the Python unittest framework, and a second time by us.
1217 print >> sbuf, "FAIL"
1218
Enrico Granatae6cedc12013-02-23 01:05:23 +00001219 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001220 """Callback invoked when an expected failure/error occurred."""
1221 self.__expected__ = True
1222 with recording(self, False) as sbuf:
1223 # False because there's no need to write "expected failure" to the
1224 # stderr twice.
1225 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001226 if bugnumber == None:
1227 print >> sbuf, "expected failure"
1228 else:
1229 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001230
Johnny Chenc5cc6252011-08-15 23:09:08 +00001231 def markSkippedTest(self):
1232 """Callback invoked when a test is skipped."""
1233 self.__skipped__ = True
1234 with recording(self, False) as sbuf:
1235 # False because there's no need to write "skipped test" to the
1236 # stderr twice.
1237 # Once by the Python unittest framework, and a second time by us.
1238 print >> sbuf, "skipped test"
1239
Enrico Granatae6cedc12013-02-23 01:05:23 +00001240 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001241 """Callback invoked when an unexpected success occurred."""
1242 self.__unexpected__ = True
1243 with recording(self, False) as sbuf:
1244 # False because there's no need to write "unexpected success" to the
1245 # stderr twice.
1246 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001247 if bugnumber == None:
1248 print >> sbuf, "unexpected success"
1249 else:
1250 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001251
Greg Clayton70995582015-01-07 22:25:50 +00001252 def getRerunArgs(self):
1253 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
1254
Johnny Chenfb4264c2011-08-01 19:50:58 +00001255 def dumpSessionInfo(self):
1256 """
1257 Dump the debugger interactions leading to a test error/failure. This
1258 allows for more convenient postmortem analysis.
1259
1260 See also LLDBTestResult (dotest.py) which is a singlton class derived
1261 from TextTestResult and overwrites addError, addFailure, and
1262 addExpectedFailure methods to allow us to to mark the test instance as
1263 such.
1264 """
1265
1266 # We are here because self.tearDown() detected that this test instance
1267 # either errored or failed. The lldb.test_result singleton contains
1268 # two lists (erros and failures) which get populated by the unittest
1269 # framework. Look over there for stack trace information.
1270 #
1271 # The lists contain 2-tuples of TestCase instances and strings holding
1272 # formatted tracebacks.
1273 #
1274 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1275 if self.__errored__:
1276 pairs = lldb.test_result.errors
1277 prefix = 'Error'
1278 elif self.__failed__:
1279 pairs = lldb.test_result.failures
1280 prefix = 'Failure'
1281 elif self.__expected__:
1282 pairs = lldb.test_result.expectedFailures
1283 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001284 elif self.__skipped__:
1285 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001286 elif self.__unexpected__:
1287 prefix = "UnexpectedSuccess"
1288 else:
1289 # Simply return, there's no session info to dump!
1290 return
1291
Johnny Chenc5cc6252011-08-15 23:09:08 +00001292 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001293 for test, traceback in pairs:
1294 if test is self:
1295 print >> self.session, traceback
1296
Johnny Chen8082a002011-08-11 00:16:28 +00001297 testMethod = getattr(self, self._testMethodName)
1298 if getattr(testMethod, "__benchmarks_test__", False):
1299 benchmarks = True
1300 else:
1301 benchmarks = False
1302
Johnny Chenfb4264c2011-08-01 19:50:58 +00001303 dname = os.path.join(os.environ["LLDB_TEST"],
1304 os.environ["LLDB_SESSION_DIRNAME"])
1305 if not os.path.isdir(dname):
1306 os.mkdir(dname)
Zachary Turner756acba2014-10-14 21:54:14 +00001307 compiler = self.getCompiler()
1308 if compiler[1] == ':':
1309 compiler = compiler[2:]
1310
1311 fname = os.path.join(dname, "%s-%s-%s-%s.log" % (prefix, self.getArchitecture(), "_".join(compiler.split(os.path.sep)), self.id()))
Johnny Chenfb4264c2011-08-01 19:50:58 +00001312 with open(fname, "w") as f:
1313 import datetime
1314 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1315 print >> f, self.session.getvalue()
1316 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Greg Clayton70995582015-01-07 22:25:50 +00001317 print >> f, "./dotest.py %s -v %s %s" % (self.getRunOptions(),
1318 ('+b' if benchmarks else '-t'),
1319 self.getRerunArgs())
Johnny Chenfb4264c2011-08-01 19:50:58 +00001320
1321 # ====================================================
1322 # Config. methods supported through a plugin interface
1323 # (enables reading of the current test configuration)
1324 # ====================================================
1325
1326 def getArchitecture(self):
1327 """Returns the architecture in effect the test suite is running with."""
1328 module = builder_module()
1329 return module.getArchitecture()
1330
1331 def getCompiler(self):
1332 """Returns the compiler in effect the test suite is running with."""
1333 module = builder_module()
1334 return module.getCompiler()
1335
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001336 def getCompilerBinary(self):
1337 """Returns the compiler binary the test suite is running with."""
1338 return self.getCompiler().split()[0]
1339
Daniel Malea0aea0162013-02-27 17:29:46 +00001340 def getCompilerVersion(self):
1341 """ Returns a string that represents the compiler version.
1342 Supports: llvm, clang.
1343 """
1344 from lldbutil import which
1345 version = 'unknown'
1346
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001347 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001348 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001349 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001350 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001351 if m:
1352 version = m.group(1)
1353 return version
1354
Daniel Maleaadaaec92013-08-06 20:51:41 +00001355 def isIntelCompiler(self):
1356 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1357 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1358
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001359 def expectedCompilerVersion(self, compiler_version):
1360 """Returns True iff compiler_version[1] matches the current compiler version.
1361 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1362 Any operator other than the following defaults to an equality test:
1363 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1364 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001365 if (compiler_version == None):
1366 return True
1367 operator = str(compiler_version[0])
1368 version = compiler_version[1]
1369
1370 if (version == None):
1371 return True
1372 if (operator == '>'):
1373 return self.getCompilerVersion() > version
1374 if (operator == '>=' or operator == '=>'):
1375 return self.getCompilerVersion() >= version
1376 if (operator == '<'):
1377 return self.getCompilerVersion() < version
1378 if (operator == '<=' or operator == '=<'):
1379 return self.getCompilerVersion() <= version
1380 if (operator == '!=' or operator == '!' or operator == 'not'):
1381 return str(version) not in str(self.getCompilerVersion())
1382 return str(version) in str(self.getCompilerVersion())
1383
1384 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001385 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001386 if (compilers == None):
1387 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001388
1389 for compiler in compilers:
1390 if compiler in self.getCompiler():
1391 return True
1392
1393 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001394
Johnny Chenfb4264c2011-08-01 19:50:58 +00001395 def getRunOptions(self):
1396 """Command line option for -A and -C to run this test again, called from
1397 self.dumpSessionInfo()."""
1398 arch = self.getArchitecture()
1399 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001400 if arch:
1401 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001402 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001403 option_str = ""
1404 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001405 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001406 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001407
1408 # ==================================================
1409 # Build methods supported through a plugin interface
1410 # ==================================================
1411
Ed Mastec97323e2014-04-01 18:47:58 +00001412 def getstdlibFlag(self):
1413 """ Returns the proper -stdlib flag, or empty if not required."""
1414 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
1415 stdlibflag = "-stdlib=libc++"
1416 else:
1417 stdlibflag = ""
1418 return stdlibflag
1419
Matt Kopec7663b3a2013-09-25 17:44:00 +00001420 def getstdFlag(self):
1421 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00001422 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00001423 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00001424 else:
1425 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00001426 return stdflag
1427
1428 def buildDriver(self, sources, exe_name):
1429 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1430 or LLDB.framework).
1431 """
1432
1433 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00001434 stdlibflag = self.getstdlibFlag()
Daniel Malea55faa402013-05-02 21:44:31 +00001435
1436 if sys.platform.startswith("darwin"):
1437 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1438 d = {'CXX_SOURCES' : sources,
1439 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001440 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Daniel Malea55faa402013-05-02 21:44:31 +00001441 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Stefanus Du Toit04004442013-07-30 19:19:49 +00001442 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, self.lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00001443 }
Ed Maste372c24d2013-07-25 21:02:34 +00001444 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Daniel Malea55faa402013-05-02 21:44:31 +00001445 d = {'CXX_SOURCES' : sources,
1446 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001447 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Daniel Malea55faa402013-05-02 21:44:31 +00001448 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
1449 if self.TraceOn():
1450 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1451
1452 self.buildDefault(dictionary=d)
1453
Matt Kopec7663b3a2013-09-25 17:44:00 +00001454 def buildLibrary(self, sources, lib_name):
1455 """Platform specific way to build a default library. """
1456
1457 stdflag = self.getstdFlag()
1458
1459 if sys.platform.startswith("darwin"):
1460 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1461 d = {'DYLIB_CXX_SOURCES' : sources,
1462 'DYLIB_NAME' : lib_name,
1463 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1464 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
1465 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, self.lib_dir),
1466 }
1467 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
1468 d = {'DYLIB_CXX_SOURCES' : sources,
1469 'DYLIB_NAME' : lib_name,
1470 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1471 'LD_EXTRAS' : "-shared -L%s -llldb" % self.lib_dir}
1472 if self.TraceOn():
1473 print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
1474
1475 self.buildDefault(dictionary=d)
1476
Daniel Malea55faa402013-05-02 21:44:31 +00001477 def buildProgram(self, sources, exe_name):
1478 """ Platform specific way to build an executable from C/C++ sources. """
1479 d = {'CXX_SOURCES' : sources,
1480 'EXE' : exe_name}
1481 self.buildDefault(dictionary=d)
1482
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001483 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001484 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001485 if lldb.skip_build_and_cleanup:
1486 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001487 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001488 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001489 raise Exception("Don't know how to build default binary")
1490
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001491 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001492 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001493 if lldb.skip_build_and_cleanup:
1494 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001495 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001496 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001497 raise Exception("Don't know how to build binary with dsym")
1498
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001499 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001500 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001501 if lldb.skip_build_and_cleanup:
1502 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001503 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001504 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001505 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00001506
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00001507 def signBinary(self, binary_path):
1508 if sys.platform.startswith("darwin"):
1509 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
1510 call(codesign_cmd, shell=True)
1511
Kuba Breckabeed8212014-09-04 01:03:18 +00001512 def findBuiltClang(self):
1513 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
1514 paths_to_try = [
1515 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
1516 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
1517 "llvm-build/Release/x86_64/Release/bin/clang",
1518 "llvm-build/Debug/x86_64/Debug/bin/clang",
1519 ]
1520 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
1521 for p in paths_to_try:
1522 path = os.path.join(lldb_root_path, p)
1523 if os.path.exists(path):
1524 return path
1525
1526 return os.environ["CC"]
1527
Tamas Berghammer765b5e52015-02-25 13:26:28 +00001528 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001529 """ Returns a dictionary (which can be provided to build* functions above) which
1530 contains OS-specific build flags.
1531 """
1532 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00001533 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00001534
1535 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
1536 if not use_libstdcxx and sys.platform.startswith('darwin'):
1537 use_libcxx = True
1538
1539 if use_libcxx and self.libcxxPath:
1540 cflags += "-stdlib=libc++ "
1541 if self.libcxxPath:
1542 libcxxInclude = os.path.join(self.libcxxPath, "include")
1543 libcxxLib = os.path.join(self.libcxxPath, "lib")
1544 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
1545 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
1546
Andrew Kaylor93132f52013-05-28 23:04:25 +00001547 if use_cpp11:
1548 cflags += "-std="
1549 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1550 cflags += "c++0x"
1551 else:
1552 cflags += "c++11"
Ed Mastedbd59502014-02-02 19:24:15 +00001553 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001554 cflags += " -stdlib=libc++"
1555 elif "clang" in self.getCompiler():
1556 cflags += " -stdlib=libstdc++"
1557
Andrew Kaylor93132f52013-05-28 23:04:25 +00001558 return {'CFLAGS_EXTRAS' : cflags,
1559 'LD_EXTRAS' : ldflags,
1560 }
1561
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001562 def cleanup(self, dictionary=None):
1563 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001564 if lldb.skip_build_and_cleanup:
1565 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001566 module = builder_module()
1567 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001568 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001569
Daniel Malea55faa402013-05-02 21:44:31 +00001570 def getLLDBLibraryEnvVal(self):
1571 """ Returns the path that the OS-specific library search environment variable
1572 (self.dylibPath) should be set to in order for a program to find the LLDB
1573 library. If an environment variable named self.dylibPath is already set,
1574 the new path is appended to it and returned.
1575 """
1576 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1577 if existing_library_path:
1578 return "%s:%s" % (existing_library_path, self.lib_dir)
1579 elif sys.platform.startswith("darwin"):
1580 return os.path.join(self.lib_dir, 'LLDB.framework')
1581 else:
1582 return self.lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00001583
Ed Maste437f8f62013-09-09 14:04:04 +00001584 def getLibcPlusPlusLibs(self):
1585 if sys.platform.startswith('freebsd'):
1586 return ['libc++.so.1']
1587 else:
1588 return ['libc++.1.dylib','libc++abi.dylib']
1589
Johnny Chena74bb0a2011-08-01 18:46:13 +00001590class TestBase(Base):
1591 """
1592 This abstract base class is meant to be subclassed. It provides default
1593 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1594 among other things.
1595
1596 Important things for test class writers:
1597
1598 - Overwrite the mydir class attribute, otherwise your test class won't
1599 run. It specifies the relative directory to the top level 'test' so
1600 the test harness can change to the correct working directory before
1601 running your test.
1602
1603 - The setUp method sets up things to facilitate subsequent interactions
1604 with the debugger as part of the test. These include:
1605 - populate the test method name
1606 - create/get a debugger set with synchronous mode (self.dbg)
1607 - get the command interpreter from with the debugger (self.ci)
1608 - create a result object for use with the command interpreter
1609 (self.res)
1610 - plus other stuffs
1611
1612 - The tearDown method tries to perform some necessary cleanup on behalf
1613 of the test to return the debugger to a good state for the next test.
1614 These include:
1615 - execute any tearDown hooks registered by the test method with
1616 TestBase.addTearDownHook(); examples can be found in
1617 settings/TestSettings.py
1618 - kill the inferior process associated with each target, if any,
1619 and, then delete the target from the debugger's target list
1620 - perform build cleanup before running the next test method in the
1621 same test class; examples of registering for this service can be
1622 found in types/TestIntegerTypes.py with the call:
1623 - self.setTearDownCleanup(dictionary=d)
1624
1625 - Similarly setUpClass and tearDownClass perform classwise setup and
1626 teardown fixtures. The tearDownClass method invokes a default build
1627 cleanup for the entire test class; also, subclasses can implement the
1628 classmethod classCleanup(cls) to perform special class cleanup action.
1629
1630 - The instance methods runCmd and expect are used heavily by existing
1631 test cases to send a command to the command interpreter and to perform
1632 string/pattern matching on the output of such command execution. The
1633 expect method also provides a mode to peform string/pattern matching
1634 without running a command.
1635
1636 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1637 build the binaries used during a particular test scenario. A plugin
1638 should be provided for the sys.platform running the test suite. The
1639 Mac OS X implementation is located in plugins/darwin.py.
1640 """
1641
1642 # Maximum allowed attempts when launching the inferior process.
1643 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1644 maxLaunchCount = 3;
1645
1646 # Time to wait before the next launching attempt in second(s).
1647 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1648 timeWaitNextLaunch = 1.0;
1649
1650 def doDelay(self):
1651 """See option -w of dotest.py."""
1652 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1653 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1654 waitTime = 1.0
1655 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1656 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1657 time.sleep(waitTime)
1658
Enrico Granata165f8af2012-09-21 19:10:53 +00001659 # Returns the list of categories to which this test case belongs
1660 # by default, look for a ".categories" file, and read its contents
1661 # if no such file exists, traverse the hierarchy - we guarantee
1662 # a .categories to exist at the top level directory so we do not end up
1663 # looping endlessly - subclasses are free to define their own categories
1664 # in whatever way makes sense to them
1665 def getCategories(self):
1666 import inspect
1667 import os.path
1668 folder = inspect.getfile(self.__class__)
1669 folder = os.path.dirname(folder)
1670 while folder != '/':
1671 categories_file_name = os.path.join(folder,".categories")
1672 if os.path.exists(categories_file_name):
1673 categories_file = open(categories_file_name,'r')
1674 categories = categories_file.readline()
1675 categories_file.close()
1676 categories = str.replace(categories,'\n','')
1677 categories = str.replace(categories,'\r','')
1678 return categories.split(',')
1679 else:
1680 folder = os.path.dirname(folder)
1681 continue
1682
Johnny Chena74bb0a2011-08-01 18:46:13 +00001683 def setUp(self):
1684 #import traceback
1685 #traceback.print_stack()
1686
1687 # Works with the test driver to conditionally skip tests via decorators.
1688 Base.setUp(self)
1689
Johnny Chena74bb0a2011-08-01 18:46:13 +00001690 try:
1691 if lldb.blacklist:
1692 className = self.__class__.__name__
1693 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1694 if className in lldb.blacklist:
1695 self.skipTest(lldb.blacklist.get(className))
1696 elif classAndMethodName in lldb.blacklist:
1697 self.skipTest(lldb.blacklist.get(classAndMethodName))
1698 except AttributeError:
1699 pass
1700
Johnny Chened492022011-06-21 00:53:00 +00001701 # Insert some delay between successive test cases if specified.
1702 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00001703
Johnny Chenf2b70232010-08-25 18:49:48 +00001704 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1705 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1706
Johnny Chen430eb762010-10-19 16:00:42 +00001707 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00001708 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00001709
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001710 # Create the debugger instance if necessary.
1711 try:
1712 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001713 except AttributeError:
1714 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +00001715
Johnny Chen3cd1e552011-05-25 19:06:18 +00001716 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001717 raise Exception('Invalid debugger instance')
1718
Daniel Maleae0f8f572013-08-26 23:57:52 +00001719 #
1720 # Warning: MAJOR HACK AHEAD!
1721 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
1722 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
1723 # command, instead. See also runCmd() where it decorates the "file filename" call
1724 # with additional functionality when running testsuite remotely.
1725 #
1726 if lldb.lldbtest_remote_sandbox:
1727 def DecoratedCreateTarget(arg):
1728 self.runCmd("file %s" % arg)
1729 target = self.dbg.GetSelectedTarget()
1730 #
Greg Claytonc6947512013-12-13 19:18:59 +00001731 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00001732 # johnny @ 04/23/2012
1733 #
1734 def DecoratedLaunchSimple(argv, envp, wd):
1735 self.runCmd("run")
1736 return target.GetProcess()
1737 target.LaunchSimple = DecoratedLaunchSimple
1738
1739 return target
1740 self.dbg.CreateTarget = DecoratedCreateTarget
1741 if self.TraceOn():
1742 print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
1743
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001744 # We want our debugger to be synchronous.
1745 self.dbg.SetAsync(False)
1746
1747 # Retrieve the associated command interpreter instance.
1748 self.ci = self.dbg.GetCommandInterpreter()
1749 if not self.ci:
1750 raise Exception('Could not get the command interpreter')
1751
1752 # And the result object.
1753 self.res = lldb.SBCommandReturnObject()
1754
Johnny Chen44d24972012-04-16 18:55:15 +00001755 # Run global pre-flight code, if defined via the config file.
1756 if lldb.pre_flight:
1757 lldb.pre_flight(self)
1758
Greg Claytonfb909312013-11-23 01:58:15 +00001759 if lldb.remote_platform:
1760 #remote_test_dir = os.path.join(lldb.remote_platform_working_dir, self.mydir)
Greg Clayton5fb8f792013-12-02 19:35:49 +00001761 remote_test_dir = os.path.join(lldb.remote_platform_working_dir,
1762 self.getArchitecture(),
1763 str(self.test_number),
1764 self.mydir)
Greg Claytonfb909312013-11-23 01:58:15 +00001765 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 0700)
1766 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00001767 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
1768 else:
1769 print "error: making remote directory '%s': %s" % (remote_test_dir, error)
1770
Greg Clayton35c91342014-11-17 18:40:27 +00001771 def registerSharedLibrariesWithTarget(self, target, shlibs):
1772 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
1773
1774 Any modules in the target that have their remote install file specification set will
1775 get uploaded to the remote host. This function registers the local copies of the
1776 shared libraries with the target and sets their remote install locations so they will
1777 be uploaded when the target is run.
1778 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001779 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001780 return None
Greg Clayton35c91342014-11-17 18:40:27 +00001781
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001782 shlib_environment_var = self.platformContext.shlib_environment_var
1783 shlib_prefix = self.platformContext.shlib_prefix
1784 shlib_extension = '.' + self.platformContext.shlib_extension
1785
1786 working_dir = self.get_process_working_directory()
1787 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
1788 # Add any shared libraries to our target if remote so they get
1789 # uploaded into the working directory on the remote side
1790 for name in shlibs:
1791 # The path can be a full path to a shared library, or a make file name like "Foo" for
1792 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
1793 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
1794 # of the shared library accordingly
1795 if os.path.exists(name):
1796 local_shlib_path = name # name is the full path to the local shared library
1797 else:
1798 # Check relative names
1799 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
1800 if not os.path.exists(local_shlib_path):
1801 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00001802 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001803 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00001804
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001805 # Make sure we found the local shared library in the above code
1806 self.assertTrue(os.path.exists(local_shlib_path))
1807
1808 # Add the shared library to our target
1809 shlib_module = target.AddModule(local_shlib_path, None, None, None)
1810 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00001811 # We must set the remote install location if we want the shared library
1812 # to get uploaded to the remote target
1813 remote_shlib_path = os.path.join(lldb.remote_platform.GetWorkingDirectory(), os.path.basename(local_shlib_path))
1814 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001815
1816 return environment
1817
Enrico Granata44818162012-10-24 01:23:57 +00001818 # utility methods that tests can use to access the current objects
1819 def target(self):
1820 if not self.dbg:
1821 raise Exception('Invalid debugger instance')
1822 return self.dbg.GetSelectedTarget()
1823
1824 def process(self):
1825 if not self.dbg:
1826 raise Exception('Invalid debugger instance')
1827 return self.dbg.GetSelectedTarget().GetProcess()
1828
1829 def thread(self):
1830 if not self.dbg:
1831 raise Exception('Invalid debugger instance')
1832 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1833
1834 def frame(self):
1835 if not self.dbg:
1836 raise Exception('Invalid debugger instance')
1837 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1838
Greg Claytonc6947512013-12-13 19:18:59 +00001839 def get_process_working_directory(self):
1840 '''Get the working directory that should be used when launching processes for local or remote processes.'''
1841 if lldb.remote_platform:
1842 # Remote tests set the platform working directory up in TestBase.setUp()
1843 return lldb.remote_platform.GetWorkingDirectory()
1844 else:
1845 # local tests change directory into each test subdirectory
1846 return os.getcwd()
1847
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001848 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001849 #import traceback
1850 #traceback.print_stack()
1851
Johnny Chenfb4264c2011-08-01 19:50:58 +00001852 Base.tearDown(self)
Johnny Chen707d8222010-10-19 23:40:13 +00001853
Johnny Chen3794ad92011-06-15 21:24:24 +00001854 # Delete the target(s) from the debugger as a general cleanup step.
1855 # This includes terminating the process for each target, if any.
1856 # We'd like to reuse the debugger for our next test without incurring
1857 # the initialization overhead.
1858 targets = []
1859 for target in self.dbg:
1860 if target:
1861 targets.append(target)
1862 process = target.GetProcess()
1863 if process:
1864 rc = self.invoke(process, "Kill")
1865 self.assertTrue(rc.Success(), PROCESS_KILLED)
1866 for target in targets:
1867 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001868
Johnny Chen44d24972012-04-16 18:55:15 +00001869 # Run global post-flight code, if defined via the config file.
1870 if lldb.post_flight:
1871 lldb.post_flight(self)
1872
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001873 del self.dbg
Johnny Chen150c3cc2010-10-15 01:18:29 +00001874
Johnny Chen86268e42011-09-30 21:48:35 +00001875 def switch_to_thread_with_stop_reason(self, stop_reason):
1876 """
1877 Run the 'thread list' command, and select the thread with stop reason as
1878 'stop_reason'. If no such thread exists, no select action is done.
1879 """
1880 from lldbutil import stop_reason_to_str
1881 self.runCmd('thread list')
1882 output = self.res.GetOutput()
1883 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1884 stop_reason_to_str(stop_reason))
1885 for line in output.splitlines():
1886 matched = thread_line_pattern.match(line)
1887 if matched:
1888 self.runCmd('thread select %s' % matched.group(1))
1889
Enrico Granata7594f142013-06-17 22:51:50 +00001890 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001891 """
1892 Ask the command interpreter to handle the command and then check its
1893 return status.
1894 """
1895 # Fail fast if 'cmd' is not meaningful.
1896 if not cmd or len(cmd) == 0:
1897 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001898
Johnny Chen8d55a342010-08-31 17:42:54 +00001899 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001900
Daniel Maleae0f8f572013-08-26 23:57:52 +00001901 # This is an opportunity to insert the 'platform target-install' command if we are told so
1902 # via the settig of lldb.lldbtest_remote_sandbox.
1903 if cmd.startswith("target create "):
1904 cmd = cmd.replace("target create ", "file ")
1905 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
1906 with recording(self, trace) as sbuf:
1907 the_rest = cmd.split("file ")[1]
1908 # Split the rest of the command line.
1909 atoms = the_rest.split()
1910 #
1911 # NOTE: This assumes that the options, if any, follow the file command,
1912 # instead of follow the specified target.
1913 #
1914 target = atoms[-1]
1915 # Now let's get the absolute pathname of our target.
1916 abs_target = os.path.abspath(target)
1917 print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
1918 fpath, fname = os.path.split(abs_target)
1919 parent_dir = os.path.split(fpath)[0]
1920 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
1921 print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
1922 self.ci.HandleCommand(platform_target_install_command, self.res)
1923 # And this is the file command we want to execute, instead.
1924 #
1925 # Warning: SIDE EFFECT AHEAD!!!
1926 # Populate the remote executable pathname into the lldb namespace,
1927 # so that test cases can grab this thing out of the namespace.
1928 #
1929 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
1930 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
1931 print >> sbuf, "And this is the replaced file command: %s" % cmd
1932
Johnny Chen63dfb272010-09-01 00:15:19 +00001933 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001934
Johnny Chen63dfb272010-09-01 00:15:19 +00001935 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00001936 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001937
Johnny Chen150c3cc2010-10-15 01:18:29 +00001938 with recording(self, trace) as sbuf:
1939 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00001940 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00001941 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00001942 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00001943 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00001944 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001945 print >> sbuf, "runCmd failed!"
1946 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001947
Johnny Chenff3d01d2010-08-20 21:03:09 +00001948 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00001949 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00001950 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00001951 # For process launch, wait some time before possible next try.
1952 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00001953 with recording(self, trace) as sbuf:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001954 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001955
Johnny Chen27f212d2010-08-19 23:26:59 +00001956 if check:
1957 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00001958 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00001959
Jim Ingham63dfc722012-09-22 00:05:11 +00001960 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
1961 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
1962
1963 Otherwise, all the arguments have the same meanings as for the expect function"""
1964
1965 trace = (True if traceAlways else trace)
1966
1967 if exe:
1968 # First run the command. If we are expecting error, set check=False.
1969 # Pass the assert message along since it provides more semantic info.
1970 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
1971
1972 # Then compare the output against expected strings.
1973 output = self.res.GetError() if error else self.res.GetOutput()
1974
1975 # If error is True, the API client expects the command to fail!
1976 if error:
1977 self.assertFalse(self.res.Succeeded(),
1978 "Command '" + str + "' is expected to fail!")
1979 else:
1980 # No execution required, just compare str against the golden input.
1981 output = str
1982 with recording(self, trace) as sbuf:
1983 print >> sbuf, "looking at:", output
1984
1985 # The heading says either "Expecting" or "Not expecting".
1986 heading = "Expecting" if matching else "Not expecting"
1987
1988 for pattern in patterns:
1989 # Match Objects always have a boolean value of True.
1990 match_object = re.search(pattern, output)
1991 matched = bool(match_object)
1992 with recording(self, trace) as sbuf:
1993 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1994 print >> sbuf, "Matched" if matched else "Not matched"
1995 if matched:
1996 break
1997
1998 self.assertTrue(matched if matching else not matched,
1999 msg if msg else EXP_MSG(str, exe))
2000
2001 return match_object
2002
Enrico Granata7594f142013-06-17 22:51:50 +00002003 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 +00002004 """
2005 Similar to runCmd; with additional expect style output matching ability.
2006
2007 Ask the command interpreter to handle the command and then check its
2008 return status. The 'msg' parameter specifies an informational assert
2009 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002010 'startstr', matches the substrings contained in 'substrs', and regexp
2011 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002012
2013 If the keyword argument error is set to True, it signifies that the API
2014 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002015 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002016 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002017
2018 If the keyword argument matching is set to False, it signifies that the API
2019 client is expecting the output of the command not to match the golden
2020 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002021
2022 Finally, the required argument 'str' represents the lldb command to be
2023 sent to the command interpreter. In case the keyword argument 'exe' is
2024 set to False, the 'str' is treated as a string to be matched/not-matched
2025 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002026 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002027 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002028
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002029 if exe:
2030 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002031 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002032 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002033
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002034 # Then compare the output against expected strings.
2035 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002036
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002037 # If error is True, the API client expects the command to fail!
2038 if error:
2039 self.assertFalse(self.res.Succeeded(),
2040 "Command '" + str + "' is expected to fail!")
2041 else:
2042 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002043 if isinstance(str,lldb.SBCommandReturnObject):
2044 output = str.GetOutput()
2045 else:
2046 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002047 with recording(self, trace) as sbuf:
2048 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00002049
Johnny Chenea88e942010-09-21 21:08:53 +00002050 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002051 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002052
2053 # Start from the startstr, if specified.
2054 # If there's no startstr, set the initial state appropriately.
2055 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002056
Johnny Chen150c3cc2010-10-15 01:18:29 +00002057 if startstr:
2058 with recording(self, trace) as sbuf:
2059 print >> sbuf, "%s start string: %s" % (heading, startstr)
2060 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00002061
Johnny Chen86268e42011-09-30 21:48:35 +00002062 # Look for endstr, if specified.
2063 keepgoing = matched if matching else not matched
2064 if endstr:
2065 matched = output.endswith(endstr)
2066 with recording(self, trace) as sbuf:
2067 print >> sbuf, "%s end string: %s" % (heading, endstr)
2068 print >> sbuf, "Matched" if matched else "Not matched"
2069
Johnny Chenea88e942010-09-21 21:08:53 +00002070 # Look for sub strings, if specified.
2071 keepgoing = matched if matching else not matched
2072 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002073 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002074 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002075 with recording(self, trace) as sbuf:
2076 print >> sbuf, "%s sub string: %s" % (heading, str)
2077 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00002078 keepgoing = matched if matching else not matched
2079 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002080 break
2081
Johnny Chenea88e942010-09-21 21:08:53 +00002082 # Search for regular expression patterns, if specified.
2083 keepgoing = matched if matching else not matched
2084 if patterns and keepgoing:
2085 for pattern in patterns:
2086 # Match Objects always have a boolean value of True.
2087 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002088 with recording(self, trace) as sbuf:
2089 print >> sbuf, "%s pattern: %s" % (heading, pattern)
2090 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00002091 keepgoing = matched if matching else not matched
2092 if not keepgoing:
2093 break
Johnny Chenea88e942010-09-21 21:08:53 +00002094
2095 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002096 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002097
Johnny Chenf3c59232010-08-25 22:52:45 +00002098 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002099 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002100 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002101
2102 method = getattr(obj, name)
2103 import inspect
2104 self.assertTrue(inspect.ismethod(method),
2105 name + "is a method name of object: " + str(obj))
2106 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002107 with recording(self, trace) as sbuf:
2108 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00002109 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002110
Johnny Chenf359cf22011-05-27 23:36:52 +00002111 # =================================================
2112 # Misc. helper methods for debugging test execution
2113 # =================================================
2114
Johnny Chen56b92a72011-07-11 19:15:11 +00002115 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002116 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00002117 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002118
Johnny Chen8d55a342010-08-31 17:42:54 +00002119 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002120 return
2121
2122 err = sys.stderr
2123 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002124 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2125 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2126 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2127 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2128 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2129 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2130 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2131 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2132 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002133
Johnny Chen36c5eb12011-08-05 20:17:27 +00002134 def DebugSBType(self, type):
2135 """Debug print a SBType object, if traceAlways is True."""
2136 if not traceAlways:
2137 return
2138
2139 err = sys.stderr
2140 err.write(type.GetName() + ":\n")
2141 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2142 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2143 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2144
Johnny Chenb877f1e2011-03-12 01:18:19 +00002145 def DebugPExpect(self, child):
2146 """Debug the spwaned pexpect object."""
2147 if not traceAlways:
2148 return
2149
2150 print child
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002151
2152 @classmethod
2153 def RemoveTempFile(cls, file):
2154 if os.path.exists(file):
2155 os.remove(file)