blob: 9c96018eb01fbc241609be121c8909e4e8c5c55c [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
Johnny Chen90312a82010-09-21 22:34:45 +000034import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000035import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000036import re
Daniel Malea69207462013-06-05 21:07:02 +000037import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000038from subprocess import *
Johnny Chen150c3cc2010-10-15 01:18:29 +000039import StringIO
Johnny Chenf2b70232010-08-25 18:49:48 +000040import time
Johnny Chena33a93c2010-08-30 23:08:52 +000041import types
Johnny Chen73258832010-08-05 23:42:46 +000042import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +000043import lldb
44
Johnny Chen707b3c92010-10-11 22:25:46 +000045# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000046# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000047
48# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000049if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
50 traceAlways = True
51else:
52 traceAlways = False
53
Johnny Chen707b3c92010-10-11 22:25:46 +000054# By default, doCleanup is True.
55if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
56 doCleanup = False
57else:
58 doCleanup = True
59
Johnny Chen8d55a342010-08-31 17:42:54 +000060
Johnny Chen00778092010-08-09 22:01:17 +000061#
62# Some commonly used assert messages.
63#
64
Johnny Chenaa902922010-09-17 22:45:27 +000065COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
66
Johnny Chen00778092010-08-09 22:01:17 +000067CURRENT_EXECUTABLE_SET = "Current executable set successfully"
68
Johnny Chen7d1d7532010-09-02 21:23:12 +000069PROCESS_IS_VALID = "Process is valid"
70
71PROCESS_KILLED = "Process is killed successfully"
72
Johnny Chend5f66fc2010-12-23 01:12:19 +000073PROCESS_EXITED = "Process exited successfully"
74
75PROCESS_STOPPED = "Process status should be stopped"
76
Johnny Chen5ee88192010-08-27 23:47:36 +000077RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +000078
Johnny Chen17941842010-08-09 23:44:24 +000079RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +000080
Johnny Chen67af43f2010-10-05 19:27:32 +000081BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
82
Johnny Chen17941842010-08-09 23:44:24 +000083BREAKPOINT_CREATED = "Breakpoint created successfully"
84
Johnny Chenf10af382010-12-04 00:07:24 +000085BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
86
Johnny Chene76896c2010-08-17 21:33:31 +000087BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
88
Johnny Chen17941842010-08-09 23:44:24 +000089BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +000090
Johnny Chen703dbd02010-09-30 17:06:24 +000091BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
92
Johnny Chen164f1e12010-10-15 18:07:09 +000093BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
94
Greg Clayton5db6b792012-10-24 18:24:14 +000095MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
96
Johnny Chen89109ed12011-06-27 20:05:23 +000097OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
98
Johnny Chen5b3a3572010-12-09 18:22:12 +000099SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
100
Johnny Chenc70b02a2010-09-22 23:00:20 +0000101STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
102
Johnny Chen1691a162011-04-15 16:44:48 +0000103STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
104
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000105STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
106
Johnny Chen5d6c4642010-11-10 23:46:38 +0000107STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000108
Johnny Chen5d6c4642010-11-10 23:46:38 +0000109STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
110 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000111
Johnny Chen2e431ce2010-10-20 18:38:48 +0000112STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
113
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000114STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
115
Johnny Chenc066ab42010-10-14 01:22:03 +0000116STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
117
Johnny Chen00778092010-08-09 22:01:17 +0000118STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
119
Johnny Chenf68cc122011-09-15 21:09:59 +0000120STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
121
Johnny Chen3c884a02010-08-24 22:07:56 +0000122DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
123
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000124VALID_BREAKPOINT = "Got a valid breakpoint"
125
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000126VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
127
Johnny Chen7209d84f2011-05-06 23:26:12 +0000128VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
129
Johnny Chen5ee88192010-08-27 23:47:36 +0000130VALID_FILESPEC = "Got a valid filespec"
131
Johnny Chen025d1b82010-12-08 01:25:21 +0000132VALID_MODULE = "Got a valid module"
133
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000134VALID_PROCESS = "Got a valid process"
135
Johnny Chen025d1b82010-12-08 01:25:21 +0000136VALID_SYMBOL = "Got a valid symbol"
137
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000138VALID_TARGET = "Got a valid target"
139
Matthew Gardinerc928de32014-10-22 07:22:56 +0000140VALID_PLATFORM = "Got a valid platform"
141
Johnny Chen15f247a2012-02-03 20:43:00 +0000142VALID_TYPE = "Got a valid type"
143
Johnny Chen5819ab42011-07-15 22:28:10 +0000144VALID_VARIABLE = "Got a valid variable"
145
Johnny Chen981463d2010-08-25 19:00:04 +0000146VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000147
Johnny Chenf68cc122011-09-15 21:09:59 +0000148WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000149
Johnny Chenc0c67f22010-11-09 18:42:22 +0000150def CMD_MSG(str):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000151 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000152 return "Command '%s' returns successfully" % str
153
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000154def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000155 '''A generic message generator for the completion mechanism.'''
156 return "'%s' successfully completes to '%s'" % (str_before, str_after)
157
Johnny Chenc0c67f22010-11-09 18:42:22 +0000158def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000159 '''A generic "'%s' returns expected result" message generator if exe.
160 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000161 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000162
Johnny Chen3343f042010-10-19 19:11:38 +0000163def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000164 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000165 return "Value of setting '%s' is correct" % setting
166
Johnny Chen27c41232010-08-26 21:49:29 +0000167def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000168 """Returns an env variable array from the os.environ map object."""
Johnny Chen27c41232010-08-26 21:49:29 +0000169 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
170
Johnny Chen47ceb032010-10-11 23:52:19 +0000171def line_number(filename, string_to_match):
172 """Helper function to return the line number of the first matched string."""
173 with open(filename, 'r') as f:
174 for i, line in enumerate(f):
175 if line.find(string_to_match) != -1:
176 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000177 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000178 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000179
Johnny Chen67af43f2010-10-05 19:27:32 +0000180def pointer_size():
181 """Return the pointer size of the host system."""
182 import ctypes
183 a_pointer = ctypes.c_void_p(0xffff)
184 return 8 * ctypes.sizeof(a_pointer)
185
Johnny Chen57816732012-02-09 02:01:59 +0000186def is_exe(fpath):
187 """Returns true if fpath is an executable."""
188 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
189
190def which(program):
191 """Returns the full path to a program; None otherwise."""
192 fpath, fname = os.path.split(program)
193 if fpath:
194 if is_exe(program):
195 return program
196 else:
197 for path in os.environ["PATH"].split(os.pathsep):
198 exe_file = os.path.join(path, program)
199 if is_exe(exe_file):
200 return exe_file
201 return None
202
Johnny Chen150c3cc2010-10-15 01:18:29 +0000203class recording(StringIO.StringIO):
204 """
205 A nice little context manager for recording the debugger interactions into
206 our session object. If trace flag is ON, it also emits the interactions
207 into the stderr.
208 """
209 def __init__(self, test, trace):
Johnny Chen690fcef2010-10-15 23:55:05 +0000210 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen150c3cc2010-10-15 01:18:29 +0000211 StringIO.StringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000212 # The test might not have undergone the 'setUp(self)' phase yet, so that
213 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000214 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000215 self.trace = trace
216
217 def __enter__(self):
218 """
219 Context management protocol on entry to the body of the with statement.
220 Just return the StringIO object.
221 """
222 return self
223
224 def __exit__(self, type, value, tb):
225 """
226 Context management protocol on exit from the body of the with statement.
227 If trace is ON, it emits the recordings into stderr. Always add the
228 recordings to our session object. And close the StringIO object, too.
229 """
230 if self.trace:
Johnny Chen690fcef2010-10-15 23:55:05 +0000231 print >> sys.stderr, self.getvalue()
232 if self.session:
233 print >> self.session, self.getvalue()
Johnny Chen150c3cc2010-10-15 01:18:29 +0000234 self.close()
235
Johnny Chen690fcef2010-10-15 23:55:05 +0000236# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000237# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000238def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000239 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000240
241 If the exit code was non-zero it raises a CalledProcessError. The
242 CalledProcessError object will have the return code in the returncode
243 attribute and output in the output attribute.
244
245 The arguments are the same as for the Popen constructor. Example:
246
247 >>> check_output(["ls", "-l", "/dev/null"])
248 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
249
250 The stdout argument is not allowed as it is used internally.
251 To capture standard error in the result, use stderr=STDOUT.
252
253 >>> check_output(["/bin/sh", "-c",
254 ... "ls -l non_existent_file ; exit 0"],
255 ... stderr=STDOUT)
256 'ls: non_existent_file: No such file or directory\n'
257 """
258
259 # Assign the sender object to variable 'test' and remove it from kwargs.
260 test = kwargs.pop('sender', None)
261
Zachary Turner9ef307b2014-07-22 16:19:29 +0000262 separator = None
263 separator = " && " if os.name == "nt" else "; "
264 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
265 commandList = [' '.join(x) for x in commands]
266 # ['make clean foo', 'make foo'] -> 'make clean foo; make foo'
267 shellCommand = separator.join(commandList)
268
Johnny Chen690fcef2010-10-15 23:55:05 +0000269 if 'stdout' in kwargs:
270 raise ValueError('stdout argument not allowed, it will be overridden.')
Zachary Turner9ef307b2014-07-22 16:19:29 +0000271 if 'shell' in kwargs and kwargs['shell']==False:
272 raise ValueError('shell=False not allowed')
273 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
Johnny Chen0bd8c312011-11-16 22:41:53 +0000274 pid = process.pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000275 output, error = process.communicate()
276 retcode = process.poll()
277
Ed Maste6e496332014-08-05 20:33:17 +0000278 # Enable trace on failure return while tracking down FreeBSD buildbot issues
279 trace = traceAlways
280 if not trace and retcode and sys.platform.startswith("freebsd"):
281 trace = True
282
283 with recording(test, trace) as sbuf:
Johnny Chen690fcef2010-10-15 23:55:05 +0000284 print >> sbuf
Zachary Turner9ef307b2014-07-22 16:19:29 +0000285 print >> sbuf, "os command:", shellCommand
Johnny Chen0bd8c312011-11-16 22:41:53 +0000286 print >> sbuf, "with pid:", pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000287 print >> sbuf, "stdout:", output
288 print >> sbuf, "stderr:", error
289 print >> sbuf, "retcode:", retcode
290 print >> sbuf
291
292 if retcode:
293 cmd = kwargs.get("args")
294 if cmd is None:
Zachary Turner9ef307b2014-07-22 16:19:29 +0000295 cmd = shellCommand
Johnny Chen690fcef2010-10-15 23:55:05 +0000296 raise CalledProcessError(retcode, cmd)
Johnny Chenac77f3b2011-03-23 20:28:59 +0000297 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000298
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000299def getsource_if_available(obj):
300 """
301 Return the text of the source code for an object if available. Otherwise,
302 a print representation is returned.
303 """
304 import inspect
305 try:
306 return inspect.getsource(obj)
307 except:
308 return repr(obj)
309
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000310def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000311 if sys.platform.startswith("freebsd"):
312 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000313 return __import__("builder_" + sys.platform)
314
Johnny Chena74bb0a2011-08-01 18:46:13 +0000315#
316# Decorators for categorizing test cases.
317#
318
319from functools import wraps
320def python_api_test(func):
321 """Decorate the item as a Python API only test."""
322 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
323 raise Exception("@python_api_test can only be used to decorate a test method")
324 @wraps(func)
325 def wrapper(self, *args, **kwargs):
326 try:
327 if lldb.dont_do_python_api_test:
328 self.skipTest("python api tests")
329 except AttributeError:
330 pass
331 return func(self, *args, **kwargs)
332
333 # Mark this function as such to separate them from lldb command line tests.
334 wrapper.__python_api_test__ = True
335 return wrapper
336
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000337def lldbmi_test(func):
338 """Decorate the item as a lldb-mi only test."""
339 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
340 raise Exception("@lldbmi_test can only be used to decorate a test method")
341 @wraps(func)
342 def wrapper(self, *args, **kwargs):
343 try:
344 if lldb.dont_do_lldbmi_test:
345 self.skipTest("lldb-mi tests")
346 except AttributeError:
347 pass
348 return func(self, *args, **kwargs)
349
350 # Mark this function as such to separate them from lldb command line tests.
351 wrapper.__lldbmi_test__ = True
352 return wrapper
353
Johnny Chena74bb0a2011-08-01 18:46:13 +0000354def benchmarks_test(func):
355 """Decorate the item as a benchmarks test."""
356 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
357 raise Exception("@benchmarks_test can only be used to decorate a test method")
358 @wraps(func)
359 def wrapper(self, *args, **kwargs):
360 try:
361 if not lldb.just_do_benchmarks_test:
362 self.skipTest("benchmarks tests")
363 except AttributeError:
364 pass
365 return func(self, *args, **kwargs)
366
367 # Mark this function as such to separate them from the regular tests.
368 wrapper.__benchmarks_test__ = True
369 return wrapper
370
Johnny Chenf1548d42012-04-06 00:56:05 +0000371def dsym_test(func):
372 """Decorate the item as a dsym test."""
373 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
374 raise Exception("@dsym_test can only be used to decorate a test method")
375 @wraps(func)
376 def wrapper(self, *args, **kwargs):
377 try:
378 if lldb.dont_do_dsym_test:
379 self.skipTest("dsym tests")
380 except AttributeError:
381 pass
382 return func(self, *args, **kwargs)
383
384 # Mark this function as such to separate them from the regular tests.
385 wrapper.__dsym_test__ = True
386 return wrapper
387
388def dwarf_test(func):
389 """Decorate the item as a dwarf test."""
390 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
391 raise Exception("@dwarf_test can only be used to decorate a test method")
392 @wraps(func)
393 def wrapper(self, *args, **kwargs):
394 try:
395 if lldb.dont_do_dwarf_test:
396 self.skipTest("dwarf tests")
397 except AttributeError:
398 pass
399 return func(self, *args, **kwargs)
400
401 # Mark this function as such to separate them from the regular tests.
402 wrapper.__dwarf_test__ = True
403 return wrapper
404
Todd Fialaa41d48c2014-04-28 04:49:40 +0000405def debugserver_test(func):
406 """Decorate the item as a debugserver test."""
407 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
408 raise Exception("@debugserver_test can only be used to decorate a test method")
409 @wraps(func)
410 def wrapper(self, *args, **kwargs):
411 try:
412 if lldb.dont_do_debugserver_test:
413 self.skipTest("debugserver tests")
414 except AttributeError:
415 pass
416 return func(self, *args, **kwargs)
417
418 # Mark this function as such to separate them from the regular tests.
419 wrapper.__debugserver_test__ = True
420 return wrapper
421
422def llgs_test(func):
423 """Decorate the item as a lldb-gdbserver test."""
424 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
425 raise Exception("@llgs_test can only be used to decorate a test method")
426 @wraps(func)
427 def wrapper(self, *args, **kwargs):
428 try:
429 if lldb.dont_do_llgs_test:
430 self.skipTest("llgs tests")
431 except AttributeError:
432 pass
433 return func(self, *args, **kwargs)
434
435 # Mark this function as such to separate them from the regular tests.
436 wrapper.__llgs_test__ = True
437 return wrapper
438
Daniel Maleae0f8f572013-08-26 23:57:52 +0000439def not_remote_testsuite_ready(func):
440 """Decorate the item as a test which is not ready yet for remote testsuite."""
441 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
442 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
443 @wraps(func)
444 def wrapper(self, *args, **kwargs):
445 try:
446 if lldb.lldbtest_remote_sandbox:
447 self.skipTest("not ready for remote testsuite")
448 except AttributeError:
449 pass
450 return func(self, *args, **kwargs)
451
452 # Mark this function as such to separate them from the regular tests.
453 wrapper.__not_ready_for_remote_testsuite_test__ = True
454 return wrapper
455
Ed Maste433790a2014-04-23 12:55:41 +0000456def expectedFailure(expected_fn, bugnumber=None):
457 def expectedFailure_impl(func):
458 @wraps(func)
459 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000460 from unittest2 import case
461 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000462 try:
Ed Maste433790a2014-04-23 12:55:41 +0000463 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000464 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000465 if expected_fn(self):
466 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000467 else:
468 raise
Ed Maste433790a2014-04-23 12:55:41 +0000469 if expected_fn(self):
470 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
471 return wrapper
Enrico Granatacf3ab582014-10-17 01:11:29 +0000472 if bugnumber:
473 if callable(bugnumber):
474 return expectedFailure_impl(bugnumber)
475 else:
476 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000477
478def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
479 if compiler_version is None:
480 compiler_version=['=', None]
481 def fn(self):
482 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
Enrico Granatacf3ab582014-10-17 01:11:29 +0000483 if bugnumber: return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000484
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000485def expectedFailureClang(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000486 if bugnumber: return expectedFailureCompiler('clang', None, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000487
488def expectedFailureGcc(bugnumber=None, compiler_version=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000489 if bugnumber: return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000490
Matt Kopec0de53f02013-03-15 19:10:12 +0000491def expectedFailureIcc(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000492 if bugnumber: return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000493
Ed Maste433790a2014-04-23 12:55:41 +0000494def expectedFailureArch(arch, bugnumber=None):
495 def fn(self):
496 return arch in self.getArchitecture()
Enrico Granatacf3ab582014-10-17 01:11:29 +0000497 if bugnumber: return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000498
Enrico Granatae6cedc12013-02-23 01:05:23 +0000499def expectedFailurei386(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000500 if bugnumber: return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000501
Matt Kopecee969f92013-09-26 23:30:59 +0000502def expectedFailurex86_64(bugnumber=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000503 if bugnumber: return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000504
505def expectedFailureOS(os, bugnumber=None, compilers=None):
506 def fn(self):
507 return os in sys.platform and self.expectedCompiler(compilers)
Enrico Granatacf3ab582014-10-17 01:11:29 +0000508 if bugnumber: return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000509
510def expectedFailureDarwin(bugnumber=None, compilers=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000511 if bugnumber: return expectedFailureOS('darwin', bugnumber, compilers)
Matt Kopecee969f92013-09-26 23:30:59 +0000512
Ed Maste24a7f7d2013-07-24 19:47:08 +0000513def expectedFailureFreeBSD(bugnumber=None, compilers=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000514 if bugnumber: return expectedFailureOS('freebsd', bugnumber, compilers)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000515
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000516def expectedFailureLinux(bugnumber=None, compilers=None):
Enrico Granatacf3ab582014-10-17 01:11:29 +0000517 if bugnumber: return expectedFailureOS('linux', bugnumber, compilers)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000518
Zachary Turner80c2c602014-12-09 19:28:00 +0000519def expectedFailureWindows(bugnumber=None, compilers=None):
520 if bugnumber: return expectedFailureOS('win32', bugnumber, compilers)
521
Greg Clayton12514562013-12-05 22:22:32 +0000522def skipIfRemote(func):
523 """Decorate the item to skip tests if testing remotely."""
524 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
525 raise Exception("@skipIfRemote can only be used to decorate a test method")
526 @wraps(func)
527 def wrapper(*args, **kwargs):
528 from unittest2 import case
529 if lldb.remote_platform:
530 self = args[0]
531 self.skipTest("skip on remote platform")
532 else:
533 func(*args, **kwargs)
534 return wrapper
535
536def skipIfRemoteDueToDeadlock(func):
537 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
538 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
539 raise Exception("@skipIfRemote can only be used to decorate a test method")
540 @wraps(func)
541 def wrapper(*args, **kwargs):
542 from unittest2 import case
543 if lldb.remote_platform:
544 self = args[0]
545 self.skipTest("skip on remote platform (deadlocks)")
546 else:
547 func(*args, **kwargs)
548 return wrapper
549
Ed Maste09617a52013-06-25 19:11:36 +0000550def skipIfFreeBSD(func):
551 """Decorate the item to skip tests that should be skipped on FreeBSD."""
552 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
553 raise Exception("@skipIfFreeBSD can only be used to decorate a test method")
554 @wraps(func)
555 def wrapper(*args, **kwargs):
556 from unittest2 import case
557 self = args[0]
558 platform = sys.platform
559 if "freebsd" in platform:
560 self.skipTest("skip on FreeBSD")
561 else:
562 func(*args, **kwargs)
563 return wrapper
564
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000565def skipIfLinux(func):
Daniel Malea93aec0f2012-11-23 21:59:29 +0000566 """Decorate the item to skip tests that should be skipped on Linux."""
567 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000568 raise Exception("@skipIfLinux can only be used to decorate a test method")
Daniel Malea93aec0f2012-11-23 21:59:29 +0000569 @wraps(func)
570 def wrapper(*args, **kwargs):
571 from unittest2 import case
572 self = args[0]
573 platform = sys.platform
574 if "linux" in platform:
575 self.skipTest("skip on linux")
576 else:
Jim Ingham9732e082012-11-27 01:21:28 +0000577 func(*args, **kwargs)
Daniel Malea93aec0f2012-11-23 21:59:29 +0000578 return wrapper
579
Enrico Granatab633e432014-10-06 21:37:06 +0000580def skipIfNoSBHeaders(func):
581 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
582 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000583 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000584 @wraps(func)
585 def wrapper(*args, **kwargs):
586 from unittest2 import case
587 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000588 if sys.platform.startswith("darwin"):
589 header = os.path.join(self.lib_dir, 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
590 else:
591 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000592 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000593 if not os.path.exists(header):
594 self.skipTest("skip because LLDB.h header not found")
595 else:
596 func(*args, **kwargs)
597 return wrapper
598
Zachary Turnerc7826522014-08-13 17:44:53 +0000599def skipIfWindows(func):
600 """Decorate the item to skip tests that should be skipped on Windows."""
601 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
602 raise Exception("@skipIfWindows can only be used to decorate a test method")
603 @wraps(func)
604 def wrapper(*args, **kwargs):
605 from unittest2 import case
606 self = args[0]
607 platform = sys.platform
608 if "win32" in platform:
609 self.skipTest("skip on Windows")
610 else:
611 func(*args, **kwargs)
612 return wrapper
613
Daniel Maleab3d41a22013-07-09 00:08:01 +0000614def skipIfDarwin(func):
615 """Decorate the item to skip tests that should be skipped on Darwin."""
616 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Mastea7f13f02013-07-09 00:24:52 +0000617 raise Exception("@skipIfDarwin can only be used to decorate a test method")
Daniel Maleab3d41a22013-07-09 00:08:01 +0000618 @wraps(func)
619 def wrapper(*args, **kwargs):
620 from unittest2 import case
621 self = args[0]
622 platform = sys.platform
623 if "darwin" in platform:
624 self.skipTest("skip on darwin")
625 else:
626 func(*args, **kwargs)
627 return wrapper
628
629
Daniel Malea48359902013-05-14 20:48:54 +0000630def skipIfLinuxClang(func):
631 """Decorate the item to skip tests that should be skipped if building on
632 Linux with clang.
633 """
634 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
635 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
636 @wraps(func)
637 def wrapper(*args, **kwargs):
638 from unittest2 import case
639 self = args[0]
640 compiler = self.getCompiler()
641 platform = sys.platform
642 if "clang" in compiler and "linux" in platform:
643 self.skipTest("skipping because Clang is used on Linux")
644 else:
645 func(*args, **kwargs)
646 return wrapper
647
Daniel Maleabe230792013-01-24 23:52:09 +0000648def skipIfGcc(func):
649 """Decorate the item to skip tests that should be skipped if building with gcc ."""
650 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +0000651 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +0000652 @wraps(func)
653 def wrapper(*args, **kwargs):
654 from unittest2 import case
655 self = args[0]
656 compiler = self.getCompiler()
657 if "gcc" in compiler:
658 self.skipTest("skipping because gcc is the test compiler")
659 else:
660 func(*args, **kwargs)
661 return wrapper
662
Matt Kopec0de53f02013-03-15 19:10:12 +0000663def skipIfIcc(func):
664 """Decorate the item to skip tests that should be skipped if building with icc ."""
665 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
666 raise Exception("@skipIfIcc can only be used to decorate a test method")
667 @wraps(func)
668 def wrapper(*args, **kwargs):
669 from unittest2 import case
670 self = args[0]
671 compiler = self.getCompiler()
672 if "icc" in compiler:
673 self.skipTest("skipping because icc is the test compiler")
674 else:
675 func(*args, **kwargs)
676 return wrapper
677
Daniel Malea55faa402013-05-02 21:44:31 +0000678def skipIfi386(func):
679 """Decorate the item to skip tests that should be skipped if building 32-bit."""
680 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
681 raise Exception("@skipIfi386 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 if "i386" == self.getArchitecture():
687 self.skipTest("skipping because i386 is not a supported architecture")
688 else:
689 func(*args, **kwargs)
690 return wrapper
691
692
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000693class _PlatformContext(object):
694 """Value object class which contains platform-specific options."""
695
696 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
697 self.shlib_environment_var = shlib_environment_var
698 self.shlib_prefix = shlib_prefix
699 self.shlib_extension = shlib_extension
700
701
Johnny Chena74bb0a2011-08-01 18:46:13 +0000702class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000703 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000704 Abstract base for performing lldb (see TestBase) or other generic tests (see
705 BenchBase for one example). lldbtest.Base works with the test driver to
706 accomplish things.
707
Johnny Chen8334dad2010-10-22 23:15:46 +0000708 """
Enrico Granata5020f952012-10-24 21:42:49 +0000709
Enrico Granata19186272012-10-24 21:44:48 +0000710 # The concrete subclass should override this attribute.
711 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000712
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000713 # Keep track of the old current working directory.
714 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000715
Greg Clayton4570d3e2013-12-10 23:19:29 +0000716 @staticmethod
717 def compute_mydir(test_file):
718 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
719
720 mydir = TestBase.compute_mydir(__file__)'''
721 test_dir = os.path.dirname(test_file)
722 return test_dir[len(os.environ["LLDB_TEST"])+1:]
723
Johnny Chenfb4264c2011-08-01 19:50:58 +0000724 def TraceOn(self):
725 """Returns True if we are in trace mode (tracing detailed test execution)."""
726 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +0000727
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000728 @classmethod
729 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000730 """
731 Python unittest framework class setup fixture.
732 Do current directory manipulation.
733 """
734
Johnny Chenf02ec122010-07-03 20:41:42 +0000735 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000736 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000737 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +0000738
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000739 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000740 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000741
742 # Change current working directory if ${LLDB_TEST} is defined.
743 # See also dotest.py which sets up ${LLDB_TEST}.
744 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000745 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000746 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000747 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
748
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000749 # Set platform context.
750 if sys.platform.startswith('darwin'):
751 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
752 elif sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):
753 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +0000754 else:
755 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000756
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000757 @classmethod
758 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000759 """
760 Python unittest framework class teardown fixture.
761 Do class-wide cleanup.
762 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000763
Johnny Chen0fddfb22011-11-17 19:57:27 +0000764 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000765 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000766 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000767 if not module.cleanup():
768 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000769
Johnny Chen707b3c92010-10-11 22:25:46 +0000770 # Subclass might have specific cleanup function defined.
771 if getattr(cls, "classCleanup", None):
772 if traceAlways:
773 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
774 try:
775 cls.classCleanup()
776 except:
777 exc_type, exc_value, exc_tb = sys.exc_info()
778 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000779
780 # Restore old working directory.
781 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000782 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000783 os.chdir(cls.oldcwd)
784
Johnny Chena74bb0a2011-08-01 18:46:13 +0000785 @classmethod
786 def skipLongRunningTest(cls):
787 """
788 By default, we skip long running test case.
789 This can be overridden by passing '-l' to the test driver (dotest.py).
790 """
791 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
792 return False
793 else:
794 return True
Johnny Chened492022011-06-21 00:53:00 +0000795
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000796 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000797 """Fixture for unittest test case setup.
798
799 It works with the test driver to conditionally skip tests and does other
800 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000801 #import traceback
802 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000803
Daniel Malea9115f072013-08-06 15:02:32 +0000804 if "LIBCXX_PATH" in os.environ:
805 self.libcxxPath = os.environ["LIBCXX_PATH"]
806 else:
807 self.libcxxPath = None
808
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000809 if "LLDB_EXEC" in os.environ:
810 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000811 else:
812 self.lldbExec = None
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000813 if "LLDBMI_EXEC" in os.environ:
814 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
815 else:
816 self.lldbMiExec = None
817 self.dont_do_lldbmi_test = True
Johnny Chend890bfc2011-08-26 00:00:01 +0000818 if "LLDB_HERE" in os.environ:
819 self.lldbHere = os.environ["LLDB_HERE"]
820 else:
821 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000822 # If we spawn an lldb process for test (via pexpect), do not load the
823 # init file unless told otherwise.
824 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
825 self.lldbOption = ""
826 else:
827 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000828
Johnny Chen985e7402011-08-01 21:13:26 +0000829 # Assign the test method name to self.testMethodName.
830 #
831 # For an example of the use of this attribute, look at test/types dir.
832 # There are a bunch of test cases under test/types and we don't want the
833 # module cacheing subsystem to be confused with executable name "a.out"
834 # used for all the test cases.
835 self.testMethodName = self._testMethodName
836
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000837 # Python API only test is decorated with @python_api_test,
838 # which also sets the "__python_api_test__" attribute of the
839 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000840 try:
841 if lldb.just_do_python_api_test:
842 testMethod = getattr(self, self._testMethodName)
843 if getattr(testMethod, "__python_api_test__", False):
844 pass
845 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000846 self.skipTest("non python api test")
847 except AttributeError:
848 pass
849
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000850 # lldb-mi only test is decorated with @lldbmi_test,
851 # which also sets the "__lldbmi_test__" attribute of the
852 # function object to True.
853 try:
854 if lldb.just_do_lldbmi_test:
855 testMethod = getattr(self, self._testMethodName)
856 if getattr(testMethod, "__lldbmi_test__", False):
857 pass
858 else:
859 self.skipTest("non lldb-mi test")
860 except AttributeError:
861 pass
862
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000863 # Benchmarks test is decorated with @benchmarks_test,
864 # which also sets the "__benchmarks_test__" attribute of the
865 # function object to True.
866 try:
867 if lldb.just_do_benchmarks_test:
868 testMethod = getattr(self, self._testMethodName)
869 if getattr(testMethod, "__benchmarks_test__", False):
870 pass
871 else:
872 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000873 except AttributeError:
874 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000875
Johnny Chen985e7402011-08-01 21:13:26 +0000876 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
877 # with it using pexpect.
878 self.child = None
879 self.child_prompt = "(lldb) "
880 # If the child is interacting with the embedded script interpreter,
881 # there are two exits required during tear down, first to quit the
882 # embedded script interpreter and second to quit the lldb command
883 # interpreter.
884 self.child_in_script_interpreter = False
885
Johnny Chenfb4264c2011-08-01 19:50:58 +0000886 # These are for customized teardown cleanup.
887 self.dict = None
888 self.doTearDownCleanup = False
889 # And in rare cases where there are multiple teardown cleanups.
890 self.dicts = []
891 self.doTearDownCleanups = False
892
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000893 # List of spawned subproces.Popen objects
894 self.subprocesses = []
895
Daniel Malea69207462013-06-05 21:07:02 +0000896 # List of forked process PIDs
897 self.forkedProcessPids = []
898
Johnny Chenfb4264c2011-08-01 19:50:58 +0000899 # Create a string buffer to record the session info, to be dumped into a
900 # test case specific file if test failure is encountered.
901 self.session = StringIO.StringIO()
902
903 # Optimistically set __errored__, __failed__, __expected__ to False
904 # initially. If the test errored/failed, the session info
905 # (self.session) is then dumped into a session specific file for
906 # diagnosis.
907 self.__errored__ = False
908 self.__failed__ = False
909 self.__expected__ = False
910 # We are also interested in unexpected success.
911 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +0000912 # And skipped tests.
913 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +0000914
915 # See addTearDownHook(self, hook) which allows the client to add a hook
916 # function to be run during tearDown() time.
917 self.hooks = []
918
919 # See HideStdout(self).
920 self.sys_stdout_hidden = False
921
Zachary Turnerbe40b2f2014-12-02 21:32:44 +0000922 if self.platformContext:
923 # set environment variable names for finding shared libraries
924 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +0000925
Johnny Chen2a808582011-10-19 16:48:07 +0000926 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +0000927 """Perform the run hooks to bring lldb debugger to the desired state.
928
Johnny Chen2a808582011-10-19 16:48:07 +0000929 By default, expect a pexpect spawned child and child prompt to be
930 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
931 and child prompt and use self.runCmd() to run the hooks one by one.
932
Johnny Chena737ba52011-10-19 01:06:21 +0000933 Note that child is a process spawned by pexpect.spawn(). If not, your
934 test case is mostly likely going to fail.
935
936 See also dotest.py where lldb.runHooks are processed/populated.
937 """
938 if not lldb.runHooks:
939 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +0000940 if use_cmd_api:
941 for hook in lldb.runhooks:
942 self.runCmd(hook)
943 else:
944 if not child or not child_prompt:
945 self.fail("Both child and child_prompt need to be defined.")
946 for hook in lldb.runHooks:
947 child.sendline(hook)
948 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +0000949
Daniel Malea249287a2013-02-19 16:08:57 +0000950 def setAsync(self, value):
951 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
952 old_async = self.dbg.GetAsync()
953 self.dbg.SetAsync(value)
954 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
955
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000956 def cleanupSubprocesses(self):
957 # Ensure any subprocesses are cleaned up
958 for p in self.subprocesses:
959 if p.poll() == None:
960 p.terminate()
961 del p
962 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +0000963 # Ensure any forked processes are cleaned up
964 for pid in self.forkedProcessPids:
965 if os.path.exists("/proc/" + str(pid)):
966 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000967
968 def spawnSubprocess(self, executable, args=[]):
969 """ Creates a subprocess.Popen object with the specified executable and arguments,
970 saves it in self.subprocesses, and returns the object.
971 NOTE: if using this function, ensure you also call:
972
973 self.addTearDownHook(self.cleanupSubprocesses)
974
975 otherwise the test suite will leak processes.
976 """
977
978 # Don't display the stdout if not in TraceOn() mode.
979 proc = Popen([executable] + args,
980 stdout = open(os.devnull) if not self.TraceOn() else None,
981 stdin = PIPE)
982 self.subprocesses.append(proc)
983 return proc
984
Daniel Malea69207462013-06-05 21:07:02 +0000985 def forkSubprocess(self, executable, args=[]):
986 """ Fork a subprocess with its own group ID.
987 NOTE: if using this function, ensure you also call:
988
989 self.addTearDownHook(self.cleanupSubprocesses)
990
991 otherwise the test suite will leak processes.
992 """
993 child_pid = os.fork()
994 if child_pid == 0:
995 # If more I/O support is required, this can be beefed up.
996 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +0000997 os.dup2(fd, 1)
998 os.dup2(fd, 2)
999 # This call causes the child to have its of group ID
1000 os.setpgid(0,0)
1001 os.execvp(executable, [executable] + args)
1002 # Give the child time to get through the execvp() call
1003 time.sleep(0.1)
1004 self.forkedProcessPids.append(child_pid)
1005 return child_pid
1006
Johnny Chenfb4264c2011-08-01 19:50:58 +00001007 def HideStdout(self):
1008 """Hide output to stdout from the user.
1009
1010 During test execution, there might be cases where we don't want to show the
1011 standard output to the user. For example,
1012
1013 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
1014
1015 tests whether command abbreviation for 'script' works or not. There is no
1016 need to show the 'Hello' output to the user as long as the 'script' command
1017 succeeds and we are not in TraceOn() mode (see the '-t' option).
1018
1019 In this case, the test method calls self.HideStdout(self) to redirect the
1020 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1021
1022 Note that you should only call this method at most once during a test case
1023 execution. Any subsequent call has no effect at all."""
1024 if self.sys_stdout_hidden:
1025 return
1026
1027 self.sys_stdout_hidden = True
1028 old_stdout = sys.stdout
1029 sys.stdout = open(os.devnull, 'w')
1030 def restore_stdout():
1031 sys.stdout = old_stdout
1032 self.addTearDownHook(restore_stdout)
1033
1034 # =======================================================================
1035 # Methods for customized teardown cleanups as well as execution of hooks.
1036 # =======================================================================
1037
1038 def setTearDownCleanup(self, dictionary=None):
1039 """Register a cleanup action at tearDown() time with a dictinary"""
1040 self.dict = dictionary
1041 self.doTearDownCleanup = True
1042
1043 def addTearDownCleanup(self, dictionary):
1044 """Add a cleanup action at tearDown() time with a dictinary"""
1045 self.dicts.append(dictionary)
1046 self.doTearDownCleanups = True
1047
1048 def addTearDownHook(self, hook):
1049 """
1050 Add a function to be run during tearDown() time.
1051
1052 Hooks are executed in a first come first serve manner.
1053 """
1054 if callable(hook):
1055 with recording(self, traceAlways) as sbuf:
1056 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
1057 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001058
1059 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001060
Jim Inghamda3a3862014-10-16 23:02:14 +00001061 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001062 # This is for the case of directly spawning 'lldb' and interacting with it
1063 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001064 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001065 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001066 with recording(self, traceAlways) as sbuf:
1067 print >> sbuf, "tearing down the child process...."
Johnny Chen985e7402011-08-01 21:13:26 +00001068 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001069 if self.child_in_script_interpreter:
1070 self.child.sendline('quit()')
1071 self.child.expect_exact(self.child_prompt)
1072 self.child.sendline('settings set interpreter.prompt-on-quit false')
1073 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001074 self.child.expect(pexpect.EOF)
Hafiz Abid Qadeera73d1ce2015-01-26 12:03:05 +00001075 except (ValueError, OSError, pexpect.ExceptionPexpect):
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001076 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001077 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001078 finally:
1079 # Give it one final blow to make sure the child is terminated.
1080 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001081
1082 def tearDown(self):
1083 """Fixture for unittest test case teardown."""
1084 #import traceback
1085 #traceback.print_stack()
1086
1087 self.deletePexpectChild()
1088
Johnny Chenfb4264c2011-08-01 19:50:58 +00001089 # Check and run any hook functions.
1090 for hook in reversed(self.hooks):
1091 with recording(self, traceAlways) as sbuf:
1092 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001093 import inspect
1094 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001095 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001096 hook()
1097 elif hook_argc == 1:
1098 hook(self)
1099 else:
1100 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001101
1102 del self.hooks
1103
1104 # Perform registered teardown cleanup.
1105 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001106 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001107
1108 # In rare cases where there are multiple teardown cleanups added.
1109 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001110 if self.dicts:
1111 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001112 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001113
1114 # Decide whether to dump the session info.
1115 self.dumpSessionInfo()
1116
1117 # =========================================================
1118 # Various callbacks to allow introspection of test progress
1119 # =========================================================
1120
1121 def markError(self):
1122 """Callback invoked when an error (unexpected exception) errored."""
1123 self.__errored__ = True
1124 with recording(self, False) as sbuf:
1125 # False because there's no need to write "ERROR" to the stderr twice.
1126 # Once by the Python unittest framework, and a second time by us.
1127 print >> sbuf, "ERROR"
1128
1129 def markFailure(self):
1130 """Callback invoked when a failure (test assertion failure) occurred."""
1131 self.__failed__ = True
1132 with recording(self, False) as sbuf:
1133 # False because there's no need to write "FAIL" to the stderr twice.
1134 # Once by the Python unittest framework, and a second time by us.
1135 print >> sbuf, "FAIL"
1136
Enrico Granatae6cedc12013-02-23 01:05:23 +00001137 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001138 """Callback invoked when an expected failure/error occurred."""
1139 self.__expected__ = True
1140 with recording(self, False) as sbuf:
1141 # False because there's no need to write "expected failure" to the
1142 # stderr twice.
1143 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001144 if bugnumber == None:
1145 print >> sbuf, "expected failure"
1146 else:
1147 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001148
Johnny Chenc5cc6252011-08-15 23:09:08 +00001149 def markSkippedTest(self):
1150 """Callback invoked when a test is skipped."""
1151 self.__skipped__ = True
1152 with recording(self, False) as sbuf:
1153 # False because there's no need to write "skipped test" to the
1154 # stderr twice.
1155 # Once by the Python unittest framework, and a second time by us.
1156 print >> sbuf, "skipped test"
1157
Enrico Granatae6cedc12013-02-23 01:05:23 +00001158 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001159 """Callback invoked when an unexpected success occurred."""
1160 self.__unexpected__ = True
1161 with recording(self, False) as sbuf:
1162 # False because there's no need to write "unexpected success" to the
1163 # stderr twice.
1164 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001165 if bugnumber == None:
1166 print >> sbuf, "unexpected success"
1167 else:
1168 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001169
Greg Clayton70995582015-01-07 22:25:50 +00001170 def getRerunArgs(self):
1171 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
1172
Johnny Chenfb4264c2011-08-01 19:50:58 +00001173 def dumpSessionInfo(self):
1174 """
1175 Dump the debugger interactions leading to a test error/failure. This
1176 allows for more convenient postmortem analysis.
1177
1178 See also LLDBTestResult (dotest.py) which is a singlton class derived
1179 from TextTestResult and overwrites addError, addFailure, and
1180 addExpectedFailure methods to allow us to to mark the test instance as
1181 such.
1182 """
1183
1184 # We are here because self.tearDown() detected that this test instance
1185 # either errored or failed. The lldb.test_result singleton contains
1186 # two lists (erros and failures) which get populated by the unittest
1187 # framework. Look over there for stack trace information.
1188 #
1189 # The lists contain 2-tuples of TestCase instances and strings holding
1190 # formatted tracebacks.
1191 #
1192 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1193 if self.__errored__:
1194 pairs = lldb.test_result.errors
1195 prefix = 'Error'
1196 elif self.__failed__:
1197 pairs = lldb.test_result.failures
1198 prefix = 'Failure'
1199 elif self.__expected__:
1200 pairs = lldb.test_result.expectedFailures
1201 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001202 elif self.__skipped__:
1203 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001204 elif self.__unexpected__:
1205 prefix = "UnexpectedSuccess"
1206 else:
1207 # Simply return, there's no session info to dump!
1208 return
1209
Johnny Chenc5cc6252011-08-15 23:09:08 +00001210 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001211 for test, traceback in pairs:
1212 if test is self:
1213 print >> self.session, traceback
1214
Johnny Chen8082a002011-08-11 00:16:28 +00001215 testMethod = getattr(self, self._testMethodName)
1216 if getattr(testMethod, "__benchmarks_test__", False):
1217 benchmarks = True
1218 else:
1219 benchmarks = False
1220
Johnny Chenfb4264c2011-08-01 19:50:58 +00001221 dname = os.path.join(os.environ["LLDB_TEST"],
1222 os.environ["LLDB_SESSION_DIRNAME"])
1223 if not os.path.isdir(dname):
1224 os.mkdir(dname)
Zachary Turner756acba2014-10-14 21:54:14 +00001225 compiler = self.getCompiler()
1226 if compiler[1] == ':':
1227 compiler = compiler[2:]
1228
1229 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 +00001230 with open(fname, "w") as f:
1231 import datetime
1232 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1233 print >> f, self.session.getvalue()
1234 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Greg Clayton70995582015-01-07 22:25:50 +00001235 print >> f, "./dotest.py %s -v %s %s" % (self.getRunOptions(),
1236 ('+b' if benchmarks else '-t'),
1237 self.getRerunArgs())
Johnny Chenfb4264c2011-08-01 19:50:58 +00001238
1239 # ====================================================
1240 # Config. methods supported through a plugin interface
1241 # (enables reading of the current test configuration)
1242 # ====================================================
1243
1244 def getArchitecture(self):
1245 """Returns the architecture in effect the test suite is running with."""
1246 module = builder_module()
1247 return module.getArchitecture()
1248
1249 def getCompiler(self):
1250 """Returns the compiler in effect the test suite is running with."""
1251 module = builder_module()
1252 return module.getCompiler()
1253
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001254 def getCompilerBinary(self):
1255 """Returns the compiler binary the test suite is running with."""
1256 return self.getCompiler().split()[0]
1257
Daniel Malea0aea0162013-02-27 17:29:46 +00001258 def getCompilerVersion(self):
1259 """ Returns a string that represents the compiler version.
1260 Supports: llvm, clang.
1261 """
1262 from lldbutil import which
1263 version = 'unknown'
1264
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001265 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001266 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001267 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001268 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001269 if m:
1270 version = m.group(1)
1271 return version
1272
Daniel Maleaadaaec92013-08-06 20:51:41 +00001273 def isIntelCompiler(self):
1274 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1275 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1276
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001277 def expectedCompilerVersion(self, compiler_version):
1278 """Returns True iff compiler_version[1] matches the current compiler version.
1279 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1280 Any operator other than the following defaults to an equality test:
1281 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1282 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001283 if (compiler_version == None):
1284 return True
1285 operator = str(compiler_version[0])
1286 version = compiler_version[1]
1287
1288 if (version == None):
1289 return True
1290 if (operator == '>'):
1291 return self.getCompilerVersion() > version
1292 if (operator == '>=' or operator == '=>'):
1293 return self.getCompilerVersion() >= version
1294 if (operator == '<'):
1295 return self.getCompilerVersion() < version
1296 if (operator == '<=' or operator == '=<'):
1297 return self.getCompilerVersion() <= version
1298 if (operator == '!=' or operator == '!' or operator == 'not'):
1299 return str(version) not in str(self.getCompilerVersion())
1300 return str(version) in str(self.getCompilerVersion())
1301
1302 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001303 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001304 if (compilers == None):
1305 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001306
1307 for compiler in compilers:
1308 if compiler in self.getCompiler():
1309 return True
1310
1311 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001312
Johnny Chenfb4264c2011-08-01 19:50:58 +00001313 def getRunOptions(self):
1314 """Command line option for -A and -C to run this test again, called from
1315 self.dumpSessionInfo()."""
1316 arch = self.getArchitecture()
1317 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001318 if arch:
1319 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001320 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001321 option_str = ""
1322 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001323 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001324 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001325
1326 # ==================================================
1327 # Build methods supported through a plugin interface
1328 # ==================================================
1329
Ed Mastec97323e2014-04-01 18:47:58 +00001330 def getstdlibFlag(self):
1331 """ Returns the proper -stdlib flag, or empty if not required."""
1332 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
1333 stdlibflag = "-stdlib=libc++"
1334 else:
1335 stdlibflag = ""
1336 return stdlibflag
1337
Matt Kopec7663b3a2013-09-25 17:44:00 +00001338 def getstdFlag(self):
1339 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00001340 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00001341 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00001342 else:
1343 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00001344 return stdflag
1345
1346 def buildDriver(self, sources, exe_name):
1347 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1348 or LLDB.framework).
1349 """
1350
1351 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00001352 stdlibflag = self.getstdlibFlag()
Daniel Malea55faa402013-05-02 21:44:31 +00001353
1354 if sys.platform.startswith("darwin"):
1355 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1356 d = {'CXX_SOURCES' : sources,
1357 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001358 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Daniel Malea55faa402013-05-02 21:44:31 +00001359 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Stefanus Du Toit04004442013-07-30 19:19:49 +00001360 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, self.lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00001361 }
Ed Maste372c24d2013-07-25 21:02:34 +00001362 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 +00001363 d = {'CXX_SOURCES' : sources,
1364 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001365 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Daniel Malea55faa402013-05-02 21:44:31 +00001366 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
1367 if self.TraceOn():
1368 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1369
1370 self.buildDefault(dictionary=d)
1371
Matt Kopec7663b3a2013-09-25 17:44:00 +00001372 def buildLibrary(self, sources, lib_name):
1373 """Platform specific way to build a default library. """
1374
1375 stdflag = self.getstdFlag()
1376
1377 if sys.platform.startswith("darwin"):
1378 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1379 d = {'DYLIB_CXX_SOURCES' : sources,
1380 'DYLIB_NAME' : lib_name,
1381 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1382 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
1383 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, self.lib_dir),
1384 }
1385 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
1386 d = {'DYLIB_CXX_SOURCES' : sources,
1387 'DYLIB_NAME' : lib_name,
1388 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1389 'LD_EXTRAS' : "-shared -L%s -llldb" % self.lib_dir}
1390 if self.TraceOn():
1391 print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
1392
1393 self.buildDefault(dictionary=d)
1394
Daniel Malea55faa402013-05-02 21:44:31 +00001395 def buildProgram(self, sources, exe_name):
1396 """ Platform specific way to build an executable from C/C++ sources. """
1397 d = {'CXX_SOURCES' : sources,
1398 'EXE' : exe_name}
1399 self.buildDefault(dictionary=d)
1400
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001401 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001402 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001403 if lldb.skip_build_and_cleanup:
1404 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001405 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001406 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001407 raise Exception("Don't know how to build default binary")
1408
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001409 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001410 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001411 if lldb.skip_build_and_cleanup:
1412 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001413 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001414 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001415 raise Exception("Don't know how to build binary with dsym")
1416
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001417 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001418 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001419 if lldb.skip_build_and_cleanup:
1420 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001421 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001422 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001423 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00001424
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00001425 def signBinary(self, binary_path):
1426 if sys.platform.startswith("darwin"):
1427 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
1428 call(codesign_cmd, shell=True)
1429
Kuba Breckabeed8212014-09-04 01:03:18 +00001430 def findBuiltClang(self):
1431 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
1432 paths_to_try = [
1433 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
1434 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
1435 "llvm-build/Release/x86_64/Release/bin/clang",
1436 "llvm-build/Debug/x86_64/Debug/bin/clang",
1437 ]
1438 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
1439 for p in paths_to_try:
1440 path = os.path.join(lldb_root_path, p)
1441 if os.path.exists(path):
1442 return path
1443
1444 return os.environ["CC"]
1445
Daniel Malea9115f072013-08-06 15:02:32 +00001446 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False, use_pthreads=True):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001447 """ Returns a dictionary (which can be provided to build* functions above) which
1448 contains OS-specific build flags.
1449 """
1450 cflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00001451
1452 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
1453 if not use_libstdcxx and sys.platform.startswith('darwin'):
1454 use_libcxx = True
1455
1456 if use_libcxx and self.libcxxPath:
1457 cflags += "-stdlib=libc++ "
1458 if self.libcxxPath:
1459 libcxxInclude = os.path.join(self.libcxxPath, "include")
1460 libcxxLib = os.path.join(self.libcxxPath, "lib")
1461 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
1462 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
1463
Andrew Kaylor93132f52013-05-28 23:04:25 +00001464 if use_cpp11:
1465 cflags += "-std="
1466 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1467 cflags += "c++0x"
1468 else:
1469 cflags += "c++11"
Ed Mastedbd59502014-02-02 19:24:15 +00001470 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001471 cflags += " -stdlib=libc++"
1472 elif "clang" in self.getCompiler():
1473 cflags += " -stdlib=libstdc++"
1474
1475 if use_pthreads:
1476 ldflags = "-lpthread"
1477
1478 return {'CFLAGS_EXTRAS' : cflags,
1479 'LD_EXTRAS' : ldflags,
1480 }
1481
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001482 def cleanup(self, dictionary=None):
1483 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001484 if lldb.skip_build_and_cleanup:
1485 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001486 module = builder_module()
1487 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001488 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001489
Daniel Malea55faa402013-05-02 21:44:31 +00001490 def getLLDBLibraryEnvVal(self):
1491 """ Returns the path that the OS-specific library search environment variable
1492 (self.dylibPath) should be set to in order for a program to find the LLDB
1493 library. If an environment variable named self.dylibPath is already set,
1494 the new path is appended to it and returned.
1495 """
1496 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1497 if existing_library_path:
1498 return "%s:%s" % (existing_library_path, self.lib_dir)
1499 elif sys.platform.startswith("darwin"):
1500 return os.path.join(self.lib_dir, 'LLDB.framework')
1501 else:
1502 return self.lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00001503
Ed Maste437f8f62013-09-09 14:04:04 +00001504 def getLibcPlusPlusLibs(self):
1505 if sys.platform.startswith('freebsd'):
1506 return ['libc++.so.1']
1507 else:
1508 return ['libc++.1.dylib','libc++abi.dylib']
1509
Johnny Chena74bb0a2011-08-01 18:46:13 +00001510class TestBase(Base):
1511 """
1512 This abstract base class is meant to be subclassed. It provides default
1513 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1514 among other things.
1515
1516 Important things for test class writers:
1517
1518 - Overwrite the mydir class attribute, otherwise your test class won't
1519 run. It specifies the relative directory to the top level 'test' so
1520 the test harness can change to the correct working directory before
1521 running your test.
1522
1523 - The setUp method sets up things to facilitate subsequent interactions
1524 with the debugger as part of the test. These include:
1525 - populate the test method name
1526 - create/get a debugger set with synchronous mode (self.dbg)
1527 - get the command interpreter from with the debugger (self.ci)
1528 - create a result object for use with the command interpreter
1529 (self.res)
1530 - plus other stuffs
1531
1532 - The tearDown method tries to perform some necessary cleanup on behalf
1533 of the test to return the debugger to a good state for the next test.
1534 These include:
1535 - execute any tearDown hooks registered by the test method with
1536 TestBase.addTearDownHook(); examples can be found in
1537 settings/TestSettings.py
1538 - kill the inferior process associated with each target, if any,
1539 and, then delete the target from the debugger's target list
1540 - perform build cleanup before running the next test method in the
1541 same test class; examples of registering for this service can be
1542 found in types/TestIntegerTypes.py with the call:
1543 - self.setTearDownCleanup(dictionary=d)
1544
1545 - Similarly setUpClass and tearDownClass perform classwise setup and
1546 teardown fixtures. The tearDownClass method invokes a default build
1547 cleanup for the entire test class; also, subclasses can implement the
1548 classmethod classCleanup(cls) to perform special class cleanup action.
1549
1550 - The instance methods runCmd and expect are used heavily by existing
1551 test cases to send a command to the command interpreter and to perform
1552 string/pattern matching on the output of such command execution. The
1553 expect method also provides a mode to peform string/pattern matching
1554 without running a command.
1555
1556 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1557 build the binaries used during a particular test scenario. A plugin
1558 should be provided for the sys.platform running the test suite. The
1559 Mac OS X implementation is located in plugins/darwin.py.
1560 """
1561
1562 # Maximum allowed attempts when launching the inferior process.
1563 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1564 maxLaunchCount = 3;
1565
1566 # Time to wait before the next launching attempt in second(s).
1567 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1568 timeWaitNextLaunch = 1.0;
1569
1570 def doDelay(self):
1571 """See option -w of dotest.py."""
1572 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1573 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1574 waitTime = 1.0
1575 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1576 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1577 time.sleep(waitTime)
1578
Enrico Granata165f8af2012-09-21 19:10:53 +00001579 # Returns the list of categories to which this test case belongs
1580 # by default, look for a ".categories" file, and read its contents
1581 # if no such file exists, traverse the hierarchy - we guarantee
1582 # a .categories to exist at the top level directory so we do not end up
1583 # looping endlessly - subclasses are free to define their own categories
1584 # in whatever way makes sense to them
1585 def getCategories(self):
1586 import inspect
1587 import os.path
1588 folder = inspect.getfile(self.__class__)
1589 folder = os.path.dirname(folder)
1590 while folder != '/':
1591 categories_file_name = os.path.join(folder,".categories")
1592 if os.path.exists(categories_file_name):
1593 categories_file = open(categories_file_name,'r')
1594 categories = categories_file.readline()
1595 categories_file.close()
1596 categories = str.replace(categories,'\n','')
1597 categories = str.replace(categories,'\r','')
1598 return categories.split(',')
1599 else:
1600 folder = os.path.dirname(folder)
1601 continue
1602
Johnny Chena74bb0a2011-08-01 18:46:13 +00001603 def setUp(self):
1604 #import traceback
1605 #traceback.print_stack()
1606
1607 # Works with the test driver to conditionally skip tests via decorators.
1608 Base.setUp(self)
1609
Johnny Chena74bb0a2011-08-01 18:46:13 +00001610 try:
1611 if lldb.blacklist:
1612 className = self.__class__.__name__
1613 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1614 if className in lldb.blacklist:
1615 self.skipTest(lldb.blacklist.get(className))
1616 elif classAndMethodName in lldb.blacklist:
1617 self.skipTest(lldb.blacklist.get(classAndMethodName))
1618 except AttributeError:
1619 pass
1620
Johnny Chened492022011-06-21 00:53:00 +00001621 # Insert some delay between successive test cases if specified.
1622 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00001623
Johnny Chenf2b70232010-08-25 18:49:48 +00001624 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1625 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1626
Johnny Chen430eb762010-10-19 16:00:42 +00001627 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00001628 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00001629
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001630 # Create the debugger instance if necessary.
1631 try:
1632 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001633 except AttributeError:
1634 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +00001635
Johnny Chen3cd1e552011-05-25 19:06:18 +00001636 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001637 raise Exception('Invalid debugger instance')
1638
Daniel Maleae0f8f572013-08-26 23:57:52 +00001639 #
1640 # Warning: MAJOR HACK AHEAD!
1641 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
1642 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
1643 # command, instead. See also runCmd() where it decorates the "file filename" call
1644 # with additional functionality when running testsuite remotely.
1645 #
1646 if lldb.lldbtest_remote_sandbox:
1647 def DecoratedCreateTarget(arg):
1648 self.runCmd("file %s" % arg)
1649 target = self.dbg.GetSelectedTarget()
1650 #
Greg Claytonc6947512013-12-13 19:18:59 +00001651 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00001652 # johnny @ 04/23/2012
1653 #
1654 def DecoratedLaunchSimple(argv, envp, wd):
1655 self.runCmd("run")
1656 return target.GetProcess()
1657 target.LaunchSimple = DecoratedLaunchSimple
1658
1659 return target
1660 self.dbg.CreateTarget = DecoratedCreateTarget
1661 if self.TraceOn():
1662 print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
1663
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001664 # We want our debugger to be synchronous.
1665 self.dbg.SetAsync(False)
1666
1667 # Retrieve the associated command interpreter instance.
1668 self.ci = self.dbg.GetCommandInterpreter()
1669 if not self.ci:
1670 raise Exception('Could not get the command interpreter')
1671
1672 # And the result object.
1673 self.res = lldb.SBCommandReturnObject()
1674
Johnny Chen44d24972012-04-16 18:55:15 +00001675 # Run global pre-flight code, if defined via the config file.
1676 if lldb.pre_flight:
1677 lldb.pre_flight(self)
1678
Greg Claytonfb909312013-11-23 01:58:15 +00001679 if lldb.remote_platform:
1680 #remote_test_dir = os.path.join(lldb.remote_platform_working_dir, self.mydir)
Greg Clayton5fb8f792013-12-02 19:35:49 +00001681 remote_test_dir = os.path.join(lldb.remote_platform_working_dir,
1682 self.getArchitecture(),
1683 str(self.test_number),
1684 self.mydir)
Greg Claytonfb909312013-11-23 01:58:15 +00001685 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 0700)
1686 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00001687 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
1688 else:
1689 print "error: making remote directory '%s': %s" % (remote_test_dir, error)
1690
Greg Clayton35c91342014-11-17 18:40:27 +00001691 def registerSharedLibrariesWithTarget(self, target, shlibs):
1692 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
1693
1694 Any modules in the target that have their remote install file specification set will
1695 get uploaded to the remote host. This function registers the local copies of the
1696 shared libraries with the target and sets their remote install locations so they will
1697 be uploaded when the target is run.
1698 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001699 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001700 return None
Greg Clayton35c91342014-11-17 18:40:27 +00001701
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001702 shlib_environment_var = self.platformContext.shlib_environment_var
1703 shlib_prefix = self.platformContext.shlib_prefix
1704 shlib_extension = '.' + self.platformContext.shlib_extension
1705
1706 working_dir = self.get_process_working_directory()
1707 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
1708 # Add any shared libraries to our target if remote so they get
1709 # uploaded into the working directory on the remote side
1710 for name in shlibs:
1711 # The path can be a full path to a shared library, or a make file name like "Foo" for
1712 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
1713 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
1714 # of the shared library accordingly
1715 if os.path.exists(name):
1716 local_shlib_path = name # name is the full path to the local shared library
1717 else:
1718 # Check relative names
1719 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
1720 if not os.path.exists(local_shlib_path):
1721 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00001722 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001723 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00001724
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001725 # Make sure we found the local shared library in the above code
1726 self.assertTrue(os.path.exists(local_shlib_path))
1727
1728 # Add the shared library to our target
1729 shlib_module = target.AddModule(local_shlib_path, None, None, None)
1730 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00001731 # We must set the remote install location if we want the shared library
1732 # to get uploaded to the remote target
1733 remote_shlib_path = os.path.join(lldb.remote_platform.GetWorkingDirectory(), os.path.basename(local_shlib_path))
1734 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001735
1736 return environment
1737
Enrico Granata44818162012-10-24 01:23:57 +00001738 # utility methods that tests can use to access the current objects
1739 def target(self):
1740 if not self.dbg:
1741 raise Exception('Invalid debugger instance')
1742 return self.dbg.GetSelectedTarget()
1743
1744 def process(self):
1745 if not self.dbg:
1746 raise Exception('Invalid debugger instance')
1747 return self.dbg.GetSelectedTarget().GetProcess()
1748
1749 def thread(self):
1750 if not self.dbg:
1751 raise Exception('Invalid debugger instance')
1752 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1753
1754 def frame(self):
1755 if not self.dbg:
1756 raise Exception('Invalid debugger instance')
1757 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1758
Greg Claytonc6947512013-12-13 19:18:59 +00001759 def get_process_working_directory(self):
1760 '''Get the working directory that should be used when launching processes for local or remote processes.'''
1761 if lldb.remote_platform:
1762 # Remote tests set the platform working directory up in TestBase.setUp()
1763 return lldb.remote_platform.GetWorkingDirectory()
1764 else:
1765 # local tests change directory into each test subdirectory
1766 return os.getcwd()
1767
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001768 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001769 #import traceback
1770 #traceback.print_stack()
1771
Johnny Chenfb4264c2011-08-01 19:50:58 +00001772 Base.tearDown(self)
Johnny Chen707d8222010-10-19 23:40:13 +00001773
Johnny Chen3794ad92011-06-15 21:24:24 +00001774 # Delete the target(s) from the debugger as a general cleanup step.
1775 # This includes terminating the process for each target, if any.
1776 # We'd like to reuse the debugger for our next test without incurring
1777 # the initialization overhead.
1778 targets = []
1779 for target in self.dbg:
1780 if target:
1781 targets.append(target)
1782 process = target.GetProcess()
1783 if process:
1784 rc = self.invoke(process, "Kill")
1785 self.assertTrue(rc.Success(), PROCESS_KILLED)
1786 for target in targets:
1787 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001788
Johnny Chen44d24972012-04-16 18:55:15 +00001789 # Run global post-flight code, if defined via the config file.
1790 if lldb.post_flight:
1791 lldb.post_flight(self)
1792
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001793 del self.dbg
Johnny Chen150c3cc2010-10-15 01:18:29 +00001794
Johnny Chen86268e42011-09-30 21:48:35 +00001795 def switch_to_thread_with_stop_reason(self, stop_reason):
1796 """
1797 Run the 'thread list' command, and select the thread with stop reason as
1798 'stop_reason'. If no such thread exists, no select action is done.
1799 """
1800 from lldbutil import stop_reason_to_str
1801 self.runCmd('thread list')
1802 output = self.res.GetOutput()
1803 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1804 stop_reason_to_str(stop_reason))
1805 for line in output.splitlines():
1806 matched = thread_line_pattern.match(line)
1807 if matched:
1808 self.runCmd('thread select %s' % matched.group(1))
1809
Enrico Granata7594f142013-06-17 22:51:50 +00001810 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001811 """
1812 Ask the command interpreter to handle the command and then check its
1813 return status.
1814 """
1815 # Fail fast if 'cmd' is not meaningful.
1816 if not cmd or len(cmd) == 0:
1817 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001818
Johnny Chen8d55a342010-08-31 17:42:54 +00001819 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001820
Daniel Maleae0f8f572013-08-26 23:57:52 +00001821 # This is an opportunity to insert the 'platform target-install' command if we are told so
1822 # via the settig of lldb.lldbtest_remote_sandbox.
1823 if cmd.startswith("target create "):
1824 cmd = cmd.replace("target create ", "file ")
1825 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
1826 with recording(self, trace) as sbuf:
1827 the_rest = cmd.split("file ")[1]
1828 # Split the rest of the command line.
1829 atoms = the_rest.split()
1830 #
1831 # NOTE: This assumes that the options, if any, follow the file command,
1832 # instead of follow the specified target.
1833 #
1834 target = atoms[-1]
1835 # Now let's get the absolute pathname of our target.
1836 abs_target = os.path.abspath(target)
1837 print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
1838 fpath, fname = os.path.split(abs_target)
1839 parent_dir = os.path.split(fpath)[0]
1840 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
1841 print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
1842 self.ci.HandleCommand(platform_target_install_command, self.res)
1843 # And this is the file command we want to execute, instead.
1844 #
1845 # Warning: SIDE EFFECT AHEAD!!!
1846 # Populate the remote executable pathname into the lldb namespace,
1847 # so that test cases can grab this thing out of the namespace.
1848 #
1849 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
1850 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
1851 print >> sbuf, "And this is the replaced file command: %s" % cmd
1852
Johnny Chen63dfb272010-09-01 00:15:19 +00001853 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001854
Johnny Chen63dfb272010-09-01 00:15:19 +00001855 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00001856 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001857
Johnny Chen150c3cc2010-10-15 01:18:29 +00001858 with recording(self, trace) as sbuf:
1859 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00001860 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00001861 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00001862 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00001863 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00001864 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001865 print >> sbuf, "runCmd failed!"
1866 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001867
Johnny Chenff3d01d2010-08-20 21:03:09 +00001868 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00001869 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00001870 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00001871 # For process launch, wait some time before possible next try.
1872 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00001873 with recording(self, trace) as sbuf:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001874 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001875
Johnny Chen27f212d2010-08-19 23:26:59 +00001876 if check:
1877 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00001878 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00001879
Jim Ingham63dfc722012-09-22 00:05:11 +00001880 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
1881 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
1882
1883 Otherwise, all the arguments have the same meanings as for the expect function"""
1884
1885 trace = (True if traceAlways else trace)
1886
1887 if exe:
1888 # First run the command. If we are expecting error, set check=False.
1889 # Pass the assert message along since it provides more semantic info.
1890 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
1891
1892 # Then compare the output against expected strings.
1893 output = self.res.GetError() if error else self.res.GetOutput()
1894
1895 # If error is True, the API client expects the command to fail!
1896 if error:
1897 self.assertFalse(self.res.Succeeded(),
1898 "Command '" + str + "' is expected to fail!")
1899 else:
1900 # No execution required, just compare str against the golden input.
1901 output = str
1902 with recording(self, trace) as sbuf:
1903 print >> sbuf, "looking at:", output
1904
1905 # The heading says either "Expecting" or "Not expecting".
1906 heading = "Expecting" if matching else "Not expecting"
1907
1908 for pattern in patterns:
1909 # Match Objects always have a boolean value of True.
1910 match_object = re.search(pattern, output)
1911 matched = bool(match_object)
1912 with recording(self, trace) as sbuf:
1913 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1914 print >> sbuf, "Matched" if matched else "Not matched"
1915 if matched:
1916 break
1917
1918 self.assertTrue(matched if matching else not matched,
1919 msg if msg else EXP_MSG(str, exe))
1920
1921 return match_object
1922
Enrico Granata7594f142013-06-17 22:51:50 +00001923 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 +00001924 """
1925 Similar to runCmd; with additional expect style output matching ability.
1926
1927 Ask the command interpreter to handle the command and then check its
1928 return status. The 'msg' parameter specifies an informational assert
1929 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00001930 'startstr', matches the substrings contained in 'substrs', and regexp
1931 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00001932
1933 If the keyword argument error is set to True, it signifies that the API
1934 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00001935 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00001936 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00001937
1938 If the keyword argument matching is set to False, it signifies that the API
1939 client is expecting the output of the command not to match the golden
1940 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001941
1942 Finally, the required argument 'str' represents the lldb command to be
1943 sent to the command interpreter. In case the keyword argument 'exe' is
1944 set to False, the 'str' is treated as a string to be matched/not-matched
1945 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00001946 """
Johnny Chen8d55a342010-08-31 17:42:54 +00001947 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001948
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001949 if exe:
1950 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00001951 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00001952 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00001953
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001954 # Then compare the output against expected strings.
1955 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00001956
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001957 # If error is True, the API client expects the command to fail!
1958 if error:
1959 self.assertFalse(self.res.Succeeded(),
1960 "Command '" + str + "' is expected to fail!")
1961 else:
1962 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00001963 if isinstance(str,lldb.SBCommandReturnObject):
1964 output = str.GetOutput()
1965 else:
1966 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00001967 with recording(self, trace) as sbuf:
1968 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00001969
Johnny Chenea88e942010-09-21 21:08:53 +00001970 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00001971 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00001972
1973 # Start from the startstr, if specified.
1974 # If there's no startstr, set the initial state appropriately.
1975 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00001976
Johnny Chen150c3cc2010-10-15 01:18:29 +00001977 if startstr:
1978 with recording(self, trace) as sbuf:
1979 print >> sbuf, "%s start string: %s" % (heading, startstr)
1980 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00001981
Johnny Chen86268e42011-09-30 21:48:35 +00001982 # Look for endstr, if specified.
1983 keepgoing = matched if matching else not matched
1984 if endstr:
1985 matched = output.endswith(endstr)
1986 with recording(self, trace) as sbuf:
1987 print >> sbuf, "%s end string: %s" % (heading, endstr)
1988 print >> sbuf, "Matched" if matched else "Not matched"
1989
Johnny Chenea88e942010-09-21 21:08:53 +00001990 # Look for sub strings, if specified.
1991 keepgoing = matched if matching else not matched
1992 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001993 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00001994 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00001995 with recording(self, trace) as sbuf:
1996 print >> sbuf, "%s sub string: %s" % (heading, str)
1997 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001998 keepgoing = matched if matching else not matched
1999 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002000 break
2001
Johnny Chenea88e942010-09-21 21:08:53 +00002002 # Search for regular expression patterns, if specified.
2003 keepgoing = matched if matching else not matched
2004 if patterns and keepgoing:
2005 for pattern in patterns:
2006 # Match Objects always have a boolean value of True.
2007 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002008 with recording(self, trace) as sbuf:
2009 print >> sbuf, "%s pattern: %s" % (heading, pattern)
2010 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00002011 keepgoing = matched if matching else not matched
2012 if not keepgoing:
2013 break
Johnny Chenea88e942010-09-21 21:08:53 +00002014
2015 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002016 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002017
Johnny Chenf3c59232010-08-25 22:52:45 +00002018 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002019 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002020 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002021
2022 method = getattr(obj, name)
2023 import inspect
2024 self.assertTrue(inspect.ismethod(method),
2025 name + "is a method name of object: " + str(obj))
2026 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002027 with recording(self, trace) as sbuf:
2028 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00002029 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002030
Johnny Chenf359cf22011-05-27 23:36:52 +00002031 # =================================================
2032 # Misc. helper methods for debugging test execution
2033 # =================================================
2034
Johnny Chen56b92a72011-07-11 19:15:11 +00002035 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002036 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00002037 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002038
Johnny Chen8d55a342010-08-31 17:42:54 +00002039 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002040 return
2041
2042 err = sys.stderr
2043 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002044 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2045 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2046 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2047 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2048 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2049 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2050 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2051 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2052 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002053
Johnny Chen36c5eb12011-08-05 20:17:27 +00002054 def DebugSBType(self, type):
2055 """Debug print a SBType object, if traceAlways is True."""
2056 if not traceAlways:
2057 return
2058
2059 err = sys.stderr
2060 err.write(type.GetName() + ":\n")
2061 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2062 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2063 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2064
Johnny Chenb877f1e2011-03-12 01:18:19 +00002065 def DebugPExpect(self, child):
2066 """Debug the spwaned pexpect object."""
2067 if not traceAlways:
2068 return
2069
2070 print child
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002071
2072 @classmethod
2073 def RemoveTempFile(cls, file):
2074 if os.path.exists(file):
2075 os.remove(file)