blob: 7fed0c47eea815f5872b0edea69345fec763ca15 [file] [log] [blame]
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001"""
2LLDB module which provides the abstract base class of lldb test case.
3
4The concrete subclass can override lldbtest.TesBase in order to inherit the
5common behavior for unitest.TestCase.setUp/tearDown implemented in this file.
6
7The subclass should override the attribute mydir in order for the python runtime
8to locate the individual test cases when running as part of a large test suite
9or when running each test case as a separate python invocation.
10
11./dotest.py provides a test driver which sets up the environment to run the
Johnny Chenc98892e2012-05-16 20:41:28 +000012entire of part of the test suite . Example:
Johnny Chenbf6ffa32010-07-03 03:41:59 +000013
Johnny Chenc98892e2012-05-16 20:41:28 +000014# Exercises the test suite in the types directory....
15/Volumes/data/lldb/svn/ToT/test $ ./dotest.py -A x86_64 types
Johnny Chen57b47382010-09-02 22:25:47 +000016...
Johnny Chend0190a62010-08-23 17:10:44 +000017
Johnny Chenc98892e2012-05-16 20:41:28 +000018Session logs for test failures/errors/unexpected successes will go into directory '2012-05-16-13_35_42'
19Command invoked: python ./dotest.py -A x86_64 types
20compilers=['clang']
Johnny Chend0190a62010-08-23 17:10:44 +000021
Johnny Chenc98892e2012-05-16 20:41:28 +000022Configuration: arch=x86_64 compiler=clang
Johnny Chend0190a62010-08-23 17:10:44 +000023----------------------------------------------------------------------
Johnny Chenc98892e2012-05-16 20:41:28 +000024Collected 72 tests
25
26........................................................................
27----------------------------------------------------------------------
28Ran 72 tests in 135.468s
Johnny Chend0190a62010-08-23 17:10:44 +000029
30OK
Johnny Chenbf6ffa32010-07-03 03:41:59 +000031$
32"""
33
Zachary Turnerff890da2015-10-19 23:45:41 +000034from __future__ import print_function
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000035from __future__ import absolute_import
Zachary Turnerff890da2015-10-19 23:45:41 +000036
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000037# System modules
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000038import abc
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000039import collections
Zachary Turnerabdb8392015-11-16 22:40:30 +000040from distutils.version import LooseVersion
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +000041import gc
Vince Harron9753dd92015-05-10 15:22:09 +000042import glob
Zachary Turnerba105702015-11-16 23:58:20 +000043import inspect
Johnny Chen90312a82010-09-21 22:34:45 +000044import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000045import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000046import re
Daniel Malea69207462013-06-05 21:07:02 +000047import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000048from subprocess import *
Johnny Chenf2b70232010-08-25 18:49:48 +000049import time
Johnny Chena33a93c2010-08-30 23:08:52 +000050import types
Zachary Turner43a01e42015-10-20 21:06:05 +000051
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000052# Third-party modules
53import unittest2
Zachary Turner43a01e42015-10-20 21:06:05 +000054from six import add_metaclass
Zachary Turner814236d2015-10-21 17:48:52 +000055from six import StringIO as SixStringIO
56from six.moves.urllib import parse as urlparse
Zachary Turnercd236b82015-10-26 18:48:24 +000057import six
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000058
59# LLDB modules
60import lldb
Zachary Turner606e3a52015-12-08 01:15:30 +000061from . import configuration
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000062from . import lldbtest_config
63from . import lldbutil
64from . import test_categories
Siva Chandra8af91662015-06-05 00:22:49 +000065
Todd Fiala9187f272015-12-11 18:06:47 +000066from .result_formatter import EventBuilder
67
Vince Harron85d19652015-05-21 19:09:29 +000068# dosep.py starts lots and lots of dotest instances
69# This option helps you find if two (or more) dotest instances are using the same
70# directory at the same time
71# Enable it to cause test failures and stderr messages if dotest instances try to run in
72# the same directory simultaneously
73# it is disabled by default because it litters the test directories with ".dirlock" files
74debug_confirm_directory_exclusivity = False
75
Johnny Chen707b3c92010-10-11 22:25:46 +000076# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000077# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000078
79# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000080if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
81 traceAlways = True
82else:
83 traceAlways = False
84
Johnny Chen707b3c92010-10-11 22:25:46 +000085# By default, doCleanup is True.
86if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
87 doCleanup = False
88else:
89 doCleanup = True
90
Johnny Chen8d55a342010-08-31 17:42:54 +000091
Johnny Chen00778092010-08-09 22:01:17 +000092#
93# Some commonly used assert messages.
94#
95
Johnny Chenaa902922010-09-17 22:45:27 +000096COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
97
Johnny Chen00778092010-08-09 22:01:17 +000098CURRENT_EXECUTABLE_SET = "Current executable set successfully"
99
Johnny Chen7d1d7532010-09-02 21:23:12 +0000100PROCESS_IS_VALID = "Process is valid"
101
102PROCESS_KILLED = "Process is killed successfully"
103
Johnny Chend5f66fc2010-12-23 01:12:19 +0000104PROCESS_EXITED = "Process exited successfully"
105
106PROCESS_STOPPED = "Process status should be stopped"
107
Sean Callanan05834cd2015-07-01 23:56:30 +0000108RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000109
Johnny Chen17941842010-08-09 23:44:24 +0000110RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000111
Johnny Chen67af43f2010-10-05 19:27:32 +0000112BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
113
Johnny Chen17941842010-08-09 23:44:24 +0000114BREAKPOINT_CREATED = "Breakpoint created successfully"
115
Johnny Chenf10af382010-12-04 00:07:24 +0000116BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
117
Johnny Chene76896c2010-08-17 21:33:31 +0000118BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
119
Johnny Chen17941842010-08-09 23:44:24 +0000120BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000121
Johnny Chen703dbd02010-09-30 17:06:24 +0000122BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
123
Johnny Chen164f1e12010-10-15 18:07:09 +0000124BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
125
Greg Clayton5db6b792012-10-24 18:24:14 +0000126MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
127
Johnny Chen89109ed12011-06-27 20:05:23 +0000128OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
129
Johnny Chen5b3a3572010-12-09 18:22:12 +0000130SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
131
Johnny Chenc70b02a2010-09-22 23:00:20 +0000132STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
133
Johnny Chen1691a162011-04-15 16:44:48 +0000134STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
135
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000136STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
137
Johnny Chen5d6c4642010-11-10 23:46:38 +0000138STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000139
Johnny Chen5d6c4642010-11-10 23:46:38 +0000140STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
141 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000142
Johnny Chen2e431ce2010-10-20 18:38:48 +0000143STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
144
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000145STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
146
Johnny Chenc066ab42010-10-14 01:22:03 +0000147STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
148
Johnny Chen00778092010-08-09 22:01:17 +0000149STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
150
Johnny Chenf68cc122011-09-15 21:09:59 +0000151STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
152
Johnny Chen3c884a02010-08-24 22:07:56 +0000153DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
154
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000155VALID_BREAKPOINT = "Got a valid breakpoint"
156
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000157VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
158
Johnny Chen7209d84f2011-05-06 23:26:12 +0000159VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
160
Johnny Chen5ee88192010-08-27 23:47:36 +0000161VALID_FILESPEC = "Got a valid filespec"
162
Johnny Chen025d1b82010-12-08 01:25:21 +0000163VALID_MODULE = "Got a valid module"
164
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000165VALID_PROCESS = "Got a valid process"
166
Johnny Chen025d1b82010-12-08 01:25:21 +0000167VALID_SYMBOL = "Got a valid symbol"
168
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000169VALID_TARGET = "Got a valid target"
170
Matthew Gardinerc928de32014-10-22 07:22:56 +0000171VALID_PLATFORM = "Got a valid platform"
172
Johnny Chen15f247a2012-02-03 20:43:00 +0000173VALID_TYPE = "Got a valid type"
174
Johnny Chen5819ab42011-07-15 22:28:10 +0000175VALID_VARIABLE = "Got a valid variable"
176
Johnny Chen981463d2010-08-25 19:00:04 +0000177VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000178
Johnny Chenf68cc122011-09-15 21:09:59 +0000179WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000180
Sean Callanan05834cd2015-07-01 23:56:30 +0000181def CMD_MSG(str):
182 '''A generic "Command '%s' returns successfully" message generator.'''
183 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000184
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000185def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000186 '''A generic message generator for the completion mechanism.'''
187 return "'%s' successfully completes to '%s'" % (str_before, str_after)
188
Johnny Chenc0c67f22010-11-09 18:42:22 +0000189def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000190 '''A generic "'%s' returns expected result" message generator if exe.
191 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000192 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000193
Johnny Chen3343f042010-10-19 19:11:38 +0000194def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000195 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000196 return "Value of setting '%s' is correct" % setting
197
Johnny Chen27c41232010-08-26 21:49:29 +0000198def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000199 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000200 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000201
Johnny Chen47ceb032010-10-11 23:52:19 +0000202def line_number(filename, string_to_match):
203 """Helper function to return the line number of the first matched string."""
204 with open(filename, 'r') as f:
205 for i, line in enumerate(f):
206 if line.find(string_to_match) != -1:
207 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000208 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000209 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000210
Johnny Chen67af43f2010-10-05 19:27:32 +0000211def pointer_size():
212 """Return the pointer size of the host system."""
213 import ctypes
214 a_pointer = ctypes.c_void_p(0xffff)
215 return 8 * ctypes.sizeof(a_pointer)
216
Johnny Chen57816732012-02-09 02:01:59 +0000217def is_exe(fpath):
218 """Returns true if fpath is an executable."""
219 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
220
221def which(program):
222 """Returns the full path to a program; None otherwise."""
223 fpath, fname = os.path.split(program)
224 if fpath:
225 if is_exe(program):
226 return program
227 else:
228 for path in os.environ["PATH"].split(os.pathsep):
229 exe_file = os.path.join(path, program)
230 if is_exe(exe_file):
231 return exe_file
232 return None
233
Zachary Turner814236d2015-10-21 17:48:52 +0000234class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000235 """
236 A nice little context manager for recording the debugger interactions into
237 our session object. If trace flag is ON, it also emits the interactions
238 into the stderr.
239 """
240 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000241 """Create a SixStringIO instance; record the session obj and trace flag."""
242 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000243 # The test might not have undergone the 'setUp(self)' phase yet, so that
244 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000245 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000246 self.trace = trace
247
248 def __enter__(self):
249 """
250 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000251 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000252 """
253 return self
254
255 def __exit__(self, type, value, tb):
256 """
257 Context management protocol on exit from the body of the with statement.
258 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000259 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000260 """
261 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000262 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000263 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000264 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000265 self.close()
266
Zachary Turner43a01e42015-10-20 21:06:05 +0000267@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000268class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000269
270 @abc.abstractproperty
271 def pid(self):
272 """Returns process PID if has been launched already."""
273
274 @abc.abstractmethod
275 def launch(self, executable, args):
276 """Launches new process with given executable and args."""
277
278 @abc.abstractmethod
279 def terminate(self):
280 """Terminates previously launched process.."""
281
282class _LocalProcess(_BaseProcess):
283
284 def __init__(self, trace_on):
285 self._proc = None
286 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000287 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000288
289 @property
290 def pid(self):
291 return self._proc.pid
292
293 def launch(self, executable, args):
294 self._proc = Popen([executable] + args,
295 stdout = open(os.devnull) if not self._trace_on else None,
296 stdin = PIPE)
297
298 def terminate(self):
299 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000300 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000301 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
302 for sig in signals_to_try:
303 try:
304 self._proc.send_signal(getattr(signal, sig))
305 time.sleep(self._delayafterterminate)
306 if self._proc.poll() != None:
307 return
308 except ValueError:
309 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000310 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000311 time.sleep(self._delayafterterminate)
312 if self._proc.poll() != None:
313 return
314 self._proc.kill()
315 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000316
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000317 def poll(self):
318 return self._proc.poll()
319
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000320class _RemoteProcess(_BaseProcess):
321
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000322 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000323 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000324 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000325
326 @property
327 def pid(self):
328 return self._pid
329
330 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000331 if self._install_remote:
332 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000333 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000334
335 dst_file_spec = lldb.SBFileSpec(dst_path, False)
336 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
337 if err.Fail():
338 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
339 else:
340 dst_path = executable
341 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000342
343 launch_info = lldb.SBLaunchInfo(args)
344 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000345 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000346
347 # Redirect stdout and stderr to /dev/null
348 launch_info.AddSuppressFileAction(1, False, True)
349 launch_info.AddSuppressFileAction(2, False, True)
350
351 err = lldb.remote_platform.Launch(launch_info)
352 if err.Fail():
353 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
354 self._pid = launch_info.GetProcessID()
355
356 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000357 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000358
Johnny Chen690fcef2010-10-15 23:55:05 +0000359# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000360# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000361def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000362 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000363
364 If the exit code was non-zero it raises a CalledProcessError. The
365 CalledProcessError object will have the return code in the returncode
366 attribute and output in the output attribute.
367
368 The arguments are the same as for the Popen constructor. Example:
369
370 >>> check_output(["ls", "-l", "/dev/null"])
371 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
372
373 The stdout argument is not allowed as it is used internally.
374 To capture standard error in the result, use stderr=STDOUT.
375
376 >>> check_output(["/bin/sh", "-c",
377 ... "ls -l non_existent_file ; exit 0"],
378 ... stderr=STDOUT)
379 'ls: non_existent_file: No such file or directory\n'
380 """
381
382 # Assign the sender object to variable 'test' and remove it from kwargs.
383 test = kwargs.pop('sender', None)
384
Zachary Turner9ef307b2014-07-22 16:19:29 +0000385 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
386 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000387 output = ""
388 error = ""
389 for shellCommand in commandList:
390 if 'stdout' in kwargs:
391 raise ValueError('stdout argument not allowed, it will be overridden.')
392 if 'shell' in kwargs and kwargs['shell']==False:
393 raise ValueError('shell=False not allowed')
Zachary Turner48ef8d4c2015-11-18 18:40:16 +0000394 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, **kwargs)
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000395 pid = process.pid
396 this_output, this_error = process.communicate()
397 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000398
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000399 # Enable trace on failure return while tracking down FreeBSD buildbot issues
400 trace = traceAlways
401 if not trace and retcode and sys.platform.startswith("freebsd"):
402 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000403
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000404 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000405 print(file=sbuf)
406 print("os command:", shellCommand, file=sbuf)
407 print("with pid:", pid, file=sbuf)
408 print("stdout:", this_output, file=sbuf)
409 print("stderr:", this_error, file=sbuf)
410 print("retcode:", retcode, file=sbuf)
411 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000412
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000413 if retcode:
414 cmd = kwargs.get("args")
415 if cmd is None:
416 cmd = shellCommand
417 raise CalledProcessError(retcode, cmd)
418 output = output + this_output
419 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000420 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000421
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000422def getsource_if_available(obj):
423 """
424 Return the text of the source code for an object if available. Otherwise,
425 a print representation is returned.
426 """
427 import inspect
428 try:
429 return inspect.getsource(obj)
430 except:
431 return repr(obj)
432
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000433def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000434 if sys.platform.startswith("freebsd"):
435 return __import__("builder_freebsd")
Kamil Rytarowski0b655da2015-12-05 18:46:56 +0000436 if sys.platform.startswith("netbsd"):
437 return __import__("builder_netbsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000438 return __import__("builder_" + sys.platform)
439
Siva Chandra8af91662015-06-05 00:22:49 +0000440def run_adb_command(cmd, device_id):
441 device_id_args = []
442 if device_id:
443 device_id_args = ["-s", device_id]
444 full_cmd = ["adb"] + device_id_args + cmd
445 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
446 stdout, stderr = p.communicate()
447 return p.returncode, stdout, stderr
448
Chaoren Line9bbabc2015-07-18 00:37:55 +0000449def append_android_envs(dictionary):
450 if dictionary is None:
451 dictionary = {}
452 dictionary["OS"] = "Android"
453 if android_device_api() >= 16:
454 dictionary["PIE"] = 1
455 return dictionary
456
Chaoren Lin9070f532015-07-17 22:13:29 +0000457def target_is_android():
458 if not hasattr(target_is_android, 'result'):
459 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
460 match = re.match(".*-.*-.*-android", triple)
461 target_is_android.result = match is not None
462 return target_is_android.result
463
Siva Chandra8af91662015-06-05 00:22:49 +0000464def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000465 if not hasattr(android_device_api, 'result'):
Zachary Turner606e3a52015-12-08 01:15:30 +0000466 assert configuration.lldb_platform_url is not None
Chaoren Lin9070f532015-07-17 22:13:29 +0000467 device_id = None
Zachary Turner606e3a52015-12-08 01:15:30 +0000468 parsed_url = urlparse.urlparse(configuration.lldb_platform_url)
Ying Chenca922bb2015-11-18 19:03:20 +0000469 host_name = parsed_url.netloc.split(":")[0]
470 if host_name != 'localhost':
471 device_id = host_name
472 if device_id.startswith('[') and device_id.endswith(']'):
473 device_id = device_id[1:-1]
Chaoren Lin9070f532015-07-17 22:13:29 +0000474 retcode, stdout, stderr = run_adb_command(
475 ["shell", "getprop", "ro.build.version.sdk"], device_id)
476 if retcode == 0:
477 android_device_api.result = int(stdout)
478 else:
479 raise LookupError(
480 ">>> Unable to determine the API level of the Android device.\n"
481 ">>> stdout:\n%s\n"
482 ">>> stderr:\n%s\n" % (stdout, stderr))
483 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000484
Zachary Turnerabdb8392015-11-16 22:40:30 +0000485def check_expected_version(comparison, expected, actual):
486 def fn_leq(x,y): return x <= y
487 def fn_less(x,y): return x < y
488 def fn_geq(x,y): return x >= y
489 def fn_greater(x,y): return x > y
490 def fn_eq(x,y): return x == y
491 def fn_neq(x,y): return x != y
492
493 op_lookup = {
494 "==": fn_eq,
495 "=": fn_eq,
496 "!=": fn_neq,
497 "<>": fn_neq,
498 ">": fn_greater,
499 "<": fn_less,
500 ">=": fn_geq,
501 "<=": fn_leq
502 }
503 expected_str = '.'.join([str(x) for x in expected])
504 actual_str = '.'.join([str(x) for x in actual])
505
506 return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str))
507
Johnny Chena74bb0a2011-08-01 18:46:13 +0000508#
509# Decorators for categorizing test cases.
510#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000511from functools import wraps
Pavel Labathffbf9e82015-12-14 13:17:18 +0000512
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000513def add_test_categories(cat):
Pavel Labathffbf9e82015-12-14 13:17:18 +0000514 """Add test categories to a TestCase method"""
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000515 cat = test_categories.validate(cat, True)
516 def impl(func):
Pavel Labathffbf9e82015-12-14 13:17:18 +0000517 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
518 raise Exception("@add_test_categories can only be used to decorate a test method")
519 if hasattr(func, "categories"):
520 cat.extend(func.categories)
521 func.categories = cat
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000522 return func
Pavel Labathffbf9e82015-12-14 13:17:18 +0000523
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000524 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000525
Johnny Chena74bb0a2011-08-01 18:46:13 +0000526def benchmarks_test(func):
527 """Decorate the item as a benchmarks test."""
528 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
529 raise Exception("@benchmarks_test can only be used to decorate a test method")
530 @wraps(func)
531 def wrapper(self, *args, **kwargs):
Zachary Turneraad25fb2015-12-08 18:36:05 +0000532 self.skipTest("benchmarks test")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000533 return func(self, *args, **kwargs)
534
535 # Mark this function as such to separate them from the regular tests.
536 wrapper.__benchmarks_test__ = True
537 return wrapper
538
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000539def no_debug_info_test(func):
540 """Decorate the item as a test what don't use any debug info. If this annotation is specified
541 then the test runner won't generate a separate test for each debug info format. """
542 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
543 raise Exception("@no_debug_info_test can only be used to decorate a test method")
544 @wraps(func)
545 def wrapper(self, *args, **kwargs):
546 return func(self, *args, **kwargs)
547
548 # Mark this function as such to separate them from the regular tests.
549 wrapper.__no_debug_info_test__ = True
550 return wrapper
551
Johnny Chenf1548d42012-04-06 00:56:05 +0000552def dsym_test(func):
553 """Decorate the item as a dsym test."""
554 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
555 raise Exception("@dsym_test can only be used to decorate a test method")
556 @wraps(func)
557 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000558 if configuration.dont_do_dsym_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000559 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000560 return func(self, *args, **kwargs)
561
562 # Mark this function as such to separate them from the regular tests.
563 wrapper.__dsym_test__ = True
564 return wrapper
565
566def dwarf_test(func):
567 """Decorate the item as a dwarf test."""
568 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
569 raise Exception("@dwarf_test can only be used to decorate a test method")
570 @wraps(func)
571 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000572 if configuration.dont_do_dwarf_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000573 self.skipTest("dwarf tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000574 return func(self, *args, **kwargs)
575
576 # Mark this function as such to separate them from the regular tests.
577 wrapper.__dwarf_test__ = True
578 return wrapper
579
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000580def dwo_test(func):
581 """Decorate the item as a dwo test."""
582 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
583 raise Exception("@dwo_test can only be used to decorate a test method")
584 @wraps(func)
585 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000586 if configuration.dont_do_dwo_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000587 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000588 return func(self, *args, **kwargs)
589
590 # Mark this function as such to separate them from the regular tests.
591 wrapper.__dwo_test__ = True
592 return wrapper
593
Todd Fialaa41d48c2014-04-28 04:49:40 +0000594def debugserver_test(func):
595 """Decorate the item as a debugserver test."""
596 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
597 raise Exception("@debugserver_test can only be used to decorate a test method")
598 @wraps(func)
599 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000600 if configuration.dont_do_debugserver_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000601 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000602 return func(self, *args, **kwargs)
603
604 # Mark this function as such to separate them from the regular tests.
605 wrapper.__debugserver_test__ = True
606 return wrapper
607
608def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000609 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000610 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
611 raise Exception("@llgs_test can only be used to decorate a test method")
612 @wraps(func)
613 def wrapper(self, *args, **kwargs):
Zachary Turner606e3a52015-12-08 01:15:30 +0000614 if configuration.dont_do_llgs_test:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000615 self.skipTest("llgs tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000616 return func(self, *args, **kwargs)
617
618 # Mark this function as such to separate them from the regular tests.
619 wrapper.__llgs_test__ = True
620 return wrapper
621
Daniel Maleae0f8f572013-08-26 23:57:52 +0000622def not_remote_testsuite_ready(func):
623 """Decorate the item as a test which is not ready yet for remote testsuite."""
624 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
625 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
626 @wraps(func)
627 def wrapper(self, *args, **kwargs):
Zachary Turnerd865c6b2015-12-08 22:15:48 +0000628 if lldb.remote_platform:
Pavel Labathf882f6f2015-10-12 13:42:16 +0000629 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000630 return func(self, *args, **kwargs)
631
632 # Mark this function as such to separate them from the regular tests.
633 wrapper.__not_ready_for_remote_testsuite_test__ = True
634 return wrapper
635
Ed Maste433790a2014-04-23 12:55:41 +0000636def expectedFailure(expected_fn, bugnumber=None):
637 def expectedFailure_impl(func):
638 @wraps(func)
639 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000640 from unittest2 import case
641 self = args[0]
Ed Maste433790a2014-04-23 12:55:41 +0000642 if expected_fn(self):
Zachary Turner5cb8e672015-11-06 18:14:42 +0000643 xfail_func = unittest2.expectedFailure(func)
644 xfail_func(*args, **kwargs)
645 else:
646 func(*args, **kwargs)
Ed Maste433790a2014-04-23 12:55:41 +0000647 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000648 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
649 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000650 if six.callable(bugnumber):
Ying Chen464d1e12015-03-27 00:26:52 +0000651 return expectedFailure_impl(bugnumber)
652 else:
653 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000654
Ying Chen0c352822015-11-16 23:41:02 +0000655# You can also pass not_in(list) to reverse the sense of the test for the arguments that
656# are simple lists, namely oslist, compiler, and debug_info.
657
658def not_in (iterable):
659 return lambda x : x not in iterable
660
Siva Chandra7dcad312015-11-20 20:30:36 +0000661def check_list_or_lambda (list_or_lambda, value):
662 if six.callable(list_or_lambda):
663 return list_or_lambda(value)
664 else:
665 return list_or_lambda is None or value is None or value in list_or_lambda
Ying Chen0c352822015-11-16 23:41:02 +0000666
Ying Chen7091c2c2015-04-21 01:15:47 +0000667# provide a function to xfail on defined oslist, compiler version, and archs
668# if none is specified for any argument, that argument won't be checked and thus means for all
669# for example,
670# @expectedFailureAll, xfail for all platform/compiler/arch,
671# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
672# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Pavel Labath7ead0b92015-12-09 10:54:18 +0000673def expectedFailureAll(bugnumber=None, oslist=None, hostoslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None, swig_version=None, py_version=None):
Ying Chen7091c2c2015-04-21 01:15:47 +0000674 def fn(self):
Siva Chandra7dcad312015-11-20 20:30:36 +0000675 oslist_passes = check_list_or_lambda(oslist, self.getPlatform())
Pavel Labath7ead0b92015-12-09 10:54:18 +0000676 hostoslist_passes = check_list_or_lambda(hostoslist, getHostPlatform())
Siva Chandra7dcad312015-11-20 20:30:36 +0000677 compiler_passes = check_list_or_lambda(self.getCompiler(), compiler) and self.expectedCompilerVersion(compiler_version)
Zachary Turnerabdb8392015-11-16 22:40:30 +0000678 arch_passes = self.expectedArch(archs)
679 triple_passes = triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())
Siva Chandra7dcad312015-11-20 20:30:36 +0000680 debug_info_passes = check_list_or_lambda(debug_info, self.debug_info)
Zachary Turnerabdb8392015-11-16 22:40:30 +0000681 swig_version_passes = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (check_expected_version(swig_version[0], swig_version[1], lldb.swig_version))
682 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
683
684 return (oslist_passes and
Pavel Labath7ead0b92015-12-09 10:54:18 +0000685 hostoslist_passes and
Zachary Turnerabdb8392015-11-16 22:40:30 +0000686 compiler_passes and
687 arch_passes and
688 triple_passes and
689 debug_info_passes and
690 swig_version_passes and
691 py_version_passes)
Ying Chen7091c2c2015-04-21 01:15:47 +0000692 return expectedFailure(fn, bugnumber)
693
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000694def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000695 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
696
697def expectedFailureDwo(bugnumber=None):
698 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000699
700def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000701 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000702
703def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
704 if compiler_version is None:
705 compiler_version=['=', None]
706 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
707
Vince Harron8974ce22015-03-13 19:54:54 +0000708# to XFAIL a specific clang versions, try this
709# @expectedFailureClang('bugnumber', ['<=', '3.4'])
710def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000711 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000712
713def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000714 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000715
Matt Kopec0de53f02013-03-15 19:10:12 +0000716def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000717 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000718
Ed Maste433790a2014-04-23 12:55:41 +0000719def expectedFailureArch(arch, bugnumber=None):
720 def fn(self):
721 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000722 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000723
Enrico Granatae6cedc12013-02-23 01:05:23 +0000724def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000725 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000726
Matt Kopecee969f92013-09-26 23:30:59 +0000727def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000728 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000729
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000730def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000731 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000732 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000733 self.expectedCompiler(compilers) and
734 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000735 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000736
Chaoren Linf7160f32015-06-09 17:39:27 +0000737def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
738 def fn(self):
739 return (getHostPlatform() in oslist and
740 self.expectedCompiler(compilers))
741 return expectedFailure(fn, bugnumber)
742
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000743def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000744 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000745 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000746
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000747def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
748 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000749
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000750def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
751 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000752
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000753def expectedFailureNetBSD(bugnumber=None, compilers=None, debug_info=None):
754 return expectedFailureOS(['netbsd'], bugnumber, compilers, debug_info=debug_info)
755
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000756def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
757 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000758
Chaoren Linf7160f32015-06-09 17:39:27 +0000759def expectedFailureHostWindows(bugnumber=None, compilers=None):
760 return expectedFailureHostOS(['windows'], bugnumber, compilers)
761
Pavel Labath090152b2015-08-20 11:37:19 +0000762def matchAndroid(api_levels=None, archs=None):
763 def match(self):
764 if not target_is_android():
765 return False
766 if archs is not None and self.getArchitecture() not in archs:
767 return False
768 if api_levels is not None and android_device_api() not in api_levels:
769 return False
770 return True
771 return match
772
773
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000774def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000775 """ Mark a test as xfail for Android.
776
777 Arguments:
778 bugnumber - The LLVM pr associated with the problem.
779 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000780 for which a test is expected to fail. None means all API level.
781 arch - A sequence of architecture names specifying the architectures
782 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000783 """
Pavel Labath090152b2015-08-20 11:37:19 +0000784 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000785
Vince Harron7ac3ea42015-06-26 15:13:21 +0000786# if the test passes on the first try, we're done (success)
787# if the test fails once, then passes on the second try, raise an ExpectedFailure
788# if the test fails twice in a row, re-throw the exception from the second test run
789def expectedFlakey(expected_fn, bugnumber=None):
790 def expectedFailure_impl(func):
791 @wraps(func)
792 def wrapper(*args, **kwargs):
793 from unittest2 import case
794 self = args[0]
Todd Fiala9187f272015-12-11 18:06:47 +0000795 if expected_fn(self):
796 # Send event marking test as explicitly eligible for rerunning.
797 if configuration.results_formatter_object is not None:
798 # Mark this test as rerunnable.
799 configuration.results_formatter_object.handle_event(
800 EventBuilder.event_for_mark_test_rerun_eligible(self))
Vince Harron7ac3ea42015-06-26 15:13:21 +0000801 try:
802 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000803 # don't retry if the test case is already decorated with xfail or skip
804 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
805 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000806 except Exception:
807 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000808 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000809 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000810 self.tearDown()
811 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000812 func(*args, **kwargs)
813 except Exception:
814 # oh snap! two failures in a row, record a failure/error
815 raise
816 # record the expected failure
817 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
818 else:
819 raise
820 return wrapper
821 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
822 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000823 if six.callable(bugnumber):
Vince Harron7ac3ea42015-06-26 15:13:21 +0000824 return expectedFailure_impl(bugnumber)
825 else:
826 return expectedFailure_impl
827
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000828def expectedFlakeyDwarf(bugnumber=None):
829 def fn(self):
830 return self.debug_info == "dwarf"
831 return expectedFlakey(fn, bugnumber)
832
833def expectedFlakeyDsym(bugnumber=None):
834 def fn(self):
835 return self.debug_info == "dwarf"
836 return expectedFlakey(fn, bugnumber)
837
Vince Harron7ac3ea42015-06-26 15:13:21 +0000838def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
839 def fn(self):
840 return (self.getPlatform() in oslist and
841 self.expectedCompiler(compilers))
842 return expectedFlakey(fn, bugnumber)
843
844def expectedFlakeyDarwin(bugnumber=None, compilers=None):
845 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
846 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
847
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000848def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
849 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
850
Vince Harron7ac3ea42015-06-26 15:13:21 +0000851def expectedFlakeyLinux(bugnumber=None, compilers=None):
852 return expectedFlakeyOS(['linux'], bugnumber, compilers)
853
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000854def expectedFlakeyNetBSD(bugnumber=None, compilers=None):
855 return expectedFlakeyOS(['netbsd'], bugnumber, compilers)
Vince Harron7ac3ea42015-06-26 15:13:21 +0000856
857def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
858 if compiler_version is None:
859 compiler_version=['=', None]
860 def fn(self):
861 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
862 return expectedFlakey(fn, bugnumber)
863
864# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
865def expectedFlakeyClang(bugnumber=None, compiler_version=None):
866 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
867
868# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
869def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
870 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
871
Pavel Labath63a579c2015-09-07 12:15:27 +0000872def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
873 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
874
Greg Clayton12514562013-12-05 22:22:32 +0000875def skipIfRemote(func):
876 """Decorate the item to skip tests if testing remotely."""
877 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
878 raise Exception("@skipIfRemote can only be used to decorate a test method")
879 @wraps(func)
880 def wrapper(*args, **kwargs):
881 from unittest2 import case
882 if lldb.remote_platform:
883 self = args[0]
884 self.skipTest("skip on remote platform")
885 else:
886 func(*args, **kwargs)
887 return wrapper
888
Siva Chandra4470f382015-06-17 22:32:27 +0000889def skipUnlessListedRemote(remote_list=None):
890 def myImpl(func):
891 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
892 raise Exception("@skipIfRemote can only be used to decorate a "
893 "test method")
894
895 @wraps(func)
896 def wrapper(*args, **kwargs):
897 if remote_list and lldb.remote_platform:
898 self = args[0]
899 triple = self.dbg.GetSelectedPlatform().GetTriple()
900 for r in remote_list:
901 if r in triple:
902 func(*args, **kwargs)
903 return
904 self.skipTest("skip on remote platform %s" % str(triple))
905 else:
906 func(*args, **kwargs)
907 return wrapper
908
909 return myImpl
910
Greg Clayton12514562013-12-05 22:22:32 +0000911def skipIfRemoteDueToDeadlock(func):
912 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
913 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
914 raise Exception("@skipIfRemote can only be used to decorate a test method")
915 @wraps(func)
916 def wrapper(*args, **kwargs):
917 from unittest2 import case
918 if lldb.remote_platform:
919 self = args[0]
920 self.skipTest("skip on remote platform (deadlocks)")
921 else:
922 func(*args, **kwargs)
923 return wrapper
924
Enrico Granatab633e432014-10-06 21:37:06 +0000925def skipIfNoSBHeaders(func):
926 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
927 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000928 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000929 @wraps(func)
930 def wrapper(*args, **kwargs):
931 from unittest2 import case
932 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000933 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000934 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000935 else:
936 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000937 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000938 if not os.path.exists(header):
939 self.skipTest("skip because LLDB.h header not found")
940 else:
941 func(*args, **kwargs)
942 return wrapper
943
Enrico Granata5f92a132015-11-05 00:46:25 +0000944def skipIfiOSSimulator(func):
945 """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
Zachary Turner606e3a52015-12-08 01:15:30 +0000946 return unittest2.skipIf(configuration.lldb_platform_name == 'ios-simulator', 'skip on the iOS Simulator')(func)
Enrico Granata5f92a132015-11-05 00:46:25 +0000947
Robert Flack13c7ad92015-03-30 14:12:17 +0000948def skipIfFreeBSD(func):
949 """Decorate the item to skip tests that should be skipped on FreeBSD."""
950 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000951
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +0000952def skipIfNetBSD(func):
953 """Decorate the item to skip tests that should be skipped on NetBSD."""
954 return skipIfPlatform(["netbsd"])(func)
955
Greg Claytone0d0a762015-04-02 18:24:03 +0000956def getDarwinOSTriples():
957 return ['darwin', 'macosx', 'ios']
958
Daniel Maleab3d41a22013-07-09 00:08:01 +0000959def skipIfDarwin(func):
960 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000961 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000962
Robert Flack13c7ad92015-03-30 14:12:17 +0000963def skipIfLinux(func):
964 """Decorate the item to skip tests that should be skipped on Linux."""
965 return skipIfPlatform(["linux"])(func)
966
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000967def skipUnlessHostLinux(func):
968 """Decorate the item to skip tests that should be skipped on any non Linux host."""
969 return skipUnlessHostPlatform(["linux"])(func)
970
Robert Flack13c7ad92015-03-30 14:12:17 +0000971def skipIfWindows(func):
972 """Decorate the item to skip tests that should be skipped on Windows."""
973 return skipIfPlatform(["windows"])(func)
974
Chaoren Line6eea5d2015-06-08 22:13:28 +0000975def skipIfHostWindows(func):
976 """Decorate the item to skip tests that should be skipped on Windows."""
977 return skipIfHostPlatform(["windows"])(func)
978
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000979def skipUnlessWindows(func):
980 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
981 return skipUnlessPlatform(["windows"])(func)
982
Robert Flack13c7ad92015-03-30 14:12:17 +0000983def skipUnlessDarwin(func):
984 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000985 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000986
Ryan Brown57bee1e2015-09-14 22:45:11 +0000987def skipUnlessGoInstalled(func):
988 """Decorate the item to skip tests when no Go compiler is available."""
989 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
990 raise Exception("@skipIfGcc can only be used to decorate a test method")
991 @wraps(func)
992 def wrapper(*args, **kwargs):
993 from unittest2 import case
994 self = args[0]
995 compiler = self.getGoCompilerVersion()
996 if not compiler:
997 self.skipTest("skipping because go compiler not found")
998 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000999 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +00001000 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +00001001 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
1002 if not match_version:
1003 # Couldn't determine version.
1004 self.skipTest(
1005 "skipping because go version could not be parsed "
1006 "out of {}".format(compiler))
1007 else:
1008 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +00001009 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +00001010 compiler_strict_version = StrictVersion(match_version.group(1))
1011 if compiler_strict_version < min_strict_version:
1012 self.skipTest(
1013 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +00001014 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +00001015 compiler_strict_version,
1016 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +00001017 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +00001018 return wrapper
1019
Robert Flack068898c2015-04-09 18:07:58 +00001020def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +00001021 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001022 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
1023 if platform.startswith('freebsd'):
1024 platform = 'freebsd'
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001025 elif platform.startswith('netbsd'):
1026 platform = 'netbsd'
Robert Flack068898c2015-04-09 18:07:58 +00001027 return platform
1028
Robert Flack6e1fd352015-05-15 12:39:33 +00001029def getHostPlatform():
1030 """Returns the host platform running the test suite."""
1031 # Attempts to return a platform name matching a target Triple platform.
1032 if sys.platform.startswith('linux'):
1033 return 'linux'
1034 elif sys.platform.startswith('win32'):
1035 return 'windows'
1036 elif sys.platform.startswith('darwin'):
1037 return 'darwin'
1038 elif sys.platform.startswith('freebsd'):
1039 return 'freebsd'
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001040 elif sys.platform.startswith('netbsd'):
1041 return 'netbsd'
Robert Flack6e1fd352015-05-15 12:39:33 +00001042 else:
1043 return sys.platform
1044
Robert Flackfb2f6c62015-04-17 08:02:18 +00001045def platformIsDarwin():
1046 """Returns true if the OS triple for the selected platform is any valid apple OS"""
1047 return getPlatform() in getDarwinOSTriples()
1048
Robert Flack6e1fd352015-05-15 12:39:33 +00001049def skipIfHostIncompatibleWithRemote(func):
1050 """Decorate the item to skip tests if binaries built on this host are incompatible."""
1051 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1052 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
1053 @wraps(func)
1054 def wrapper(*args, **kwargs):
1055 from unittest2 import case
1056 self = args[0]
1057 host_arch = self.getLldbArchitecture()
1058 host_platform = getHostPlatform()
1059 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +00001060 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +00001061 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
1062 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
1063 elif target_platform != host_platform:
1064 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
1065 else:
1066 func(*args, **kwargs)
1067 return wrapper
1068
Chaoren Line6eea5d2015-06-08 22:13:28 +00001069def skipIfHostPlatform(oslist):
1070 """Decorate the item to skip tests if running on one of the listed host platforms."""
1071 return unittest2.skipIf(getHostPlatform() in oslist,
1072 "skip on %s" % (", ".join(oslist)))
1073
1074def skipUnlessHostPlatform(oslist):
1075 """Decorate the item to skip tests unless running on one of the listed host platforms."""
1076 return unittest2.skipUnless(getHostPlatform() in oslist,
1077 "requires on of %s" % (", ".join(oslist)))
1078
Zachary Turner793d9972015-08-14 23:29:24 +00001079def skipUnlessArch(archlist):
1080 """Decorate the item to skip tests unless running on one of the listed architectures."""
1081 def myImpl(func):
1082 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1083 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1084
1085 @wraps(func)
1086 def wrapper(*args, **kwargs):
1087 self = args[0]
1088 if self.getArchitecture() not in archlist:
1089 self.skipTest("skipping for architecture %s (requires one of %s)" %
1090 (self.getArchitecture(), ", ".join(archlist)))
1091 else:
1092 func(*args, **kwargs)
1093 return wrapper
1094
1095 return myImpl
1096
Robert Flack13c7ad92015-03-30 14:12:17 +00001097def skipIfPlatform(oslist):
1098 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001099 return unittest2.skipIf(getPlatform() in oslist,
1100 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001101
1102def skipUnlessPlatform(oslist):
1103 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001104 return unittest2.skipUnless(getPlatform() in oslist,
1105 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001106
Daniel Malea48359902013-05-14 20:48:54 +00001107def skipIfLinuxClang(func):
1108 """Decorate the item to skip tests that should be skipped if building on
1109 Linux with clang.
1110 """
1111 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1112 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1113 @wraps(func)
1114 def wrapper(*args, **kwargs):
1115 from unittest2 import case
1116 self = args[0]
1117 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001118 platform = self.getPlatform()
1119 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001120 self.skipTest("skipping because Clang is used on Linux")
1121 else:
1122 func(*args, **kwargs)
1123 return wrapper
1124
Ying Chen7091c2c2015-04-21 01:15:47 +00001125# provide a function to skip on defined oslist, compiler version, and archs
1126# if none is specified for any argument, that argument won't be checked and thus means for all
1127# for example,
1128# @skipIf, skip for all platform/compiler/arch,
1129# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1130# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1131
1132# TODO: refactor current code, to make skipIfxxx functions to call this function
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001133def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None, swig_version=None, py_version=None, remote=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001134 def fn(self):
Siva Chandra7dcad312015-11-20 20:30:36 +00001135 oslist_passes = oslist is None or self.getPlatform() in oslist
1136 compiler_passes = compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))
Zachary Turnerabdb8392015-11-16 22:40:30 +00001137 arch_passes = self.expectedArch(archs)
Siva Chandra7dcad312015-11-20 20:30:36 +00001138 debug_info_passes = debug_info is None or self.debug_info in debug_info
Zachary Turnerabdb8392015-11-16 22:40:30 +00001139 swig_version_passes = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (check_expected_version(swig_version[0], swig_version[1], lldb.swig_version))
1140 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001141 remote_passes = (remote is None) or (remote == (lldb.remote_platform is not None))
Zachary Turnerabdb8392015-11-16 22:40:30 +00001142
1143 return (oslist_passes and
1144 compiler_passes and
1145 arch_passes and
1146 debug_info_passes and
1147 swig_version_passes and
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001148 py_version_passes and
1149 remote_passes)
Zachary Turnerba105702015-11-16 23:58:20 +00001150
1151 local_vars = locals()
1152 args = [x for x in inspect.getargspec(skipIf).args]
1153 arg_vals = [eval(x, globals(), local_vars) for x in args]
1154 args = [x for x in zip(args, arg_vals) if x[1] is not None]
1155 reasons = ['%s=%s' % (x, str(y)) for (x,y) in args]
1156 return skipTestIfFn(fn, bugnumber, skipReason='skipping because ' + ' && '.join(reasons))
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001157
1158def skipIfDebugInfo(bugnumber=None, debug_info=None):
1159 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1160
Greg Claytonedea2372015-10-07 20:01:13 +00001161def skipIfDWO(bugnumber=None):
1162 return skipIfDebugInfo(bugnumber, ["dwo"])
1163
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001164def skipIfDwarf(bugnumber=None):
1165 return skipIfDebugInfo(bugnumber, ["dwarf"])
1166
1167def skipIfDsym(bugnumber=None):
1168 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001169
1170def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1171 def skipTestIfFn_impl(func):
1172 @wraps(func)
1173 def wrapper(*args, **kwargs):
1174 from unittest2 import case
1175 self = args[0]
1176 if expected_fn(self):
1177 self.skipTest(skipReason)
1178 else:
1179 func(*args, **kwargs)
1180 return wrapper
Zachary Turnercd236b82015-10-26 18:48:24 +00001181 if six.callable(bugnumber):
Ying Chen7091c2c2015-04-21 01:15:47 +00001182 return skipTestIfFn_impl(bugnumber)
1183 else:
1184 return skipTestIfFn_impl
1185
Daniel Maleabe230792013-01-24 23:52:09 +00001186def skipIfGcc(func):
1187 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1188 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001189 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001190 @wraps(func)
1191 def wrapper(*args, **kwargs):
1192 from unittest2 import case
1193 self = args[0]
1194 compiler = self.getCompiler()
1195 if "gcc" in compiler:
1196 self.skipTest("skipping because gcc is the test compiler")
1197 else:
1198 func(*args, **kwargs)
1199 return wrapper
1200
Matt Kopec0de53f02013-03-15 19:10:12 +00001201def skipIfIcc(func):
1202 """Decorate the item to skip tests that should be skipped if building with icc ."""
1203 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1204 raise Exception("@skipIfIcc can only be used to decorate a test method")
1205 @wraps(func)
1206 def wrapper(*args, **kwargs):
1207 from unittest2 import case
1208 self = args[0]
1209 compiler = self.getCompiler()
1210 if "icc" in compiler:
1211 self.skipTest("skipping because icc is the test compiler")
1212 else:
1213 func(*args, **kwargs)
1214 return wrapper
1215
Daniel Malea55faa402013-05-02 21:44:31 +00001216def skipIfi386(func):
1217 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1218 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1219 raise Exception("@skipIfi386 can only be used to decorate a test method")
1220 @wraps(func)
1221 def wrapper(*args, **kwargs):
1222 from unittest2 import case
1223 self = args[0]
1224 if "i386" == self.getArchitecture():
1225 self.skipTest("skipping because i386 is not a supported architecture")
1226 else:
1227 func(*args, **kwargs)
1228 return wrapper
1229
Pavel Labath090152b2015-08-20 11:37:19 +00001230def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001231 """Decorator to skip tests when the target is Android.
1232
1233 Arguments:
1234 api_levels - The API levels for which the test should be skipped. If
1235 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001236 arch - A sequence of architecture names specifying the architectures
1237 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001238 """
1239 def myImpl(func):
1240 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1241 raise Exception("@skipIfTargetAndroid can only be used to "
1242 "decorate a test method")
1243 @wraps(func)
1244 def wrapper(*args, **kwargs):
1245 from unittest2 import case
1246 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001247 if matchAndroid(api_levels, archs)(self):
1248 self.skipTest("skiped on Android target with API %d and architecture %s" %
1249 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001250 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001251 return wrapper
1252 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001253
Ilia Kd9953052015-03-12 07:19:41 +00001254def skipUnlessCompilerRt(func):
1255 """Decorate the item to skip tests if testing remotely."""
1256 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1257 raise Exception("@skipUnless can only be used to decorate a test method")
1258 @wraps(func)
1259 def wrapper(*args, **kwargs):
1260 from unittest2 import case
1261 import os.path
Enrico Granata55d99f02015-11-19 21:45:07 +00001262 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "llvm","projects","compiler-rt")
1263 print(compilerRtPath)
Ilia Kd9953052015-03-12 07:19:41 +00001264 if not os.path.exists(compilerRtPath):
1265 self = args[0]
1266 self.skipTest("skip if compiler-rt not found")
1267 else:
1268 func(*args, **kwargs)
1269 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001270
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001271class _PlatformContext(object):
1272 """Value object class which contains platform-specific options."""
1273
1274 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1275 self.shlib_environment_var = shlib_environment_var
1276 self.shlib_prefix = shlib_prefix
1277 self.shlib_extension = shlib_extension
1278
1279
Johnny Chena74bb0a2011-08-01 18:46:13 +00001280class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001281 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001282 Abstract base for performing lldb (see TestBase) or other generic tests (see
1283 BenchBase for one example). lldbtest.Base works with the test driver to
1284 accomplish things.
1285
Johnny Chen8334dad2010-10-22 23:15:46 +00001286 """
Enrico Granata5020f952012-10-24 21:42:49 +00001287
Enrico Granata19186272012-10-24 21:44:48 +00001288 # The concrete subclass should override this attribute.
1289 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001290
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001291 # Keep track of the old current working directory.
1292 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001293
Greg Clayton4570d3e2013-12-10 23:19:29 +00001294 @staticmethod
1295 def compute_mydir(test_file):
1296 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1297
1298 mydir = TestBase.compute_mydir(__file__)'''
1299 test_dir = os.path.dirname(test_file)
1300 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1301
Johnny Chenfb4264c2011-08-01 19:50:58 +00001302 def TraceOn(self):
1303 """Returns True if we are in trace mode (tracing detailed test execution)."""
1304 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001305
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001306 @classmethod
1307 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001308 """
1309 Python unittest framework class setup fixture.
1310 Do current directory manipulation.
1311 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001312 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001313 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001314 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001315
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001316 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001317 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001318
1319 # Change current working directory if ${LLDB_TEST} is defined.
1320 # See also dotest.py which sets up ${LLDB_TEST}.
1321 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001322 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001323 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001324 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001325 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1326
Vince Harron85d19652015-05-21 19:09:29 +00001327 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001328 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001329 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1330 try:
1331 cls.dir_lock.try_acquire()
1332 # write the class that owns the lock into the lock file
1333 cls.dir_lock.handle.write(cls.__name__)
1334 except IOError as ioerror:
1335 # nothing else should have this directory lock
1336 # wait here until we get a lock
1337 cls.dir_lock.acquire()
1338 # read the previous owner from the lock file
1339 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001340 print("LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format(cls.__name__, full_dir, lock_id), file=sys.stderr)
Vince Harron85d19652015-05-21 19:09:29 +00001341 raise ioerror
1342
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001343 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001344 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001345 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00001346 elif getPlatform() in ("freebsd", "linux", "netbsd"):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001347 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001348 else:
1349 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001350
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001351 @classmethod
1352 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001353 """
1354 Python unittest framework class teardown fixture.
1355 Do class-wide cleanup.
1356 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001357
Zachary Turner742afdb2015-12-11 19:21:49 +00001358 if doCleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001359 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001360 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001361 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001362
Johnny Chen707b3c92010-10-11 22:25:46 +00001363 # Subclass might have specific cleanup function defined.
1364 if getattr(cls, "classCleanup", None):
1365 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001366 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001367 try:
1368 cls.classCleanup()
1369 except:
1370 exc_type, exc_value, exc_tb = sys.exc_info()
1371 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001372
Vince Harron85d19652015-05-21 19:09:29 +00001373 if debug_confirm_directory_exclusivity:
1374 cls.dir_lock.release()
1375 del cls.dir_lock
1376
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001377 # Restore old working directory.
1378 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001379 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001380 os.chdir(cls.oldcwd)
1381
Johnny Chena74bb0a2011-08-01 18:46:13 +00001382 @classmethod
1383 def skipLongRunningTest(cls):
1384 """
1385 By default, we skip long running test case.
1386 This can be overridden by passing '-l' to the test driver (dotest.py).
1387 """
1388 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1389 return False
1390 else:
1391 return True
Johnny Chened492022011-06-21 00:53:00 +00001392
Vince Harron6d3d0f12015-05-10 22:01:59 +00001393 def enableLogChannelsForCurrentTest(self):
1394 if len(lldbtest_config.channels) == 0:
1395 return
1396
1397 # if debug channels are specified in lldbtest_config.channels,
1398 # create a new set of log files for every test
1399 log_basename = self.getLogBasenameForCurrentTest()
1400
1401 # confirm that the file is writeable
1402 host_log_path = "{}-host.log".format(log_basename)
1403 open(host_log_path, 'w').close()
1404
1405 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1406 for channel_with_categories in lldbtest_config.channels:
1407 channel_then_categories = channel_with_categories.split(' ', 1)
1408 channel = channel_then_categories[0]
1409 if len(channel_then_categories) > 1:
1410 categories = channel_then_categories[1]
1411 else:
1412 categories = "default"
1413
1414 if channel == "gdb-remote":
1415 # communicate gdb-remote categories to debugserver
1416 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1417
1418 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1419 if not self.res.Succeeded():
1420 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1421
1422 # Communicate log path name to debugserver & lldb-server
1423 server_log_path = "{}-server.log".format(log_basename)
1424 open(server_log_path, 'w').close()
1425 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1426
1427 # Communicate channels to lldb-server
1428 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1429
1430 if len(lldbtest_config.channels) == 0:
1431 return
1432
1433 def disableLogChannelsForCurrentTest(self):
1434 # close all log files that we opened
1435 for channel_and_categories in lldbtest_config.channels:
1436 # channel format - <channel-name> [<category0> [<category1> ...]]
1437 channel = channel_and_categories.split(' ', 1)[0]
1438 self.ci.HandleCommand("log disable " + channel, self.res)
1439 if not self.res.Succeeded():
1440 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1441
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001442 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001443 """Fixture for unittest test case setup.
1444
1445 It works with the test driver to conditionally skip tests and does other
1446 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001447 #import traceback
1448 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001449
Daniel Malea9115f072013-08-06 15:02:32 +00001450 if "LIBCXX_PATH" in os.environ:
1451 self.libcxxPath = os.environ["LIBCXX_PATH"]
1452 else:
1453 self.libcxxPath = None
1454
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001455 if "LLDBMI_EXEC" in os.environ:
1456 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1457 else:
1458 self.lldbMiExec = None
Vince Harron790d95c2015-05-18 19:39:03 +00001459
Johnny Chenebe51722011-10-07 19:21:09 +00001460 # If we spawn an lldb process for test (via pexpect), do not load the
1461 # init file unless told otherwise.
1462 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1463 self.lldbOption = ""
1464 else:
1465 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001466
Johnny Chen985e7402011-08-01 21:13:26 +00001467 # Assign the test method name to self.testMethodName.
1468 #
1469 # For an example of the use of this attribute, look at test/types dir.
1470 # There are a bunch of test cases under test/types and we don't want the
1471 # module cacheing subsystem to be confused with executable name "a.out"
1472 # used for all the test cases.
1473 self.testMethodName = self._testMethodName
1474
Johnny Chen985e7402011-08-01 21:13:26 +00001475 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1476 # with it using pexpect.
1477 self.child = None
1478 self.child_prompt = "(lldb) "
1479 # If the child is interacting with the embedded script interpreter,
1480 # there are two exits required during tear down, first to quit the
1481 # embedded script interpreter and second to quit the lldb command
1482 # interpreter.
1483 self.child_in_script_interpreter = False
1484
Johnny Chenfb4264c2011-08-01 19:50:58 +00001485 # These are for customized teardown cleanup.
1486 self.dict = None
1487 self.doTearDownCleanup = False
1488 # And in rare cases where there are multiple teardown cleanups.
1489 self.dicts = []
1490 self.doTearDownCleanups = False
1491
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001492 # List of spawned subproces.Popen objects
1493 self.subprocesses = []
1494
Daniel Malea69207462013-06-05 21:07:02 +00001495 # List of forked process PIDs
1496 self.forkedProcessPids = []
1497
Johnny Chenfb4264c2011-08-01 19:50:58 +00001498 # Create a string buffer to record the session info, to be dumped into a
1499 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001500 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001501
Vince Harron1f160372015-05-21 18:51:20 +00001502 session_file = "{}.log".format(self.log_basename)
Zachary Turner8d13fab2015-11-07 01:08:15 +00001503 # Python 3 doesn't support unbuffered I/O in text mode. Open buffered.
1504 self.session = open(session_file, "w")
Johnny Chenfb4264c2011-08-01 19:50:58 +00001505
1506 # Optimistically set __errored__, __failed__, __expected__ to False
1507 # initially. If the test errored/failed, the session info
1508 # (self.session) is then dumped into a session specific file for
1509 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001510 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001511 self.__errored__ = False
1512 self.__failed__ = False
1513 self.__expected__ = False
1514 # We are also interested in unexpected success.
1515 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001516 # And skipped tests.
1517 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001518
1519 # See addTearDownHook(self, hook) which allows the client to add a hook
1520 # function to be run during tearDown() time.
1521 self.hooks = []
1522
1523 # See HideStdout(self).
1524 self.sys_stdout_hidden = False
1525
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001526 if self.platformContext:
1527 # set environment variable names for finding shared libraries
1528 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001529
Vince Harron6d3d0f12015-05-10 22:01:59 +00001530 # Create the debugger instance if necessary.
1531 try:
1532 self.dbg = lldb.DBG
1533 except AttributeError:
1534 self.dbg = lldb.SBDebugger.Create()
1535
1536 if not self.dbg:
1537 raise Exception('Invalid debugger instance')
1538
1539 # Retrieve the associated command interpreter instance.
1540 self.ci = self.dbg.GetCommandInterpreter()
1541 if not self.ci:
1542 raise Exception('Could not get the command interpreter')
1543
1544 # And the result object.
1545 self.res = lldb.SBCommandReturnObject()
1546
1547 self.enableLogChannelsForCurrentTest()
1548
Ying Chen0c352822015-11-16 23:41:02 +00001549 #Initialize debug_info
1550 self.debug_info = None
1551
Daniel Malea249287a2013-02-19 16:08:57 +00001552 def setAsync(self, value):
1553 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1554 old_async = self.dbg.GetAsync()
1555 self.dbg.SetAsync(value)
1556 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1557
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001558 def cleanupSubprocesses(self):
1559 # Ensure any subprocesses are cleaned up
1560 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001561 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001562 del p
1563 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001564 # Ensure any forked processes are cleaned up
1565 for pid in self.forkedProcessPids:
1566 if os.path.exists("/proc/" + str(pid)):
1567 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001568
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001569 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001570 """ Creates a subprocess.Popen object with the specified executable and arguments,
1571 saves it in self.subprocesses, and returns the object.
1572 NOTE: if using this function, ensure you also call:
1573
1574 self.addTearDownHook(self.cleanupSubprocesses)
1575
1576 otherwise the test suite will leak processes.
1577 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001578 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001579 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001580 self.subprocesses.append(proc)
1581 return proc
1582
Daniel Malea69207462013-06-05 21:07:02 +00001583 def forkSubprocess(self, executable, args=[]):
1584 """ Fork a subprocess with its own group ID.
1585 NOTE: if using this function, ensure you also call:
1586
1587 self.addTearDownHook(self.cleanupSubprocesses)
1588
1589 otherwise the test suite will leak processes.
1590 """
1591 child_pid = os.fork()
1592 if child_pid == 0:
1593 # If more I/O support is required, this can be beefed up.
1594 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001595 os.dup2(fd, 1)
1596 os.dup2(fd, 2)
1597 # This call causes the child to have its of group ID
1598 os.setpgid(0,0)
1599 os.execvp(executable, [executable] + args)
1600 # Give the child time to get through the execvp() call
1601 time.sleep(0.1)
1602 self.forkedProcessPids.append(child_pid)
1603 return child_pid
1604
Johnny Chenfb4264c2011-08-01 19:50:58 +00001605 def HideStdout(self):
1606 """Hide output to stdout from the user.
1607
1608 During test execution, there might be cases where we don't want to show the
1609 standard output to the user. For example,
1610
Zachary Turner35d017f2015-10-23 17:04:29 +00001611 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001612
1613 tests whether command abbreviation for 'script' works or not. There is no
1614 need to show the 'Hello' output to the user as long as the 'script' command
1615 succeeds and we are not in TraceOn() mode (see the '-t' option).
1616
1617 In this case, the test method calls self.HideStdout(self) to redirect the
1618 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1619
1620 Note that you should only call this method at most once during a test case
1621 execution. Any subsequent call has no effect at all."""
1622 if self.sys_stdout_hidden:
1623 return
1624
1625 self.sys_stdout_hidden = True
1626 old_stdout = sys.stdout
1627 sys.stdout = open(os.devnull, 'w')
1628 def restore_stdout():
1629 sys.stdout = old_stdout
1630 self.addTearDownHook(restore_stdout)
1631
1632 # =======================================================================
1633 # Methods for customized teardown cleanups as well as execution of hooks.
1634 # =======================================================================
1635
1636 def setTearDownCleanup(self, dictionary=None):
1637 """Register a cleanup action at tearDown() time with a dictinary"""
1638 self.dict = dictionary
1639 self.doTearDownCleanup = True
1640
1641 def addTearDownCleanup(self, dictionary):
1642 """Add a cleanup action at tearDown() time with a dictinary"""
1643 self.dicts.append(dictionary)
1644 self.doTearDownCleanups = True
1645
1646 def addTearDownHook(self, hook):
1647 """
1648 Add a function to be run during tearDown() time.
1649
1650 Hooks are executed in a first come first serve manner.
1651 """
Zachary Turnercd236b82015-10-26 18:48:24 +00001652 if six.callable(hook):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001653 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001654 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001655 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001656
1657 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001658
Jim Inghamda3a3862014-10-16 23:02:14 +00001659 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001660 # This is for the case of directly spawning 'lldb' and interacting with it
1661 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001662 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001663 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001664 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001665 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001666 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001667 if self.child_in_script_interpreter:
1668 self.child.sendline('quit()')
1669 self.child.expect_exact(self.child_prompt)
1670 self.child.sendline('settings set interpreter.prompt-on-quit false')
1671 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001672 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001673 except (ValueError, pexpect.ExceptionPexpect):
1674 # child is already terminated
1675 pass
1676 except OSError as exception:
1677 import errno
1678 if exception.errno != errno.EIO:
1679 # unexpected error
1680 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001681 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001682 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001683 finally:
1684 # Give it one final blow to make sure the child is terminated.
1685 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001686
1687 def tearDown(self):
1688 """Fixture for unittest test case teardown."""
1689 #import traceback
1690 #traceback.print_stack()
1691
1692 self.deletePexpectChild()
1693
Johnny Chenfb4264c2011-08-01 19:50:58 +00001694 # Check and run any hook functions.
1695 for hook in reversed(self.hooks):
1696 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001697 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001698 import inspect
1699 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001700 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001701 hook()
1702 elif hook_argc == 1:
1703 hook(self)
1704 else:
1705 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001706
1707 del self.hooks
1708
1709 # Perform registered teardown cleanup.
1710 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001711 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001712
1713 # In rare cases where there are multiple teardown cleanups added.
1714 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001715 if self.dicts:
1716 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001717 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001718
Vince Harron9753dd92015-05-10 15:22:09 +00001719 self.disableLogChannelsForCurrentTest()
1720
Johnny Chenfb4264c2011-08-01 19:50:58 +00001721 # =========================================================
1722 # Various callbacks to allow introspection of test progress
1723 # =========================================================
1724
1725 def markError(self):
1726 """Callback invoked when an error (unexpected exception) errored."""
1727 self.__errored__ = True
1728 with recording(self, False) as sbuf:
1729 # False because there's no need to write "ERROR" to the stderr twice.
1730 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001731 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001732
Zachary Turnerb1490b62015-08-26 19:44:56 +00001733 def markCleanupError(self):
1734 """Callback invoked when an error occurs while a test is cleaning up."""
1735 self.__cleanup_errored__ = True
1736 with recording(self, False) as sbuf:
1737 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1738 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001739 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001740
Johnny Chenfb4264c2011-08-01 19:50:58 +00001741 def markFailure(self):
1742 """Callback invoked when a failure (test assertion failure) occurred."""
1743 self.__failed__ = True
1744 with recording(self, False) as sbuf:
1745 # False because there's no need to write "FAIL" to the stderr twice.
1746 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001747 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001748
Enrico Granatae6cedc12013-02-23 01:05:23 +00001749 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001750 """Callback invoked when an expected failure/error occurred."""
1751 self.__expected__ = True
1752 with recording(self, False) as sbuf:
1753 # False because there's no need to write "expected failure" to the
1754 # stderr twice.
1755 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001756 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001757 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001758 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001759 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001760
Johnny Chenc5cc6252011-08-15 23:09:08 +00001761 def markSkippedTest(self):
1762 """Callback invoked when a test is skipped."""
1763 self.__skipped__ = True
1764 with recording(self, False) as sbuf:
1765 # False because there's no need to write "skipped test" to the
1766 # stderr twice.
1767 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001768 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001769
Enrico Granatae6cedc12013-02-23 01:05:23 +00001770 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001771 """Callback invoked when an unexpected success occurred."""
1772 self.__unexpected__ = True
1773 with recording(self, False) as sbuf:
1774 # False because there's no need to write "unexpected success" to the
1775 # stderr twice.
1776 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001777 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001778 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001779 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001780 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001781
Greg Clayton70995582015-01-07 22:25:50 +00001782 def getRerunArgs(self):
1783 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001784
1785 def getLogBasenameForCurrentTest(self, prefix=None):
1786 """
1787 returns a partial path that can be used as the beginning of the name of multiple
1788 log files pertaining to this test
1789
1790 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1791 """
1792 dname = os.path.join(os.environ["LLDB_TEST"],
1793 os.environ["LLDB_SESSION_DIRNAME"])
1794 if not os.path.isdir(dname):
1795 os.mkdir(dname)
1796
1797 compiler = self.getCompiler()
1798
1799 if compiler[1] == ':':
1800 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001801 if os.path.altsep is not None:
1802 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001803
Vince Harron19e300f2015-05-12 00:50:54 +00001804 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001805 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001806 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001807
1808 if prefix is not None:
1809 fname = "{}-{}".format(prefix, fname)
1810
1811 return os.path.join(dname, fname)
1812
Johnny Chenfb4264c2011-08-01 19:50:58 +00001813 def dumpSessionInfo(self):
1814 """
1815 Dump the debugger interactions leading to a test error/failure. This
1816 allows for more convenient postmortem analysis.
1817
1818 See also LLDBTestResult (dotest.py) which is a singlton class derived
1819 from TextTestResult and overwrites addError, addFailure, and
1820 addExpectedFailure methods to allow us to to mark the test instance as
1821 such.
1822 """
1823
1824 # We are here because self.tearDown() detected that this test instance
1825 # either errored or failed. The lldb.test_result singleton contains
1826 # two lists (erros and failures) which get populated by the unittest
1827 # framework. Look over there for stack trace information.
1828 #
1829 # The lists contain 2-tuples of TestCase instances and strings holding
1830 # formatted tracebacks.
1831 #
1832 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001833
Vince Harron35b17dc2015-05-21 18:20:21 +00001834 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001835 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001836 if self.__errored__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001837 pairs = configuration.test_result.errors
Johnny Chenfb4264c2011-08-01 19:50:58 +00001838 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001839 elif self.__cleanup_errored__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001840 pairs = configuration.test_result.cleanup_errors
Zachary Turnerb1490b62015-08-26 19:44:56 +00001841 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001842 elif self.__failed__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001843 pairs = configuration.test_result.failures
Johnny Chenfb4264c2011-08-01 19:50:58 +00001844 prefix = 'Failure'
1845 elif self.__expected__:
Zachary Turner606e3a52015-12-08 01:15:30 +00001846 pairs = configuration.test_result.expectedFailures
Johnny Chenfb4264c2011-08-01 19:50:58 +00001847 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001848 elif self.__skipped__:
1849 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001850 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001851 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001852 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001853 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001854
Johnny Chenc5cc6252011-08-15 23:09:08 +00001855 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001856 for test, traceback in pairs:
1857 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001858 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001859
Vince Harron35b17dc2015-05-21 18:20:21 +00001860 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001861 testMethod = getattr(self, self._testMethodName)
1862 if getattr(testMethod, "__benchmarks_test__", False):
1863 benchmarks = True
1864 else:
1865 benchmarks = False
1866
Vince Harron35b17dc2015-05-21 18:20:21 +00001867 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001868 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1869 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1870 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001871 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001872 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001873 self.session.close()
1874 del self.session
1875
1876 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001877 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001878
1879 if prefix != 'Success' or lldbtest_config.log_success:
1880 # keep all log files, rename them to include prefix
1881 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1882 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001883 if os.path.isfile(src):
1884 dst = src.replace(self.log_basename, dst_log_basename)
1885 if os.name == "nt" and os.path.isfile(dst):
1886 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1887 # it silently replaces the destination. Ultimately this means that atomic renames are not
1888 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1889 # destination first if it already exists.
1890 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001891
Zachary Turner306278f2015-05-26 20:26:29 +00001892 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001893 else:
1894 # success! (and we don't want log files) delete log files
1895 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001896 try:
1897 os.unlink(log_file)
1898 except:
1899 # We've seen consistent unlink failures on Windows, perhaps because the
1900 # just-created log file is being scanned by anti-virus. Empirically, this
1901 # sleep-and-retry approach allows tests to succeed much more reliably.
1902 # Attempts to figure out exactly what process was still holding a file handle
1903 # have failed because running instrumentation like Process Monitor seems to
1904 # slow things down enough that the problem becomes much less consistent.
1905 time.sleep(0.5)
1906 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001907
1908 # ====================================================
1909 # Config. methods supported through a plugin interface
1910 # (enables reading of the current test configuration)
1911 # ====================================================
1912
1913 def getArchitecture(self):
1914 """Returns the architecture in effect the test suite is running with."""
1915 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001916 arch = module.getArchitecture()
1917 if arch == 'amd64':
1918 arch = 'x86_64'
1919 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001920
Vince Harron02613762015-05-04 00:17:53 +00001921 def getLldbArchitecture(self):
1922 """Returns the architecture of the lldb binary."""
1923 if not hasattr(self, 'lldbArchitecture'):
1924
1925 # spawn local process
1926 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001927 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001928 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001929 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001930 "-o",
1931 "quit"
1932 ]
1933
1934 output = check_output(command)
1935 str = output.decode("utf-8");
1936
1937 for line in str.splitlines():
1938 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1939 if m:
1940 self.lldbArchitecture = m.group(1)
1941 break
1942
1943 return self.lldbArchitecture
1944
Johnny Chenfb4264c2011-08-01 19:50:58 +00001945 def getCompiler(self):
1946 """Returns the compiler in effect the test suite is running with."""
1947 module = builder_module()
1948 return module.getCompiler()
1949
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001950 def getCompilerBinary(self):
1951 """Returns the compiler binary the test suite is running with."""
1952 return self.getCompiler().split()[0]
1953
Daniel Malea0aea0162013-02-27 17:29:46 +00001954 def getCompilerVersion(self):
1955 """ Returns a string that represents the compiler version.
1956 Supports: llvm, clang.
1957 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00001958 from .lldbutil import which
Daniel Malea0aea0162013-02-27 17:29:46 +00001959 version = 'unknown'
1960
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001961 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001962 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001963 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001964 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001965 if m:
1966 version = m.group(1)
1967 return version
1968
Ryan Brown57bee1e2015-09-14 22:45:11 +00001969 def getGoCompilerVersion(self):
1970 """ Returns a string that represents the go compiler version, or None if go is not found.
1971 """
1972 compiler = which("go")
1973 if compiler:
1974 version_output = system([[compiler, "version"]])[0]
1975 for line in version_output.split(os.linesep):
1976 m = re.search('go version (devel|go\\S+)', line)
1977 if m:
1978 return m.group(1)
1979 return None
1980
Greg Claytone0d0a762015-04-02 18:24:03 +00001981 def platformIsDarwin(self):
1982 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00001983 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00001984
Robert Flack13c7ad92015-03-30 14:12:17 +00001985 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00001986 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001987 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00001988
Daniel Maleaadaaec92013-08-06 20:51:41 +00001989 def isIntelCompiler(self):
1990 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1991 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1992
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001993 def expectedCompilerVersion(self, compiler_version):
1994 """Returns True iff compiler_version[1] matches the current compiler version.
1995 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1996 Any operator other than the following defaults to an equality test:
1997 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1998 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001999 if (compiler_version == None):
2000 return True
2001 operator = str(compiler_version[0])
2002 version = compiler_version[1]
2003
2004 if (version == None):
2005 return True
2006 if (operator == '>'):
2007 return self.getCompilerVersion() > version
2008 if (operator == '>=' or operator == '=>'):
2009 return self.getCompilerVersion() >= version
2010 if (operator == '<'):
2011 return self.getCompilerVersion() < version
2012 if (operator == '<=' or operator == '=<'):
2013 return self.getCompilerVersion() <= version
2014 if (operator == '!=' or operator == '!' or operator == 'not'):
2015 return str(version) not in str(self.getCompilerVersion())
2016 return str(version) in str(self.getCompilerVersion())
2017
2018 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002019 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002020 if (compilers == None):
2021 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00002022
2023 for compiler in compilers:
2024 if compiler in self.getCompiler():
2025 return True
2026
2027 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002028
Ying Chen7091c2c2015-04-21 01:15:47 +00002029 def expectedArch(self, archs):
2030 """Returns True iff any element of archs is a sub-string of the current architecture."""
2031 if (archs == None):
2032 return True
2033
2034 for arch in archs:
2035 if arch in self.getArchitecture():
2036 return True
2037
2038 return False
2039
Johnny Chenfb4264c2011-08-01 19:50:58 +00002040 def getRunOptions(self):
2041 """Command line option for -A and -C to run this test again, called from
2042 self.dumpSessionInfo()."""
2043 arch = self.getArchitecture()
2044 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00002045 if arch:
2046 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00002047 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00002048 option_str = ""
2049 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00002050 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00002051 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00002052
2053 # ==================================================
2054 # Build methods supported through a plugin interface
2055 # ==================================================
2056
Ed Mastec97323e2014-04-01 18:47:58 +00002057 def getstdlibFlag(self):
2058 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00002059 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00002060 stdlibflag = "-stdlib=libc++"
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002061 else: # this includes NetBSD
Ed Mastec97323e2014-04-01 18:47:58 +00002062 stdlibflag = ""
2063 return stdlibflag
2064
Matt Kopec7663b3a2013-09-25 17:44:00 +00002065 def getstdFlag(self):
2066 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002067 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002068 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002069 else:
2070 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002071 return stdflag
2072
2073 def buildDriver(self, sources, exe_name):
2074 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2075 or LLDB.framework).
2076 """
2077
2078 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002079 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002080
2081 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002082 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002083 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002084 d = {'CXX_SOURCES' : sources,
2085 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002086 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002087 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2088 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002089 }
Kamil Rytarowskif5d34b72015-12-10 22:56:56 +00002090 elif sys.platform.rstrip('0123456789') in ('freebsd', 'linux', 'netbsd') or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002091 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002092 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002093 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002094 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002095 elif sys.platform.startswith('win'):
2096 d = {'CXX_SOURCES' : sources,
2097 'EXE' : exe_name,
2098 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002099 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002100 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002101 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002102
2103 self.buildDefault(dictionary=d)
2104
Matt Kopec7663b3a2013-09-25 17:44:00 +00002105 def buildLibrary(self, sources, lib_name):
2106 """Platform specific way to build a default library. """
2107
2108 stdflag = self.getstdFlag()
2109
Greg Clayton22fd3b12015-10-26 17:52:16 +00002110 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002111 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002112 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002113 d = {'DYLIB_CXX_SOURCES' : sources,
2114 'DYLIB_NAME' : lib_name,
2115 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002116 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2117 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002118 }
Kamil Rytarowskif5d34b72015-12-10 22:56:56 +00002119 elif self.getPlatform() in ('freebsd', 'linux', 'netbsd') or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002120 d = {'DYLIB_CXX_SOURCES' : sources,
2121 'DYLIB_NAME' : lib_name,
2122 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002123 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002124 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002125 d = {'DYLIB_CXX_SOURCES' : sources,
2126 'DYLIB_NAME' : lib_name,
2127 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002128 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002129 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002130 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002131
2132 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002133
Daniel Malea55faa402013-05-02 21:44:31 +00002134 def buildProgram(self, sources, exe_name):
2135 """ Platform specific way to build an executable from C/C++ sources. """
2136 d = {'CXX_SOURCES' : sources,
2137 'EXE' : exe_name}
2138 self.buildDefault(dictionary=d)
2139
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002140 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002141 """Platform specific way to build the default binaries."""
2142 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002143 if target_is_android():
2144 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002145 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002146 raise Exception("Don't know how to build default binary")
2147
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002148 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002149 """Platform specific way to build binaries with dsym info."""
2150 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002151 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002152 raise Exception("Don't know how to build binary with dsym")
2153
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002154 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002155 """Platform specific way to build binaries with dwarf maps."""
2156 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002157 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002158 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002159 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002160 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002161
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002162 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2163 """Platform specific way to build binaries with dwarf maps."""
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002164 module = builder_module()
2165 if target_is_android():
2166 dictionary = append_android_envs(dictionary)
2167 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2168 raise Exception("Don't know how to build binary with dwo")
2169
Ryan Brown57bee1e2015-09-14 22:45:11 +00002170 def buildGo(self):
2171 """Build the default go binary.
2172 """
2173 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2174
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002175 def signBinary(self, binary_path):
2176 if sys.platform.startswith("darwin"):
2177 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2178 call(codesign_cmd, shell=True)
2179
Kuba Breckabeed8212014-09-04 01:03:18 +00002180 def findBuiltClang(self):
2181 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2182 paths_to_try = [
2183 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2184 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2185 "llvm-build/Release/x86_64/Release/bin/clang",
2186 "llvm-build/Debug/x86_64/Debug/bin/clang",
2187 ]
Enrico Granata55d99f02015-11-19 21:45:07 +00002188 lldb_root_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
Kuba Breckabeed8212014-09-04 01:03:18 +00002189 for p in paths_to_try:
2190 path = os.path.join(lldb_root_path, p)
2191 if os.path.exists(path):
2192 return path
Ilia Kd9953052015-03-12 07:19:41 +00002193
2194 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002195 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002196 if os.path.exists(path):
2197 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002198
2199 return os.environ["CC"]
2200
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002201 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002202 """ Returns a dictionary (which can be provided to build* functions above) which
2203 contains OS-specific build flags.
2204 """
2205 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002206 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002207
2208 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002209 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002210 use_libcxx = True
2211
2212 if use_libcxx and self.libcxxPath:
2213 cflags += "-stdlib=libc++ "
2214 if self.libcxxPath:
2215 libcxxInclude = os.path.join(self.libcxxPath, "include")
2216 libcxxLib = os.path.join(self.libcxxPath, "lib")
2217 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2218 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2219
Andrew Kaylor93132f52013-05-28 23:04:25 +00002220 if use_cpp11:
2221 cflags += "-std="
2222 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2223 cflags += "c++0x"
2224 else:
2225 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002226 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002227 cflags += " -stdlib=libc++"
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002228 elif self.getPlatform() == "netbsd":
2229 cflags += " -stdlib=libstdc++"
Andrew Kaylor93132f52013-05-28 23:04:25 +00002230 elif "clang" in self.getCompiler():
2231 cflags += " -stdlib=libstdc++"
2232
Andrew Kaylor93132f52013-05-28 23:04:25 +00002233 return {'CFLAGS_EXTRAS' : cflags,
2234 'LD_EXTRAS' : ldflags,
2235 }
2236
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002237 def cleanup(self, dictionary=None):
2238 """Platform specific way to do cleanup after build."""
2239 module = builder_module()
2240 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002241 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002242
Daniel Malea55faa402013-05-02 21:44:31 +00002243 def getLLDBLibraryEnvVal(self):
2244 """ Returns the path that the OS-specific library search environment variable
2245 (self.dylibPath) should be set to in order for a program to find the LLDB
2246 library. If an environment variable named self.dylibPath is already set,
2247 the new path is appended to it and returned.
2248 """
2249 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002250 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002251 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002252 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002253 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002254 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002255 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002256 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002257
Ed Maste437f8f62013-09-09 14:04:04 +00002258 def getLibcPlusPlusLibs(self):
Kamil Rytarowski49f9fb82015-12-07 21:25:57 +00002259 if self.getPlatform() in ('freebsd', 'linux', 'netbsd'):
Ed Maste437f8f62013-09-09 14:04:04 +00002260 return ['libc++.so.1']
2261 else:
2262 return ['libc++.1.dylib','libc++abi.dylib']
2263
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002264# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2265# We change the test methods to create a new test method for each test for each debug info we are
2266# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2267# the new test method we remove the old method at the same time.
2268class LLDBTestCaseFactory(type):
2269 def __new__(cls, name, bases, attrs):
2270 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002271 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002272 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2273 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002274 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002275 def dsym_test_method(self, attrvalue=attrvalue):
2276 self.debug_info = "dsym"
2277 return attrvalue(self)
2278 dsym_method_name = attrname + "_dsym"
2279 dsym_test_method.__name__ = dsym_method_name
2280 newattrs[dsym_method_name] = dsym_test_method
2281
2282 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002283 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002284 def dwarf_test_method(self, attrvalue=attrvalue):
2285 self.debug_info = "dwarf"
2286 return attrvalue(self)
2287 dwarf_method_name = attrname + "_dwarf"
2288 dwarf_test_method.__name__ = dwarf_method_name
2289 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002290
2291 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002292 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002293 def dwo_test_method(self, attrvalue=attrvalue):
2294 self.debug_info = "dwo"
2295 return attrvalue(self)
2296 dwo_method_name = attrname + "_dwo"
2297 dwo_test_method.__name__ = dwo_method_name
2298 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002299 else:
2300 newattrs[attrname] = attrvalue
2301 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2302
Zachary Turner43a01e42015-10-20 21:06:05 +00002303# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2304@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002305class TestBase(Base):
2306 """
2307 This abstract base class is meant to be subclassed. It provides default
2308 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2309 among other things.
2310
2311 Important things for test class writers:
2312
2313 - Overwrite the mydir class attribute, otherwise your test class won't
2314 run. It specifies the relative directory to the top level 'test' so
2315 the test harness can change to the correct working directory before
2316 running your test.
2317
2318 - The setUp method sets up things to facilitate subsequent interactions
2319 with the debugger as part of the test. These include:
2320 - populate the test method name
2321 - create/get a debugger set with synchronous mode (self.dbg)
2322 - get the command interpreter from with the debugger (self.ci)
2323 - create a result object for use with the command interpreter
2324 (self.res)
2325 - plus other stuffs
2326
2327 - The tearDown method tries to perform some necessary cleanup on behalf
2328 of the test to return the debugger to a good state for the next test.
2329 These include:
2330 - execute any tearDown hooks registered by the test method with
2331 TestBase.addTearDownHook(); examples can be found in
2332 settings/TestSettings.py
2333 - kill the inferior process associated with each target, if any,
2334 and, then delete the target from the debugger's target list
2335 - perform build cleanup before running the next test method in the
2336 same test class; examples of registering for this service can be
2337 found in types/TestIntegerTypes.py with the call:
2338 - self.setTearDownCleanup(dictionary=d)
2339
2340 - Similarly setUpClass and tearDownClass perform classwise setup and
2341 teardown fixtures. The tearDownClass method invokes a default build
2342 cleanup for the entire test class; also, subclasses can implement the
2343 classmethod classCleanup(cls) to perform special class cleanup action.
2344
2345 - The instance methods runCmd and expect are used heavily by existing
2346 test cases to send a command to the command interpreter and to perform
2347 string/pattern matching on the output of such command execution. The
2348 expect method also provides a mode to peform string/pattern matching
2349 without running a command.
2350
2351 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2352 build the binaries used during a particular test scenario. A plugin
2353 should be provided for the sys.platform running the test suite. The
2354 Mac OS X implementation is located in plugins/darwin.py.
2355 """
2356
2357 # Maximum allowed attempts when launching the inferior process.
2358 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2359 maxLaunchCount = 3;
2360
2361 # Time to wait before the next launching attempt in second(s).
2362 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2363 timeWaitNextLaunch = 1.0;
2364
Enrico Granata165f8af2012-09-21 19:10:53 +00002365 # Returns the list of categories to which this test case belongs
2366 # by default, look for a ".categories" file, and read its contents
2367 # if no such file exists, traverse the hierarchy - we guarantee
2368 # a .categories to exist at the top level directory so we do not end up
2369 # looping endlessly - subclasses are free to define their own categories
2370 # in whatever way makes sense to them
2371 def getCategories(self):
2372 import inspect
2373 import os.path
2374 folder = inspect.getfile(self.__class__)
2375 folder = os.path.dirname(folder)
2376 while folder != '/':
2377 categories_file_name = os.path.join(folder,".categories")
2378 if os.path.exists(categories_file_name):
2379 categories_file = open(categories_file_name,'r')
2380 categories = categories_file.readline()
2381 categories_file.close()
2382 categories = str.replace(categories,'\n','')
2383 categories = str.replace(categories,'\r','')
2384 return categories.split(',')
2385 else:
2386 folder = os.path.dirname(folder)
2387 continue
2388
Johnny Chena74bb0a2011-08-01 18:46:13 +00002389 def setUp(self):
2390 #import traceback
2391 #traceback.print_stack()
2392
2393 # Works with the test driver to conditionally skip tests via decorators.
2394 Base.setUp(self)
2395
Johnny Chenf2b70232010-08-25 18:49:48 +00002396 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2397 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2398
Johnny Chen430eb762010-10-19 16:00:42 +00002399 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002400 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002401
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002402 # We want our debugger to be synchronous.
2403 self.dbg.SetAsync(False)
2404
2405 # Retrieve the associated command interpreter instance.
2406 self.ci = self.dbg.GetCommandInterpreter()
2407 if not self.ci:
2408 raise Exception('Could not get the command interpreter')
2409
2410 # And the result object.
2411 self.res = lldb.SBCommandReturnObject()
2412
Zachary Turner606e3a52015-12-08 01:15:30 +00002413 if lldb.remote_platform and configuration.lldb_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002414 remote_test_dir = lldbutil.join_remote_paths(
Zachary Turner606e3a52015-12-08 01:15:30 +00002415 configuration.lldb_platform_working_dir,
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002416 self.getArchitecture(),
2417 str(self.test_number),
2418 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002419 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002420 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002421 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002422
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002423 # This function removes all files from the current working directory while leaving
2424 # the directories in place. The cleaup is required to reduce the disk space required
2425 # by the test suit while leaving the directories untached is neccessary because
2426 # sub-directories might belong to an other test
2427 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002428 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002429 # TODO: Replace the heuristic to remove the files with a logic what collects the
2430 # list of files we have to remove during test runs.
2431 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002432 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002433 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002434 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002435 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002436
Greg Clayton35c91342014-11-17 18:40:27 +00002437 def registerSharedLibrariesWithTarget(self, target, shlibs):
2438 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2439
2440 Any modules in the target that have their remote install file specification set will
2441 get uploaded to the remote host. This function registers the local copies of the
2442 shared libraries with the target and sets their remote install locations so they will
2443 be uploaded when the target is run.
2444 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002445 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002446 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002447
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002448 shlib_environment_var = self.platformContext.shlib_environment_var
2449 shlib_prefix = self.platformContext.shlib_prefix
2450 shlib_extension = '.' + self.platformContext.shlib_extension
2451
2452 working_dir = self.get_process_working_directory()
2453 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2454 # Add any shared libraries to our target if remote so they get
2455 # uploaded into the working directory on the remote side
2456 for name in shlibs:
2457 # The path can be a full path to a shared library, or a make file name like "Foo" for
2458 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2459 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2460 # of the shared library accordingly
2461 if os.path.exists(name):
2462 local_shlib_path = name # name is the full path to the local shared library
2463 else:
2464 # Check relative names
2465 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2466 if not os.path.exists(local_shlib_path):
2467 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002468 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002469 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002470
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002471 # Make sure we found the local shared library in the above code
2472 self.assertTrue(os.path.exists(local_shlib_path))
2473
2474 # Add the shared library to our target
2475 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2476 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002477 # We must set the remote install location if we want the shared library
2478 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002479 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002480 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002481
2482 return environment
2483
Enrico Granata44818162012-10-24 01:23:57 +00002484 # utility methods that tests can use to access the current objects
2485 def target(self):
2486 if not self.dbg:
2487 raise Exception('Invalid debugger instance')
2488 return self.dbg.GetSelectedTarget()
2489
2490 def process(self):
2491 if not self.dbg:
2492 raise Exception('Invalid debugger instance')
2493 return self.dbg.GetSelectedTarget().GetProcess()
2494
2495 def thread(self):
2496 if not self.dbg:
2497 raise Exception('Invalid debugger instance')
2498 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2499
2500 def frame(self):
2501 if not self.dbg:
2502 raise Exception('Invalid debugger instance')
2503 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2504
Greg Claytonc6947512013-12-13 19:18:59 +00002505 def get_process_working_directory(self):
2506 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2507 if lldb.remote_platform:
2508 # Remote tests set the platform working directory up in TestBase.setUp()
2509 return lldb.remote_platform.GetWorkingDirectory()
2510 else:
2511 # local tests change directory into each test subdirectory
2512 return os.getcwd()
2513
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002514 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002515 #import traceback
2516 #traceback.print_stack()
2517
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002518 # Ensure all the references to SB objects have gone away so that we can
2519 # be sure that all test-specific resources have been freed before we
2520 # attempt to delete the targets.
2521 gc.collect()
2522
Johnny Chen3794ad92011-06-15 21:24:24 +00002523 # Delete the target(s) from the debugger as a general cleanup step.
2524 # This includes terminating the process for each target, if any.
2525 # We'd like to reuse the debugger for our next test without incurring
2526 # the initialization overhead.
2527 targets = []
2528 for target in self.dbg:
2529 if target:
2530 targets.append(target)
2531 process = target.GetProcess()
2532 if process:
2533 rc = self.invoke(process, "Kill")
2534 self.assertTrue(rc.Success(), PROCESS_KILLED)
2535 for target in targets:
2536 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002537
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002538 # Do this last, to make sure it's in reverse order from how we setup.
2539 Base.tearDown(self)
2540
Zachary Turner95812042015-03-26 18:54:21 +00002541 # This must be the last statement, otherwise teardown hooks or other
2542 # lines might depend on this still being active.
2543 del self.dbg
2544
Johnny Chen86268e42011-09-30 21:48:35 +00002545 def switch_to_thread_with_stop_reason(self, stop_reason):
2546 """
2547 Run the 'thread list' command, and select the thread with stop reason as
2548 'stop_reason'. If no such thread exists, no select action is done.
2549 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002550 from .lldbutil import stop_reason_to_str
Johnny Chen86268e42011-09-30 21:48:35 +00002551 self.runCmd('thread list')
2552 output = self.res.GetOutput()
2553 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2554 stop_reason_to_str(stop_reason))
2555 for line in output.splitlines():
2556 matched = thread_line_pattern.match(line)
2557 if matched:
2558 self.runCmd('thread select %s' % matched.group(1))
2559
Enrico Granata7594f142013-06-17 22:51:50 +00002560 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002561 """
2562 Ask the command interpreter to handle the command and then check its
2563 return status.
2564 """
2565 # Fail fast if 'cmd' is not meaningful.
2566 if not cmd or len(cmd) == 0:
2567 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002568
Johnny Chen8d55a342010-08-31 17:42:54 +00002569 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002570
Daniel Maleae0f8f572013-08-26 23:57:52 +00002571 if cmd.startswith("target create "):
2572 cmd = cmd.replace("target create ", "file ")
Daniel Maleae0f8f572013-08-26 23:57:52 +00002573
Johnny Chen63dfb272010-09-01 00:15:19 +00002574 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002575
Johnny Chen63dfb272010-09-01 00:15:19 +00002576 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002577 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002578
Johnny Chen150c3cc2010-10-15 01:18:29 +00002579 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002580 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002581 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002582 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002583 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002584 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002585 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002586 print("runCmd failed!", file=sbuf)
2587 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002588
Johnny Chenff3d01d2010-08-20 21:03:09 +00002589 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002590 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002591 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002592 # For process launch, wait some time before possible next try.
2593 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002594 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002595 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002596
Johnny Chen27f212d2010-08-19 23:26:59 +00002597 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002598 self.assertTrue(self.res.Succeeded(),
2599 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002600
Jim Ingham63dfc722012-09-22 00:05:11 +00002601 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2602 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2603
2604 Otherwise, all the arguments have the same meanings as for the expect function"""
2605
2606 trace = (True if traceAlways else trace)
2607
2608 if exe:
2609 # First run the command. If we are expecting error, set check=False.
2610 # Pass the assert message along since it provides more semantic info.
2611 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2612
2613 # Then compare the output against expected strings.
2614 output = self.res.GetError() if error else self.res.GetOutput()
2615
2616 # If error is True, the API client expects the command to fail!
2617 if error:
2618 self.assertFalse(self.res.Succeeded(),
2619 "Command '" + str + "' is expected to fail!")
2620 else:
2621 # No execution required, just compare str against the golden input.
2622 output = str
2623 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002624 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002625
2626 # The heading says either "Expecting" or "Not expecting".
2627 heading = "Expecting" if matching else "Not expecting"
2628
2629 for pattern in patterns:
2630 # Match Objects always have a boolean value of True.
2631 match_object = re.search(pattern, output)
2632 matched = bool(match_object)
2633 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002634 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2635 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002636 if matched:
2637 break
2638
2639 self.assertTrue(matched if matching else not matched,
2640 msg if msg else EXP_MSG(str, exe))
2641
2642 return match_object
2643
Enrico Granata7594f142013-06-17 22:51:50 +00002644 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 +00002645 """
2646 Similar to runCmd; with additional expect style output matching ability.
2647
2648 Ask the command interpreter to handle the command and then check its
2649 return status. The 'msg' parameter specifies an informational assert
2650 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002651 'startstr', matches the substrings contained in 'substrs', and regexp
2652 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002653
2654 If the keyword argument error is set to True, it signifies that the API
2655 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002656 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002657 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002658
2659 If the keyword argument matching is set to False, it signifies that the API
2660 client is expecting the output of the command not to match the golden
2661 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002662
2663 Finally, the required argument 'str' represents the lldb command to be
2664 sent to the command interpreter. In case the keyword argument 'exe' is
2665 set to False, the 'str' is treated as a string to be matched/not-matched
2666 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002667 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002668 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002669
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002670 if exe:
2671 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002672 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002673 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002674
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002675 # Then compare the output against expected strings.
2676 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002677
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002678 # If error is True, the API client expects the command to fail!
2679 if error:
2680 self.assertFalse(self.res.Succeeded(),
2681 "Command '" + str + "' is expected to fail!")
2682 else:
2683 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002684 if isinstance(str,lldb.SBCommandReturnObject):
2685 output = str.GetOutput()
2686 else:
2687 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002688 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002689 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002690
Johnny Chenea88e942010-09-21 21:08:53 +00002691 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002692 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002693
2694 # Start from the startstr, if specified.
2695 # If there's no startstr, set the initial state appropriately.
2696 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002697
Johnny Chen150c3cc2010-10-15 01:18:29 +00002698 if startstr:
2699 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002700 print("%s start string: %s" % (heading, startstr), file=sbuf)
2701 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002702
Johnny Chen86268e42011-09-30 21:48:35 +00002703 # Look for endstr, if specified.
2704 keepgoing = matched if matching else not matched
2705 if endstr:
2706 matched = output.endswith(endstr)
2707 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002708 print("%s end string: %s" % (heading, endstr), file=sbuf)
2709 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002710
Johnny Chenea88e942010-09-21 21:08:53 +00002711 # Look for sub strings, if specified.
2712 keepgoing = matched if matching else not matched
2713 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002714 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002715 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002716 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002717 print("%s sub string: %s" % (heading, str), file=sbuf)
2718 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002719 keepgoing = matched if matching else not matched
2720 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002721 break
2722
Johnny Chenea88e942010-09-21 21:08:53 +00002723 # Search for regular expression patterns, if specified.
2724 keepgoing = matched if matching else not matched
2725 if patterns and keepgoing:
2726 for pattern in patterns:
2727 # Match Objects always have a boolean value of True.
2728 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002729 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002730 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2731 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002732 keepgoing = matched if matching else not matched
2733 if not keepgoing:
2734 break
Johnny Chenea88e942010-09-21 21:08:53 +00002735
2736 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002737 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002738
Johnny Chenf3c59232010-08-25 22:52:45 +00002739 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002740 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002741 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002742
2743 method = getattr(obj, name)
2744 import inspect
2745 self.assertTrue(inspect.ismethod(method),
2746 name + "is a method name of object: " + str(obj))
2747 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002748 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002749 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002750 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002751
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002752 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2753 """Platform specific way to build the default binaries."""
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002754 module = builder_module()
2755 if target_is_android():
2756 dictionary = append_android_envs(dictionary)
2757 if self.debug_info is None:
2758 return self.buildDefault(architecture, compiler, dictionary, clean)
2759 elif self.debug_info == "dsym":
2760 return self.buildDsym(architecture, compiler, dictionary, clean)
2761 elif self.debug_info == "dwarf":
2762 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002763 elif self.debug_info == "dwo":
2764 return self.buildDwo(architecture, compiler, dictionary, clean)
2765 else:
2766 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002767
Johnny Chenf359cf22011-05-27 23:36:52 +00002768 # =================================================
2769 # Misc. helper methods for debugging test execution
2770 # =================================================
2771
Johnny Chen56b92a72011-07-11 19:15:11 +00002772 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002773 """Debug print a SBValue object, if traceAlways is True."""
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002774 from .lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002775
Johnny Chen8d55a342010-08-31 17:42:54 +00002776 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002777 return
2778
2779 err = sys.stderr
2780 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002781 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2782 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2783 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2784 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2785 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2786 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2787 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2788 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2789 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002790
Johnny Chen36c5eb12011-08-05 20:17:27 +00002791 def DebugSBType(self, type):
2792 """Debug print a SBType object, if traceAlways is True."""
2793 if not traceAlways:
2794 return
2795
2796 err = sys.stderr
2797 err.write(type.GetName() + ":\n")
2798 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2799 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2800 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2801
Johnny Chenb877f1e2011-03-12 01:18:19 +00002802 def DebugPExpect(self, child):
2803 """Debug the spwaned pexpect object."""
2804 if not traceAlways:
2805 return
2806
Zachary Turnerff890da2015-10-19 23:45:41 +00002807 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002808
2809 @classmethod
2810 def RemoveTempFile(cls, file):
2811 if os.path.exists(file):
2812 os.remove(file)