blob: fb14fba83197edbde32ff8c09a58830c20224d08 [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
Johnny Chen90312a82010-09-21 22:34:45 +000043import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000044import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000045import re
Daniel Malea69207462013-06-05 21:07:02 +000046import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000047from subprocess import *
Johnny Chenf2b70232010-08-25 18:49:48 +000048import time
Johnny Chena33a93c2010-08-30 23:08:52 +000049import types
Zachary Turner43a01e42015-10-20 21:06:05 +000050
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000051# Third-party modules
52import unittest2
Zachary Turner43a01e42015-10-20 21:06:05 +000053from six import add_metaclass
Zachary Turner814236d2015-10-21 17:48:52 +000054from six import StringIO as SixStringIO
55from six.moves.urllib import parse as urlparse
Zachary Turnercd236b82015-10-26 18:48:24 +000056import six
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000057
58# LLDB modules
59import lldb
60from . import lldbtest_config
61from . import lldbutil
62from . import test_categories
Siva Chandra8af91662015-06-05 00:22:49 +000063
Vince Harron85d19652015-05-21 19:09:29 +000064# dosep.py starts lots and lots of dotest instances
65# This option helps you find if two (or more) dotest instances are using the same
66# directory at the same time
67# Enable it to cause test failures and stderr messages if dotest instances try to run in
68# the same directory simultaneously
69# it is disabled by default because it litters the test directories with ".dirlock" files
70debug_confirm_directory_exclusivity = False
71
Johnny Chen707b3c92010-10-11 22:25:46 +000072# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000073# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000074
75# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000076if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
77 traceAlways = True
78else:
79 traceAlways = False
80
Johnny Chen707b3c92010-10-11 22:25:46 +000081# By default, doCleanup is True.
82if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
83 doCleanup = False
84else:
85 doCleanup = True
86
Johnny Chen8d55a342010-08-31 17:42:54 +000087
Johnny Chen00778092010-08-09 22:01:17 +000088#
89# Some commonly used assert messages.
90#
91
Johnny Chenaa902922010-09-17 22:45:27 +000092COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
93
Johnny Chen00778092010-08-09 22:01:17 +000094CURRENT_EXECUTABLE_SET = "Current executable set successfully"
95
Johnny Chen7d1d7532010-09-02 21:23:12 +000096PROCESS_IS_VALID = "Process is valid"
97
98PROCESS_KILLED = "Process is killed successfully"
99
Johnny Chend5f66fc2010-12-23 01:12:19 +0000100PROCESS_EXITED = "Process exited successfully"
101
102PROCESS_STOPPED = "Process status should be stopped"
103
Sean Callanan05834cd2015-07-01 23:56:30 +0000104RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000105
Johnny Chen17941842010-08-09 23:44:24 +0000106RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000107
Johnny Chen67af43f2010-10-05 19:27:32 +0000108BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
109
Johnny Chen17941842010-08-09 23:44:24 +0000110BREAKPOINT_CREATED = "Breakpoint created successfully"
111
Johnny Chenf10af382010-12-04 00:07:24 +0000112BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
113
Johnny Chene76896c2010-08-17 21:33:31 +0000114BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
115
Johnny Chen17941842010-08-09 23:44:24 +0000116BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000117
Johnny Chen703dbd02010-09-30 17:06:24 +0000118BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
119
Johnny Chen164f1e12010-10-15 18:07:09 +0000120BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
121
Greg Clayton5db6b792012-10-24 18:24:14 +0000122MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
123
Johnny Chen89109ed12011-06-27 20:05:23 +0000124OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
125
Johnny Chen5b3a3572010-12-09 18:22:12 +0000126SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
127
Johnny Chenc70b02a2010-09-22 23:00:20 +0000128STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
129
Johnny Chen1691a162011-04-15 16:44:48 +0000130STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
131
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000132STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
133
Johnny Chen5d6c4642010-11-10 23:46:38 +0000134STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000135
Johnny Chen5d6c4642010-11-10 23:46:38 +0000136STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
137 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000138
Johnny Chen2e431ce2010-10-20 18:38:48 +0000139STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
140
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000141STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
142
Johnny Chenc066ab42010-10-14 01:22:03 +0000143STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
144
Johnny Chen00778092010-08-09 22:01:17 +0000145STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
146
Johnny Chenf68cc122011-09-15 21:09:59 +0000147STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
148
Johnny Chen3c884a02010-08-24 22:07:56 +0000149DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
150
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000151VALID_BREAKPOINT = "Got a valid breakpoint"
152
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000153VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
154
Johnny Chen7209d84f2011-05-06 23:26:12 +0000155VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
156
Johnny Chen5ee88192010-08-27 23:47:36 +0000157VALID_FILESPEC = "Got a valid filespec"
158
Johnny Chen025d1b82010-12-08 01:25:21 +0000159VALID_MODULE = "Got a valid module"
160
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000161VALID_PROCESS = "Got a valid process"
162
Johnny Chen025d1b82010-12-08 01:25:21 +0000163VALID_SYMBOL = "Got a valid symbol"
164
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000165VALID_TARGET = "Got a valid target"
166
Matthew Gardinerc928de32014-10-22 07:22:56 +0000167VALID_PLATFORM = "Got a valid platform"
168
Johnny Chen15f247a2012-02-03 20:43:00 +0000169VALID_TYPE = "Got a valid type"
170
Johnny Chen5819ab42011-07-15 22:28:10 +0000171VALID_VARIABLE = "Got a valid variable"
172
Johnny Chen981463d2010-08-25 19:00:04 +0000173VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000174
Johnny Chenf68cc122011-09-15 21:09:59 +0000175WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000176
Sean Callanan05834cd2015-07-01 23:56:30 +0000177def CMD_MSG(str):
178 '''A generic "Command '%s' returns successfully" message generator.'''
179 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000180
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000181def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000182 '''A generic message generator for the completion mechanism.'''
183 return "'%s' successfully completes to '%s'" % (str_before, str_after)
184
Johnny Chenc0c67f22010-11-09 18:42:22 +0000185def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000186 '''A generic "'%s' returns expected result" message generator if exe.
187 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000188 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000189
Johnny Chen3343f042010-10-19 19:11:38 +0000190def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000191 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000192 return "Value of setting '%s' is correct" % setting
193
Johnny Chen27c41232010-08-26 21:49:29 +0000194def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000195 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000196 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000197
Johnny Chen47ceb032010-10-11 23:52:19 +0000198def line_number(filename, string_to_match):
199 """Helper function to return the line number of the first matched string."""
200 with open(filename, 'r') as f:
201 for i, line in enumerate(f):
202 if line.find(string_to_match) != -1:
203 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000204 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000205 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000206
Johnny Chen67af43f2010-10-05 19:27:32 +0000207def pointer_size():
208 """Return the pointer size of the host system."""
209 import ctypes
210 a_pointer = ctypes.c_void_p(0xffff)
211 return 8 * ctypes.sizeof(a_pointer)
212
Johnny Chen57816732012-02-09 02:01:59 +0000213def is_exe(fpath):
214 """Returns true if fpath is an executable."""
215 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
216
217def which(program):
218 """Returns the full path to a program; None otherwise."""
219 fpath, fname = os.path.split(program)
220 if fpath:
221 if is_exe(program):
222 return program
223 else:
224 for path in os.environ["PATH"].split(os.pathsep):
225 exe_file = os.path.join(path, program)
226 if is_exe(exe_file):
227 return exe_file
228 return None
229
Zachary Turner814236d2015-10-21 17:48:52 +0000230class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000231 """
232 A nice little context manager for recording the debugger interactions into
233 our session object. If trace flag is ON, it also emits the interactions
234 into the stderr.
235 """
236 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000237 """Create a SixStringIO instance; record the session obj and trace flag."""
238 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000239 # The test might not have undergone the 'setUp(self)' phase yet, so that
240 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000241 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000242 self.trace = trace
243
244 def __enter__(self):
245 """
246 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000247 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000248 """
249 return self
250
251 def __exit__(self, type, value, tb):
252 """
253 Context management protocol on exit from the body of the with statement.
254 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000255 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000256 """
257 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000258 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000259 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000260 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000261 self.close()
262
Zachary Turner43a01e42015-10-20 21:06:05 +0000263@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000264class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000265
266 @abc.abstractproperty
267 def pid(self):
268 """Returns process PID if has been launched already."""
269
270 @abc.abstractmethod
271 def launch(self, executable, args):
272 """Launches new process with given executable and args."""
273
274 @abc.abstractmethod
275 def terminate(self):
276 """Terminates previously launched process.."""
277
278class _LocalProcess(_BaseProcess):
279
280 def __init__(self, trace_on):
281 self._proc = None
282 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000283 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000284
285 @property
286 def pid(self):
287 return self._proc.pid
288
289 def launch(self, executable, args):
290 self._proc = Popen([executable] + args,
291 stdout = open(os.devnull) if not self._trace_on else None,
292 stdin = PIPE)
293
294 def terminate(self):
295 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000296 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000297 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
298 for sig in signals_to_try:
299 try:
300 self._proc.send_signal(getattr(signal, sig))
301 time.sleep(self._delayafterterminate)
302 if self._proc.poll() != None:
303 return
304 except ValueError:
305 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000306 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000307 time.sleep(self._delayafterterminate)
308 if self._proc.poll() != None:
309 return
310 self._proc.kill()
311 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000312
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000313 def poll(self):
314 return self._proc.poll()
315
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000316class _RemoteProcess(_BaseProcess):
317
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000318 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000319 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000320 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000321
322 @property
323 def pid(self):
324 return self._pid
325
326 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000327 if self._install_remote:
328 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000329 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000330
331 dst_file_spec = lldb.SBFileSpec(dst_path, False)
332 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
333 if err.Fail():
334 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
335 else:
336 dst_path = executable
337 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000338
339 launch_info = lldb.SBLaunchInfo(args)
340 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000341 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000342
343 # Redirect stdout and stderr to /dev/null
344 launch_info.AddSuppressFileAction(1, False, True)
345 launch_info.AddSuppressFileAction(2, False, True)
346
347 err = lldb.remote_platform.Launch(launch_info)
348 if err.Fail():
349 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
350 self._pid = launch_info.GetProcessID()
351
352 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000353 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000354
Johnny Chen690fcef2010-10-15 23:55:05 +0000355# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000356# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000357def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000358 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000359
360 If the exit code was non-zero it raises a CalledProcessError. The
361 CalledProcessError object will have the return code in the returncode
362 attribute and output in the output attribute.
363
364 The arguments are the same as for the Popen constructor. Example:
365
366 >>> check_output(["ls", "-l", "/dev/null"])
367 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
368
369 The stdout argument is not allowed as it is used internally.
370 To capture standard error in the result, use stderr=STDOUT.
371
372 >>> check_output(["/bin/sh", "-c",
373 ... "ls -l non_existent_file ; exit 0"],
374 ... stderr=STDOUT)
375 'ls: non_existent_file: No such file or directory\n'
376 """
377
378 # Assign the sender object to variable 'test' and remove it from kwargs.
379 test = kwargs.pop('sender', None)
380
Zachary Turner9ef307b2014-07-22 16:19:29 +0000381 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
382 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000383 output = ""
384 error = ""
385 for shellCommand in commandList:
386 if 'stdout' in kwargs:
387 raise ValueError('stdout argument not allowed, it will be overridden.')
388 if 'shell' in kwargs and kwargs['shell']==False:
389 raise ValueError('shell=False not allowed')
390 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
391 pid = process.pid
392 this_output, this_error = process.communicate()
393 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000394
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000395 # Enable trace on failure return while tracking down FreeBSD buildbot issues
396 trace = traceAlways
397 if not trace and retcode and sys.platform.startswith("freebsd"):
398 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000399
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000400 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000401 print(file=sbuf)
402 print("os command:", shellCommand, file=sbuf)
403 print("with pid:", pid, file=sbuf)
404 print("stdout:", this_output, file=sbuf)
405 print("stderr:", this_error, file=sbuf)
406 print("retcode:", retcode, file=sbuf)
407 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000408
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000409 if retcode:
410 cmd = kwargs.get("args")
411 if cmd is None:
412 cmd = shellCommand
413 raise CalledProcessError(retcode, cmd)
414 output = output + this_output
415 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000416 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000417
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000418def getsource_if_available(obj):
419 """
420 Return the text of the source code for an object if available. Otherwise,
421 a print representation is returned.
422 """
423 import inspect
424 try:
425 return inspect.getsource(obj)
426 except:
427 return repr(obj)
428
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000429def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000430 if sys.platform.startswith("freebsd"):
431 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000432 return __import__("builder_" + sys.platform)
433
Siva Chandra8af91662015-06-05 00:22:49 +0000434def run_adb_command(cmd, device_id):
435 device_id_args = []
436 if device_id:
437 device_id_args = ["-s", device_id]
438 full_cmd = ["adb"] + device_id_args + cmd
439 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
440 stdout, stderr = p.communicate()
441 return p.returncode, stdout, stderr
442
Chaoren Line9bbabc2015-07-18 00:37:55 +0000443def append_android_envs(dictionary):
444 if dictionary is None:
445 dictionary = {}
446 dictionary["OS"] = "Android"
447 if android_device_api() >= 16:
448 dictionary["PIE"] = 1
449 return dictionary
450
Chaoren Lin9070f532015-07-17 22:13:29 +0000451def target_is_android():
452 if not hasattr(target_is_android, 'result'):
453 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
454 match = re.match(".*-.*-.*-android", triple)
455 target_is_android.result = match is not None
456 return target_is_android.result
457
Siva Chandra8af91662015-06-05 00:22:49 +0000458def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000459 if not hasattr(android_device_api, 'result'):
460 assert lldb.platform_url is not None
461 device_id = None
462 parsed_url = urlparse.urlparse(lldb.platform_url)
463 if parsed_url.scheme == "adb":
464 device_id = parsed_url.netloc.split(":")[0]
465 retcode, stdout, stderr = run_adb_command(
466 ["shell", "getprop", "ro.build.version.sdk"], device_id)
467 if retcode == 0:
468 android_device_api.result = int(stdout)
469 else:
470 raise LookupError(
471 ">>> Unable to determine the API level of the Android device.\n"
472 ">>> stdout:\n%s\n"
473 ">>> stderr:\n%s\n" % (stdout, stderr))
474 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000475
Zachary Turnerabdb8392015-11-16 22:40:30 +0000476def check_expected_version(comparison, expected, actual):
477 def fn_leq(x,y): return x <= y
478 def fn_less(x,y): return x < y
479 def fn_geq(x,y): return x >= y
480 def fn_greater(x,y): return x > y
481 def fn_eq(x,y): return x == y
482 def fn_neq(x,y): return x != y
483
484 op_lookup = {
485 "==": fn_eq,
486 "=": fn_eq,
487 "!=": fn_neq,
488 "<>": fn_neq,
489 ">": fn_greater,
490 "<": fn_less,
491 ">=": fn_geq,
492 "<=": fn_leq
493 }
494 expected_str = '.'.join([str(x) for x in expected])
495 actual_str = '.'.join([str(x) for x in actual])
496
497 return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str))
498
Johnny Chena74bb0a2011-08-01 18:46:13 +0000499#
500# Decorators for categorizing test cases.
501#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000502from functools import wraps
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000503def add_test_categories(cat):
504 """Decorate an item with test categories"""
505 cat = test_categories.validate(cat, True)
506 def impl(func):
507 func.getCategories = lambda test: cat
508 return func
509 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000510
Johnny Chena74bb0a2011-08-01 18:46:13 +0000511def benchmarks_test(func):
512 """Decorate the item as a benchmarks test."""
513 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
514 raise Exception("@benchmarks_test can only be used to decorate a test method")
515 @wraps(func)
516 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000517 if not lldb.just_do_benchmarks_test:
518 self.skipTest("benchmarks tests")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000519 return func(self, *args, **kwargs)
520
521 # Mark this function as such to separate them from the regular tests.
522 wrapper.__benchmarks_test__ = True
523 return wrapper
524
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000525def no_debug_info_test(func):
526 """Decorate the item as a test what don't use any debug info. If this annotation is specified
527 then the test runner won't generate a separate test for each debug info format. """
528 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
529 raise Exception("@no_debug_info_test can only be used to decorate a test method")
530 @wraps(func)
531 def wrapper(self, *args, **kwargs):
532 return func(self, *args, **kwargs)
533
534 # Mark this function as such to separate them from the regular tests.
535 wrapper.__no_debug_info_test__ = True
536 return wrapper
537
Johnny Chenf1548d42012-04-06 00:56:05 +0000538def dsym_test(func):
539 """Decorate the item as a dsym test."""
540 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
541 raise Exception("@dsym_test can only be used to decorate a test method")
542 @wraps(func)
543 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000544 if lldb.dont_do_dsym_test:
545 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000546 return func(self, *args, **kwargs)
547
548 # Mark this function as such to separate them from the regular tests.
549 wrapper.__dsym_test__ = True
550 return wrapper
551
552def dwarf_test(func):
553 """Decorate the item as a dwarf test."""
554 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
555 raise Exception("@dwarf_test can only be used to decorate a test method")
556 @wraps(func)
557 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000558 if lldb.dont_do_dwarf_test:
559 self.skipTest("dwarf 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.__dwarf_test__ = True
564 return wrapper
565
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000566def dwo_test(func):
567 """Decorate the item as a dwo test."""
568 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
569 raise Exception("@dwo_test can only be used to decorate a test method")
570 @wraps(func)
571 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000572 if lldb.dont_do_dwo_test:
573 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000574 return func(self, *args, **kwargs)
575
576 # Mark this function as such to separate them from the regular tests.
577 wrapper.__dwo_test__ = True
578 return wrapper
579
Todd Fialaa41d48c2014-04-28 04:49:40 +0000580def debugserver_test(func):
581 """Decorate the item as a debugserver test."""
582 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
583 raise Exception("@debugserver_test can only be used to decorate a test method")
584 @wraps(func)
585 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000586 if lldb.dont_do_debugserver_test:
587 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000588 return func(self, *args, **kwargs)
589
590 # Mark this function as such to separate them from the regular tests.
591 wrapper.__debugserver_test__ = True
592 return wrapper
593
594def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000595 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000596 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
597 raise Exception("@llgs_test can only be used to decorate a test method")
598 @wraps(func)
599 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000600 if lldb.dont_do_llgs_test:
601 self.skipTest("llgs 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.__llgs_test__ = True
606 return wrapper
607
Daniel Maleae0f8f572013-08-26 23:57:52 +0000608def not_remote_testsuite_ready(func):
609 """Decorate the item as a test which is not ready yet for remote testsuite."""
610 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
611 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
612 @wraps(func)
613 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000614 if lldb.lldbtest_remote_sandbox or lldb.remote_platform:
615 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000616 return func(self, *args, **kwargs)
617
618 # Mark this function as such to separate them from the regular tests.
619 wrapper.__not_ready_for_remote_testsuite_test__ = True
620 return wrapper
621
Ed Maste433790a2014-04-23 12:55:41 +0000622def expectedFailure(expected_fn, bugnumber=None):
623 def expectedFailure_impl(func):
624 @wraps(func)
625 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000626 from unittest2 import case
627 self = args[0]
Ed Maste433790a2014-04-23 12:55:41 +0000628 if expected_fn(self):
Zachary Turner5cb8e672015-11-06 18:14:42 +0000629 xfail_func = unittest2.expectedFailure(func)
630 xfail_func(*args, **kwargs)
631 else:
632 func(*args, **kwargs)
Ed Maste433790a2014-04-23 12:55:41 +0000633 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000634 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
635 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000636 if six.callable(bugnumber):
Ying Chen464d1e12015-03-27 00:26:52 +0000637 return expectedFailure_impl(bugnumber)
638 else:
639 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000640
Ying Chen7091c2c2015-04-21 01:15:47 +0000641# provide a function to xfail on defined oslist, compiler version, and archs
642# if none is specified for any argument, that argument won't be checked and thus means for all
643# for example,
644# @expectedFailureAll, xfail for all platform/compiler/arch,
645# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
646# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Zachary Turnerabdb8392015-11-16 22:40:30 +0000647def expectedFailureAll(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None, swig_version=None, py_version=None):
Ying Chen7091c2c2015-04-21 01:15:47 +0000648 def fn(self):
Zachary Turnerabdb8392015-11-16 22:40:30 +0000649 oslist_passes = oslist is None or self.getPlatform() in oslist
650 compiler_passes = compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))
651 arch_passes = self.expectedArch(archs)
652 triple_passes = triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())
653 debug_info_passes = debug_info is None or self.debug_info in debug_info
654 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))
655 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
656
657 return (oslist_passes and
658 compiler_passes and
659 arch_passes and
660 triple_passes and
661 debug_info_passes and
662 swig_version_passes and
663 py_version_passes)
Ying Chen7091c2c2015-04-21 01:15:47 +0000664 return expectedFailure(fn, bugnumber)
665
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000666def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000667 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
668
669def expectedFailureDwo(bugnumber=None):
670 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000671
672def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000673 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000674
675def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
676 if compiler_version is None:
677 compiler_version=['=', None]
678 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
679
Vince Harron8974ce22015-03-13 19:54:54 +0000680# to XFAIL a specific clang versions, try this
681# @expectedFailureClang('bugnumber', ['<=', '3.4'])
682def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000683 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000684
685def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000686 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000687
Matt Kopec0de53f02013-03-15 19:10:12 +0000688def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000689 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000690
Ed Maste433790a2014-04-23 12:55:41 +0000691def expectedFailureArch(arch, bugnumber=None):
692 def fn(self):
693 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000694 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000695
Enrico Granatae6cedc12013-02-23 01:05:23 +0000696def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000697 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000698
Matt Kopecee969f92013-09-26 23:30:59 +0000699def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000700 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000701
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000702def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000703 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000704 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000705 self.expectedCompiler(compilers) and
706 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000707 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000708
Chaoren Linf7160f32015-06-09 17:39:27 +0000709def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
710 def fn(self):
711 return (getHostPlatform() in oslist and
712 self.expectedCompiler(compilers))
713 return expectedFailure(fn, bugnumber)
714
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000715def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000716 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000717 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000718
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000719def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
720 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000721
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000722def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
723 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000724
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000725def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
726 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000727
Chaoren Linf7160f32015-06-09 17:39:27 +0000728def expectedFailureHostWindows(bugnumber=None, compilers=None):
729 return expectedFailureHostOS(['windows'], bugnumber, compilers)
730
Pavel Labath090152b2015-08-20 11:37:19 +0000731def matchAndroid(api_levels=None, archs=None):
732 def match(self):
733 if not target_is_android():
734 return False
735 if archs is not None and self.getArchitecture() not in archs:
736 return False
737 if api_levels is not None and android_device_api() not in api_levels:
738 return False
739 return True
740 return match
741
742
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000743def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000744 """ Mark a test as xfail for Android.
745
746 Arguments:
747 bugnumber - The LLVM pr associated with the problem.
748 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000749 for which a test is expected to fail. None means all API level.
750 arch - A sequence of architecture names specifying the architectures
751 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000752 """
Pavel Labath090152b2015-08-20 11:37:19 +0000753 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000754
Vince Harron7ac3ea42015-06-26 15:13:21 +0000755# if the test passes on the first try, we're done (success)
756# if the test fails once, then passes on the second try, raise an ExpectedFailure
757# if the test fails twice in a row, re-throw the exception from the second test run
758def expectedFlakey(expected_fn, bugnumber=None):
759 def expectedFailure_impl(func):
760 @wraps(func)
761 def wrapper(*args, **kwargs):
762 from unittest2 import case
763 self = args[0]
764 try:
765 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000766 # don't retry if the test case is already decorated with xfail or skip
767 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
768 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000769 except Exception:
770 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000771 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000772 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000773 self.tearDown()
774 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000775 func(*args, **kwargs)
776 except Exception:
777 # oh snap! two failures in a row, record a failure/error
778 raise
779 # record the expected failure
780 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
781 else:
782 raise
783 return wrapper
784 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
785 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000786 if six.callable(bugnumber):
Vince Harron7ac3ea42015-06-26 15:13:21 +0000787 return expectedFailure_impl(bugnumber)
788 else:
789 return expectedFailure_impl
790
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000791def expectedFlakeyDwarf(bugnumber=None):
792 def fn(self):
793 return self.debug_info == "dwarf"
794 return expectedFlakey(fn, bugnumber)
795
796def expectedFlakeyDsym(bugnumber=None):
797 def fn(self):
798 return self.debug_info == "dwarf"
799 return expectedFlakey(fn, bugnumber)
800
Vince Harron7ac3ea42015-06-26 15:13:21 +0000801def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
802 def fn(self):
803 return (self.getPlatform() in oslist and
804 self.expectedCompiler(compilers))
805 return expectedFlakey(fn, bugnumber)
806
807def expectedFlakeyDarwin(bugnumber=None, compilers=None):
808 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
809 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
810
811def expectedFlakeyLinux(bugnumber=None, compilers=None):
812 return expectedFlakeyOS(['linux'], bugnumber, compilers)
813
814def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
815 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
816
817def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
818 if compiler_version is None:
819 compiler_version=['=', None]
820 def fn(self):
821 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
822 return expectedFlakey(fn, bugnumber)
823
824# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
825def expectedFlakeyClang(bugnumber=None, compiler_version=None):
826 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
827
828# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
829def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
830 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
831
Pavel Labath63a579c2015-09-07 12:15:27 +0000832def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
833 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
834
Greg Clayton12514562013-12-05 22:22:32 +0000835def skipIfRemote(func):
836 """Decorate the item to skip tests if testing remotely."""
837 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
838 raise Exception("@skipIfRemote can only be used to decorate a test method")
839 @wraps(func)
840 def wrapper(*args, **kwargs):
841 from unittest2 import case
842 if lldb.remote_platform:
843 self = args[0]
844 self.skipTest("skip on remote platform")
845 else:
846 func(*args, **kwargs)
847 return wrapper
848
Siva Chandra4470f382015-06-17 22:32:27 +0000849def skipUnlessListedRemote(remote_list=None):
850 def myImpl(func):
851 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
852 raise Exception("@skipIfRemote can only be used to decorate a "
853 "test method")
854
855 @wraps(func)
856 def wrapper(*args, **kwargs):
857 if remote_list and lldb.remote_platform:
858 self = args[0]
859 triple = self.dbg.GetSelectedPlatform().GetTriple()
860 for r in remote_list:
861 if r in triple:
862 func(*args, **kwargs)
863 return
864 self.skipTest("skip on remote platform %s" % str(triple))
865 else:
866 func(*args, **kwargs)
867 return wrapper
868
869 return myImpl
870
Greg Clayton12514562013-12-05 22:22:32 +0000871def skipIfRemoteDueToDeadlock(func):
872 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
873 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
874 raise Exception("@skipIfRemote can only be used to decorate a test method")
875 @wraps(func)
876 def wrapper(*args, **kwargs):
877 from unittest2 import case
878 if lldb.remote_platform:
879 self = args[0]
880 self.skipTest("skip on remote platform (deadlocks)")
881 else:
882 func(*args, **kwargs)
883 return wrapper
884
Enrico Granatab633e432014-10-06 21:37:06 +0000885def skipIfNoSBHeaders(func):
886 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
887 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000888 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000889 @wraps(func)
890 def wrapper(*args, **kwargs):
891 from unittest2 import case
892 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000893 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000894 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000895 else:
896 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000897 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000898 if not os.path.exists(header):
899 self.skipTest("skip because LLDB.h header not found")
900 else:
901 func(*args, **kwargs)
902 return wrapper
903
Enrico Granata5f92a132015-11-05 00:46:25 +0000904def skipIfiOSSimulator(func):
905 """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
906 return unittest2.skipIf(hasattr(lldb, 'remote_platform_name') and lldb.remote_platform_name == 'ios-simulator', 'skip on the iOS Simulator')(func)
907
Robert Flack13c7ad92015-03-30 14:12:17 +0000908def skipIfFreeBSD(func):
909 """Decorate the item to skip tests that should be skipped on FreeBSD."""
910 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000911
Greg Claytone0d0a762015-04-02 18:24:03 +0000912def getDarwinOSTriples():
913 return ['darwin', 'macosx', 'ios']
914
Daniel Maleab3d41a22013-07-09 00:08:01 +0000915def skipIfDarwin(func):
916 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000917 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000918
Robert Flack13c7ad92015-03-30 14:12:17 +0000919def skipIfLinux(func):
920 """Decorate the item to skip tests that should be skipped on Linux."""
921 return skipIfPlatform(["linux"])(func)
922
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000923def skipUnlessHostLinux(func):
924 """Decorate the item to skip tests that should be skipped on any non Linux host."""
925 return skipUnlessHostPlatform(["linux"])(func)
926
Robert Flack13c7ad92015-03-30 14:12:17 +0000927def skipIfWindows(func):
928 """Decorate the item to skip tests that should be skipped on Windows."""
929 return skipIfPlatform(["windows"])(func)
930
Chaoren Line6eea5d2015-06-08 22:13:28 +0000931def skipIfHostWindows(func):
932 """Decorate the item to skip tests that should be skipped on Windows."""
933 return skipIfHostPlatform(["windows"])(func)
934
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000935def skipUnlessWindows(func):
936 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
937 return skipUnlessPlatform(["windows"])(func)
938
Robert Flack13c7ad92015-03-30 14:12:17 +0000939def skipUnlessDarwin(func):
940 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000941 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000942
Ryan Brown57bee1e2015-09-14 22:45:11 +0000943def skipUnlessGoInstalled(func):
944 """Decorate the item to skip tests when no Go compiler is available."""
945 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
946 raise Exception("@skipIfGcc can only be used to decorate a test method")
947 @wraps(func)
948 def wrapper(*args, **kwargs):
949 from unittest2 import case
950 self = args[0]
951 compiler = self.getGoCompilerVersion()
952 if not compiler:
953 self.skipTest("skipping because go compiler not found")
954 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000955 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +0000956 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +0000957 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
958 if not match_version:
959 # Couldn't determine version.
960 self.skipTest(
961 "skipping because go version could not be parsed "
962 "out of {}".format(compiler))
963 else:
964 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +0000965 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +0000966 compiler_strict_version = StrictVersion(match_version.group(1))
967 if compiler_strict_version < min_strict_version:
968 self.skipTest(
969 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +0000970 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +0000971 compiler_strict_version,
972 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +0000973 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +0000974 return wrapper
975
Robert Flack068898c2015-04-09 18:07:58 +0000976def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +0000977 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +0000978 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
979 if platform.startswith('freebsd'):
980 platform = 'freebsd'
981 return platform
982
Robert Flack6e1fd352015-05-15 12:39:33 +0000983def getHostPlatform():
984 """Returns the host platform running the test suite."""
985 # Attempts to return a platform name matching a target Triple platform.
986 if sys.platform.startswith('linux'):
987 return 'linux'
988 elif sys.platform.startswith('win32'):
989 return 'windows'
990 elif sys.platform.startswith('darwin'):
991 return 'darwin'
992 elif sys.platform.startswith('freebsd'):
993 return 'freebsd'
994 else:
995 return sys.platform
996
Robert Flackfb2f6c62015-04-17 08:02:18 +0000997def platformIsDarwin():
998 """Returns true if the OS triple for the selected platform is any valid apple OS"""
999 return getPlatform() in getDarwinOSTriples()
1000
Robert Flack6e1fd352015-05-15 12:39:33 +00001001def skipIfHostIncompatibleWithRemote(func):
1002 """Decorate the item to skip tests if binaries built on this host are incompatible."""
1003 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1004 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
1005 @wraps(func)
1006 def wrapper(*args, **kwargs):
1007 from unittest2 import case
1008 self = args[0]
1009 host_arch = self.getLldbArchitecture()
1010 host_platform = getHostPlatform()
1011 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +00001012 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +00001013 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
1014 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
1015 elif target_platform != host_platform:
1016 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
1017 else:
1018 func(*args, **kwargs)
1019 return wrapper
1020
Chaoren Line6eea5d2015-06-08 22:13:28 +00001021def skipIfHostPlatform(oslist):
1022 """Decorate the item to skip tests if running on one of the listed host platforms."""
1023 return unittest2.skipIf(getHostPlatform() in oslist,
1024 "skip on %s" % (", ".join(oslist)))
1025
1026def skipUnlessHostPlatform(oslist):
1027 """Decorate the item to skip tests unless running on one of the listed host platforms."""
1028 return unittest2.skipUnless(getHostPlatform() in oslist,
1029 "requires on of %s" % (", ".join(oslist)))
1030
Zachary Turner793d9972015-08-14 23:29:24 +00001031def skipUnlessArch(archlist):
1032 """Decorate the item to skip tests unless running on one of the listed architectures."""
1033 def myImpl(func):
1034 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1035 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1036
1037 @wraps(func)
1038 def wrapper(*args, **kwargs):
1039 self = args[0]
1040 if self.getArchitecture() not in archlist:
1041 self.skipTest("skipping for architecture %s (requires one of %s)" %
1042 (self.getArchitecture(), ", ".join(archlist)))
1043 else:
1044 func(*args, **kwargs)
1045 return wrapper
1046
1047 return myImpl
1048
Robert Flack13c7ad92015-03-30 14:12:17 +00001049def skipIfPlatform(oslist):
1050 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001051 return unittest2.skipIf(getPlatform() in oslist,
1052 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001053
1054def skipUnlessPlatform(oslist):
1055 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001056 return unittest2.skipUnless(getPlatform() in oslist,
1057 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001058
Daniel Malea48359902013-05-14 20:48:54 +00001059def skipIfLinuxClang(func):
1060 """Decorate the item to skip tests that should be skipped if building on
1061 Linux with clang.
1062 """
1063 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1064 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1065 @wraps(func)
1066 def wrapper(*args, **kwargs):
1067 from unittest2 import case
1068 self = args[0]
1069 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001070 platform = self.getPlatform()
1071 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001072 self.skipTest("skipping because Clang is used on Linux")
1073 else:
1074 func(*args, **kwargs)
1075 return wrapper
1076
Ying Chen7091c2c2015-04-21 01:15:47 +00001077# provide a function to skip on defined oslist, compiler version, and archs
1078# if none is specified for any argument, that argument won't be checked and thus means for all
1079# for example,
1080# @skipIf, skip for all platform/compiler/arch,
1081# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1082# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1083
1084# TODO: refactor current code, to make skipIfxxx functions to call this function
Zachary Turnerabdb8392015-11-16 22:40:30 +00001085def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None, swig_version=None, py_version=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001086 def fn(self):
Zachary Turnerabdb8392015-11-16 22:40:30 +00001087 oslist_passes = oslist is None or self.getPlatform() in oslist
1088 compiler_passes = compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))
1089 arch_passes = self.expectedArch(archs)
1090 debug_info_passes = debug_info is None or self.debug_info in debug_info
1091 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))
1092 py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
1093
1094 return (oslist_passes and
1095 compiler_passes and
1096 arch_passes and
1097 debug_info_passes and
1098 swig_version_passes and
1099 py_version_passes)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001100 return skipTestIfFn(fn, bugnumber, skipReason="skipping because os:%s compiler: %s %s arch: %s debug info: %s"%(oslist, compiler, compiler_version, archs, debug_info))
1101
1102def skipIfDebugInfo(bugnumber=None, debug_info=None):
1103 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1104
Greg Claytonedea2372015-10-07 20:01:13 +00001105def skipIfDWO(bugnumber=None):
1106 return skipIfDebugInfo(bugnumber, ["dwo"])
1107
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001108def skipIfDwarf(bugnumber=None):
1109 return skipIfDebugInfo(bugnumber, ["dwarf"])
1110
1111def skipIfDsym(bugnumber=None):
1112 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001113
1114def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1115 def skipTestIfFn_impl(func):
1116 @wraps(func)
1117 def wrapper(*args, **kwargs):
1118 from unittest2 import case
1119 self = args[0]
1120 if expected_fn(self):
1121 self.skipTest(skipReason)
1122 else:
1123 func(*args, **kwargs)
1124 return wrapper
Zachary Turnercd236b82015-10-26 18:48:24 +00001125 if six.callable(bugnumber):
Ying Chen7091c2c2015-04-21 01:15:47 +00001126 return skipTestIfFn_impl(bugnumber)
1127 else:
1128 return skipTestIfFn_impl
1129
Daniel Maleabe230792013-01-24 23:52:09 +00001130def skipIfGcc(func):
1131 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1132 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001133 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001134 @wraps(func)
1135 def wrapper(*args, **kwargs):
1136 from unittest2 import case
1137 self = args[0]
1138 compiler = self.getCompiler()
1139 if "gcc" in compiler:
1140 self.skipTest("skipping because gcc is the test compiler")
1141 else:
1142 func(*args, **kwargs)
1143 return wrapper
1144
Matt Kopec0de53f02013-03-15 19:10:12 +00001145def skipIfIcc(func):
1146 """Decorate the item to skip tests that should be skipped if building with icc ."""
1147 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1148 raise Exception("@skipIfIcc can only be used to decorate a test method")
1149 @wraps(func)
1150 def wrapper(*args, **kwargs):
1151 from unittest2 import case
1152 self = args[0]
1153 compiler = self.getCompiler()
1154 if "icc" in compiler:
1155 self.skipTest("skipping because icc is the test compiler")
1156 else:
1157 func(*args, **kwargs)
1158 return wrapper
1159
Daniel Malea55faa402013-05-02 21:44:31 +00001160def skipIfi386(func):
1161 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1162 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1163 raise Exception("@skipIfi386 can only be used to decorate a test method")
1164 @wraps(func)
1165 def wrapper(*args, **kwargs):
1166 from unittest2 import case
1167 self = args[0]
1168 if "i386" == self.getArchitecture():
1169 self.skipTest("skipping because i386 is not a supported architecture")
1170 else:
1171 func(*args, **kwargs)
1172 return wrapper
1173
Pavel Labath090152b2015-08-20 11:37:19 +00001174def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001175 """Decorator to skip tests when the target is Android.
1176
1177 Arguments:
1178 api_levels - The API levels for which the test should be skipped. If
1179 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001180 arch - A sequence of architecture names specifying the architectures
1181 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001182 """
1183 def myImpl(func):
1184 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1185 raise Exception("@skipIfTargetAndroid can only be used to "
1186 "decorate a test method")
1187 @wraps(func)
1188 def wrapper(*args, **kwargs):
1189 from unittest2 import case
1190 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001191 if matchAndroid(api_levels, archs)(self):
1192 self.skipTest("skiped on Android target with API %d and architecture %s" %
1193 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001194 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001195 return wrapper
1196 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001197
Ilia Kd9953052015-03-12 07:19:41 +00001198def skipUnlessCompilerRt(func):
1199 """Decorate the item to skip tests if testing remotely."""
1200 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1201 raise Exception("@skipUnless can only be used to decorate a test method")
1202 @wraps(func)
1203 def wrapper(*args, **kwargs):
1204 from unittest2 import case
1205 import os.path
1206 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "projects", "compiler-rt")
1207 if not os.path.exists(compilerRtPath):
1208 self = args[0]
1209 self.skipTest("skip if compiler-rt not found")
1210 else:
1211 func(*args, **kwargs)
1212 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001213
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001214class _PlatformContext(object):
1215 """Value object class which contains platform-specific options."""
1216
1217 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1218 self.shlib_environment_var = shlib_environment_var
1219 self.shlib_prefix = shlib_prefix
1220 self.shlib_extension = shlib_extension
1221
1222
Johnny Chena74bb0a2011-08-01 18:46:13 +00001223class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001224 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001225 Abstract base for performing lldb (see TestBase) or other generic tests (see
1226 BenchBase for one example). lldbtest.Base works with the test driver to
1227 accomplish things.
1228
Johnny Chen8334dad2010-10-22 23:15:46 +00001229 """
Enrico Granata5020f952012-10-24 21:42:49 +00001230
Enrico Granata19186272012-10-24 21:44:48 +00001231 # The concrete subclass should override this attribute.
1232 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001233
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001234 # Keep track of the old current working directory.
1235 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001236
Greg Clayton4570d3e2013-12-10 23:19:29 +00001237 @staticmethod
1238 def compute_mydir(test_file):
1239 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1240
1241 mydir = TestBase.compute_mydir(__file__)'''
1242 test_dir = os.path.dirname(test_file)
1243 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1244
Johnny Chenfb4264c2011-08-01 19:50:58 +00001245 def TraceOn(self):
1246 """Returns True if we are in trace mode (tracing detailed test execution)."""
1247 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001248
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001249 @classmethod
1250 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001251 """
1252 Python unittest framework class setup fixture.
1253 Do current directory manipulation.
1254 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001255 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001256 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001257 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001258
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001259 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001260 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001261
1262 # Change current working directory if ${LLDB_TEST} is defined.
1263 # See also dotest.py which sets up ${LLDB_TEST}.
1264 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001265 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001266 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001267 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001268 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1269
Vince Harron85d19652015-05-21 19:09:29 +00001270 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001271 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001272 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1273 try:
1274 cls.dir_lock.try_acquire()
1275 # write the class that owns the lock into the lock file
1276 cls.dir_lock.handle.write(cls.__name__)
1277 except IOError as ioerror:
1278 # nothing else should have this directory lock
1279 # wait here until we get a lock
1280 cls.dir_lock.acquire()
1281 # read the previous owner from the lock file
1282 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001283 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 +00001284 raise ioerror
1285
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001286 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001287 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001288 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Robert Flackfb2f6c62015-04-17 08:02:18 +00001289 elif getPlatform() == "linux" or getPlatform() == "freebsd":
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001290 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001291 else:
1292 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001293
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001294 @classmethod
1295 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001296 """
1297 Python unittest framework class teardown fixture.
1298 Do class-wide cleanup.
1299 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001300
Johnny Chen0fddfb22011-11-17 19:57:27 +00001301 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001302 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001303 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001304 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001305
Johnny Chen707b3c92010-10-11 22:25:46 +00001306 # Subclass might have specific cleanup function defined.
1307 if getattr(cls, "classCleanup", None):
1308 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001309 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001310 try:
1311 cls.classCleanup()
1312 except:
1313 exc_type, exc_value, exc_tb = sys.exc_info()
1314 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001315
Vince Harron85d19652015-05-21 19:09:29 +00001316 if debug_confirm_directory_exclusivity:
1317 cls.dir_lock.release()
1318 del cls.dir_lock
1319
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001320 # Restore old working directory.
1321 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001322 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001323 os.chdir(cls.oldcwd)
1324
Johnny Chena74bb0a2011-08-01 18:46:13 +00001325 @classmethod
1326 def skipLongRunningTest(cls):
1327 """
1328 By default, we skip long running test case.
1329 This can be overridden by passing '-l' to the test driver (dotest.py).
1330 """
1331 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1332 return False
1333 else:
1334 return True
Johnny Chened492022011-06-21 00:53:00 +00001335
Vince Harron6d3d0f12015-05-10 22:01:59 +00001336 def enableLogChannelsForCurrentTest(self):
1337 if len(lldbtest_config.channels) == 0:
1338 return
1339
1340 # if debug channels are specified in lldbtest_config.channels,
1341 # create a new set of log files for every test
1342 log_basename = self.getLogBasenameForCurrentTest()
1343
1344 # confirm that the file is writeable
1345 host_log_path = "{}-host.log".format(log_basename)
1346 open(host_log_path, 'w').close()
1347
1348 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1349 for channel_with_categories in lldbtest_config.channels:
1350 channel_then_categories = channel_with_categories.split(' ', 1)
1351 channel = channel_then_categories[0]
1352 if len(channel_then_categories) > 1:
1353 categories = channel_then_categories[1]
1354 else:
1355 categories = "default"
1356
1357 if channel == "gdb-remote":
1358 # communicate gdb-remote categories to debugserver
1359 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1360
1361 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1362 if not self.res.Succeeded():
1363 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1364
1365 # Communicate log path name to debugserver & lldb-server
1366 server_log_path = "{}-server.log".format(log_basename)
1367 open(server_log_path, 'w').close()
1368 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1369
1370 # Communicate channels to lldb-server
1371 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1372
1373 if len(lldbtest_config.channels) == 0:
1374 return
1375
1376 def disableLogChannelsForCurrentTest(self):
1377 # close all log files that we opened
1378 for channel_and_categories in lldbtest_config.channels:
1379 # channel format - <channel-name> [<category0> [<category1> ...]]
1380 channel = channel_and_categories.split(' ', 1)[0]
1381 self.ci.HandleCommand("log disable " + channel, self.res)
1382 if not self.res.Succeeded():
1383 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1384
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001385 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001386 """Fixture for unittest test case setup.
1387
1388 It works with the test driver to conditionally skip tests and does other
1389 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001390 #import traceback
1391 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001392
Daniel Malea9115f072013-08-06 15:02:32 +00001393 if "LIBCXX_PATH" in os.environ:
1394 self.libcxxPath = os.environ["LIBCXX_PATH"]
1395 else:
1396 self.libcxxPath = None
1397
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001398 if "LLDBMI_EXEC" in os.environ:
1399 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1400 else:
1401 self.lldbMiExec = None
Vince Harron790d95c2015-05-18 19:39:03 +00001402
Johnny Chenebe51722011-10-07 19:21:09 +00001403 # If we spawn an lldb process for test (via pexpect), do not load the
1404 # init file unless told otherwise.
1405 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1406 self.lldbOption = ""
1407 else:
1408 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001409
Johnny Chen985e7402011-08-01 21:13:26 +00001410 # Assign the test method name to self.testMethodName.
1411 #
1412 # For an example of the use of this attribute, look at test/types dir.
1413 # There are a bunch of test cases under test/types and we don't want the
1414 # module cacheing subsystem to be confused with executable name "a.out"
1415 # used for all the test cases.
1416 self.testMethodName = self._testMethodName
1417
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001418 # Benchmarks test is decorated with @benchmarks_test,
1419 # which also sets the "__benchmarks_test__" attribute of the
1420 # function object to True.
1421 try:
1422 if lldb.just_do_benchmarks_test:
1423 testMethod = getattr(self, self._testMethodName)
1424 if getattr(testMethod, "__benchmarks_test__", False):
1425 pass
1426 else:
1427 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +00001428 except AttributeError:
1429 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001430
Johnny Chen985e7402011-08-01 21:13:26 +00001431 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1432 # with it using pexpect.
1433 self.child = None
1434 self.child_prompt = "(lldb) "
1435 # If the child is interacting with the embedded script interpreter,
1436 # there are two exits required during tear down, first to quit the
1437 # embedded script interpreter and second to quit the lldb command
1438 # interpreter.
1439 self.child_in_script_interpreter = False
1440
Johnny Chenfb4264c2011-08-01 19:50:58 +00001441 # These are for customized teardown cleanup.
1442 self.dict = None
1443 self.doTearDownCleanup = False
1444 # And in rare cases where there are multiple teardown cleanups.
1445 self.dicts = []
1446 self.doTearDownCleanups = False
1447
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001448 # List of spawned subproces.Popen objects
1449 self.subprocesses = []
1450
Daniel Malea69207462013-06-05 21:07:02 +00001451 # List of forked process PIDs
1452 self.forkedProcessPids = []
1453
Johnny Chenfb4264c2011-08-01 19:50:58 +00001454 # Create a string buffer to record the session info, to be dumped into a
1455 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001456 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001457
Vince Harron1f160372015-05-21 18:51:20 +00001458 session_file = "{}.log".format(self.log_basename)
Zachary Turner8d13fab2015-11-07 01:08:15 +00001459 # Python 3 doesn't support unbuffered I/O in text mode. Open buffered.
1460 self.session = open(session_file, "w")
Johnny Chenfb4264c2011-08-01 19:50:58 +00001461
1462 # Optimistically set __errored__, __failed__, __expected__ to False
1463 # initially. If the test errored/failed, the session info
1464 # (self.session) is then dumped into a session specific file for
1465 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001466 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001467 self.__errored__ = False
1468 self.__failed__ = False
1469 self.__expected__ = False
1470 # We are also interested in unexpected success.
1471 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001472 # And skipped tests.
1473 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001474
1475 # See addTearDownHook(self, hook) which allows the client to add a hook
1476 # function to be run during tearDown() time.
1477 self.hooks = []
1478
1479 # See HideStdout(self).
1480 self.sys_stdout_hidden = False
1481
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001482 if self.platformContext:
1483 # set environment variable names for finding shared libraries
1484 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001485
Vince Harron6d3d0f12015-05-10 22:01:59 +00001486 # Create the debugger instance if necessary.
1487 try:
1488 self.dbg = lldb.DBG
1489 except AttributeError:
1490 self.dbg = lldb.SBDebugger.Create()
1491
1492 if not self.dbg:
1493 raise Exception('Invalid debugger instance')
1494
1495 # Retrieve the associated command interpreter instance.
1496 self.ci = self.dbg.GetCommandInterpreter()
1497 if not self.ci:
1498 raise Exception('Could not get the command interpreter')
1499
1500 # And the result object.
1501 self.res = lldb.SBCommandReturnObject()
1502
1503 self.enableLogChannelsForCurrentTest()
1504
Johnny Chen2a808582011-10-19 16:48:07 +00001505 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001506 """Perform the run hooks to bring lldb debugger to the desired state.
1507
Johnny Chen2a808582011-10-19 16:48:07 +00001508 By default, expect a pexpect spawned child and child prompt to be
1509 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1510 and child prompt and use self.runCmd() to run the hooks one by one.
1511
Johnny Chena737ba52011-10-19 01:06:21 +00001512 Note that child is a process spawned by pexpect.spawn(). If not, your
1513 test case is mostly likely going to fail.
1514
1515 See also dotest.py where lldb.runHooks are processed/populated.
1516 """
1517 if not lldb.runHooks:
1518 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001519 if use_cmd_api:
1520 for hook in lldb.runhooks:
1521 self.runCmd(hook)
1522 else:
1523 if not child or not child_prompt:
1524 self.fail("Both child and child_prompt need to be defined.")
1525 for hook in lldb.runHooks:
1526 child.sendline(hook)
1527 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001528
Daniel Malea249287a2013-02-19 16:08:57 +00001529 def setAsync(self, value):
1530 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1531 old_async = self.dbg.GetAsync()
1532 self.dbg.SetAsync(value)
1533 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1534
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001535 def cleanupSubprocesses(self):
1536 # Ensure any subprocesses are cleaned up
1537 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001538 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001539 del p
1540 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001541 # Ensure any forked processes are cleaned up
1542 for pid in self.forkedProcessPids:
1543 if os.path.exists("/proc/" + str(pid)):
1544 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001545
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001546 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001547 """ Creates a subprocess.Popen object with the specified executable and arguments,
1548 saves it in self.subprocesses, and returns the object.
1549 NOTE: if using this function, ensure you also call:
1550
1551 self.addTearDownHook(self.cleanupSubprocesses)
1552
1553 otherwise the test suite will leak processes.
1554 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001555 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001556 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001557 self.subprocesses.append(proc)
1558 return proc
1559
Daniel Malea69207462013-06-05 21:07:02 +00001560 def forkSubprocess(self, executable, args=[]):
1561 """ Fork a subprocess with its own group ID.
1562 NOTE: if using this function, ensure you also call:
1563
1564 self.addTearDownHook(self.cleanupSubprocesses)
1565
1566 otherwise the test suite will leak processes.
1567 """
1568 child_pid = os.fork()
1569 if child_pid == 0:
1570 # If more I/O support is required, this can be beefed up.
1571 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001572 os.dup2(fd, 1)
1573 os.dup2(fd, 2)
1574 # This call causes the child to have its of group ID
1575 os.setpgid(0,0)
1576 os.execvp(executable, [executable] + args)
1577 # Give the child time to get through the execvp() call
1578 time.sleep(0.1)
1579 self.forkedProcessPids.append(child_pid)
1580 return child_pid
1581
Johnny Chenfb4264c2011-08-01 19:50:58 +00001582 def HideStdout(self):
1583 """Hide output to stdout from the user.
1584
1585 During test execution, there might be cases where we don't want to show the
1586 standard output to the user. For example,
1587
Zachary Turner35d017f2015-10-23 17:04:29 +00001588 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001589
1590 tests whether command abbreviation for 'script' works or not. There is no
1591 need to show the 'Hello' output to the user as long as the 'script' command
1592 succeeds and we are not in TraceOn() mode (see the '-t' option).
1593
1594 In this case, the test method calls self.HideStdout(self) to redirect the
1595 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1596
1597 Note that you should only call this method at most once during a test case
1598 execution. Any subsequent call has no effect at all."""
1599 if self.sys_stdout_hidden:
1600 return
1601
1602 self.sys_stdout_hidden = True
1603 old_stdout = sys.stdout
1604 sys.stdout = open(os.devnull, 'w')
1605 def restore_stdout():
1606 sys.stdout = old_stdout
1607 self.addTearDownHook(restore_stdout)
1608
1609 # =======================================================================
1610 # Methods for customized teardown cleanups as well as execution of hooks.
1611 # =======================================================================
1612
1613 def setTearDownCleanup(self, dictionary=None):
1614 """Register a cleanup action at tearDown() time with a dictinary"""
1615 self.dict = dictionary
1616 self.doTearDownCleanup = True
1617
1618 def addTearDownCleanup(self, dictionary):
1619 """Add a cleanup action at tearDown() time with a dictinary"""
1620 self.dicts.append(dictionary)
1621 self.doTearDownCleanups = True
1622
1623 def addTearDownHook(self, hook):
1624 """
1625 Add a function to be run during tearDown() time.
1626
1627 Hooks are executed in a first come first serve manner.
1628 """
Zachary Turnercd236b82015-10-26 18:48:24 +00001629 if six.callable(hook):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001630 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001631 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001632 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001633
1634 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001635
Jim Inghamda3a3862014-10-16 23:02:14 +00001636 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001637 # This is for the case of directly spawning 'lldb' and interacting with it
1638 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001639 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001640 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001641 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001642 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001643 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001644 if self.child_in_script_interpreter:
1645 self.child.sendline('quit()')
1646 self.child.expect_exact(self.child_prompt)
1647 self.child.sendline('settings set interpreter.prompt-on-quit false')
1648 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001649 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001650 except (ValueError, pexpect.ExceptionPexpect):
1651 # child is already terminated
1652 pass
1653 except OSError as exception:
1654 import errno
1655 if exception.errno != errno.EIO:
1656 # unexpected error
1657 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001658 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001659 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001660 finally:
1661 # Give it one final blow to make sure the child is terminated.
1662 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001663
1664 def tearDown(self):
1665 """Fixture for unittest test case teardown."""
1666 #import traceback
1667 #traceback.print_stack()
1668
1669 self.deletePexpectChild()
1670
Johnny Chenfb4264c2011-08-01 19:50:58 +00001671 # Check and run any hook functions.
1672 for hook in reversed(self.hooks):
1673 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001674 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001675 import inspect
1676 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001677 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001678 hook()
1679 elif hook_argc == 1:
1680 hook(self)
1681 else:
1682 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001683
1684 del self.hooks
1685
1686 # Perform registered teardown cleanup.
1687 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001688 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001689
1690 # In rare cases where there are multiple teardown cleanups added.
1691 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001692 if self.dicts:
1693 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001694 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001695
Vince Harron9753dd92015-05-10 15:22:09 +00001696 self.disableLogChannelsForCurrentTest()
1697
Johnny Chenfb4264c2011-08-01 19:50:58 +00001698 # =========================================================
1699 # Various callbacks to allow introspection of test progress
1700 # =========================================================
1701
1702 def markError(self):
1703 """Callback invoked when an error (unexpected exception) errored."""
1704 self.__errored__ = True
1705 with recording(self, False) as sbuf:
1706 # False because there's no need to write "ERROR" to the stderr twice.
1707 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001708 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001709
Zachary Turnerb1490b62015-08-26 19:44:56 +00001710 def markCleanupError(self):
1711 """Callback invoked when an error occurs while a test is cleaning up."""
1712 self.__cleanup_errored__ = True
1713 with recording(self, False) as sbuf:
1714 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1715 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001716 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001717
Johnny Chenfb4264c2011-08-01 19:50:58 +00001718 def markFailure(self):
1719 """Callback invoked when a failure (test assertion failure) occurred."""
1720 self.__failed__ = True
1721 with recording(self, False) as sbuf:
1722 # False because there's no need to write "FAIL" to the stderr twice.
1723 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001724 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001725
Enrico Granatae6cedc12013-02-23 01:05:23 +00001726 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001727 """Callback invoked when an expected failure/error occurred."""
1728 self.__expected__ = True
1729 with recording(self, False) as sbuf:
1730 # False because there's no need to write "expected failure" to the
1731 # stderr twice.
1732 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001733 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001734 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001735 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001736 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001737
Johnny Chenc5cc6252011-08-15 23:09:08 +00001738 def markSkippedTest(self):
1739 """Callback invoked when a test is skipped."""
1740 self.__skipped__ = True
1741 with recording(self, False) as sbuf:
1742 # False because there's no need to write "skipped test" to the
1743 # stderr twice.
1744 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001745 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001746
Enrico Granatae6cedc12013-02-23 01:05:23 +00001747 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001748 """Callback invoked when an unexpected success occurred."""
1749 self.__unexpected__ = True
1750 with recording(self, False) as sbuf:
1751 # False because there's no need to write "unexpected success" to the
1752 # stderr twice.
1753 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001754 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001755 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001756 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001757 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001758
Greg Clayton70995582015-01-07 22:25:50 +00001759 def getRerunArgs(self):
1760 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001761
1762 def getLogBasenameForCurrentTest(self, prefix=None):
1763 """
1764 returns a partial path that can be used as the beginning of the name of multiple
1765 log files pertaining to this test
1766
1767 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1768 """
1769 dname = os.path.join(os.environ["LLDB_TEST"],
1770 os.environ["LLDB_SESSION_DIRNAME"])
1771 if not os.path.isdir(dname):
1772 os.mkdir(dname)
1773
1774 compiler = self.getCompiler()
1775
1776 if compiler[1] == ':':
1777 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001778 if os.path.altsep is not None:
1779 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001780
Vince Harron19e300f2015-05-12 00:50:54 +00001781 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001782 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001783 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001784
1785 if prefix is not None:
1786 fname = "{}-{}".format(prefix, fname)
1787
1788 return os.path.join(dname, fname)
1789
Johnny Chenfb4264c2011-08-01 19:50:58 +00001790 def dumpSessionInfo(self):
1791 """
1792 Dump the debugger interactions leading to a test error/failure. This
1793 allows for more convenient postmortem analysis.
1794
1795 See also LLDBTestResult (dotest.py) which is a singlton class derived
1796 from TextTestResult and overwrites addError, addFailure, and
1797 addExpectedFailure methods to allow us to to mark the test instance as
1798 such.
1799 """
1800
1801 # We are here because self.tearDown() detected that this test instance
1802 # either errored or failed. The lldb.test_result singleton contains
1803 # two lists (erros and failures) which get populated by the unittest
1804 # framework. Look over there for stack trace information.
1805 #
1806 # The lists contain 2-tuples of TestCase instances and strings holding
1807 # formatted tracebacks.
1808 #
1809 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001810
Vince Harron35b17dc2015-05-21 18:20:21 +00001811 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001812 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001813 if self.__errored__:
1814 pairs = lldb.test_result.errors
1815 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001816 elif self.__cleanup_errored__:
Zachary Turnerb1490b62015-08-26 19:44:56 +00001817 pairs = lldb.test_result.cleanup_errors
1818 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001819 elif self.__failed__:
1820 pairs = lldb.test_result.failures
1821 prefix = 'Failure'
1822 elif self.__expected__:
1823 pairs = lldb.test_result.expectedFailures
1824 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001825 elif self.__skipped__:
1826 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001827 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001828 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001829 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001830 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001831
Johnny Chenc5cc6252011-08-15 23:09:08 +00001832 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001833 for test, traceback in pairs:
1834 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001835 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001836
Vince Harron35b17dc2015-05-21 18:20:21 +00001837 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001838 testMethod = getattr(self, self._testMethodName)
1839 if getattr(testMethod, "__benchmarks_test__", False):
1840 benchmarks = True
1841 else:
1842 benchmarks = False
1843
Vince Harron35b17dc2015-05-21 18:20:21 +00001844 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001845 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1846 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1847 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001848 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001849 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001850 self.session.close()
1851 del self.session
1852
1853 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001854 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001855
1856 if prefix != 'Success' or lldbtest_config.log_success:
1857 # keep all log files, rename them to include prefix
1858 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1859 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001860 if os.path.isfile(src):
1861 dst = src.replace(self.log_basename, dst_log_basename)
1862 if os.name == "nt" and os.path.isfile(dst):
1863 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1864 # it silently replaces the destination. Ultimately this means that atomic renames are not
1865 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1866 # destination first if it already exists.
1867 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001868
Zachary Turner306278f2015-05-26 20:26:29 +00001869 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001870 else:
1871 # success! (and we don't want log files) delete log files
1872 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001873 try:
1874 os.unlink(log_file)
1875 except:
1876 # We've seen consistent unlink failures on Windows, perhaps because the
1877 # just-created log file is being scanned by anti-virus. Empirically, this
1878 # sleep-and-retry approach allows tests to succeed much more reliably.
1879 # Attempts to figure out exactly what process was still holding a file handle
1880 # have failed because running instrumentation like Process Monitor seems to
1881 # slow things down enough that the problem becomes much less consistent.
1882 time.sleep(0.5)
1883 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001884
1885 # ====================================================
1886 # Config. methods supported through a plugin interface
1887 # (enables reading of the current test configuration)
1888 # ====================================================
1889
1890 def getArchitecture(self):
1891 """Returns the architecture in effect the test suite is running with."""
1892 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001893 arch = module.getArchitecture()
1894 if arch == 'amd64':
1895 arch = 'x86_64'
1896 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001897
Vince Harron02613762015-05-04 00:17:53 +00001898 def getLldbArchitecture(self):
1899 """Returns the architecture of the lldb binary."""
1900 if not hasattr(self, 'lldbArchitecture'):
1901
1902 # spawn local process
1903 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001904 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001905 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001906 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001907 "-o",
1908 "quit"
1909 ]
1910
1911 output = check_output(command)
1912 str = output.decode("utf-8");
1913
1914 for line in str.splitlines():
1915 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1916 if m:
1917 self.lldbArchitecture = m.group(1)
1918 break
1919
1920 return self.lldbArchitecture
1921
Johnny Chenfb4264c2011-08-01 19:50:58 +00001922 def getCompiler(self):
1923 """Returns the compiler in effect the test suite is running with."""
1924 module = builder_module()
1925 return module.getCompiler()
1926
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001927 def getCompilerBinary(self):
1928 """Returns the compiler binary the test suite is running with."""
1929 return self.getCompiler().split()[0]
1930
Daniel Malea0aea0162013-02-27 17:29:46 +00001931 def getCompilerVersion(self):
1932 """ Returns a string that represents the compiler version.
1933 Supports: llvm, clang.
1934 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00001935 from .lldbutil import which
Daniel Malea0aea0162013-02-27 17:29:46 +00001936 version = 'unknown'
1937
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001938 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001939 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001940 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001941 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001942 if m:
1943 version = m.group(1)
1944 return version
1945
Ryan Brown57bee1e2015-09-14 22:45:11 +00001946 def getGoCompilerVersion(self):
1947 """ Returns a string that represents the go compiler version, or None if go is not found.
1948 """
1949 compiler = which("go")
1950 if compiler:
1951 version_output = system([[compiler, "version"]])[0]
1952 for line in version_output.split(os.linesep):
1953 m = re.search('go version (devel|go\\S+)', line)
1954 if m:
1955 return m.group(1)
1956 return None
1957
Greg Claytone0d0a762015-04-02 18:24:03 +00001958 def platformIsDarwin(self):
1959 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00001960 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00001961
Robert Flack13c7ad92015-03-30 14:12:17 +00001962 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00001963 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001964 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00001965
Daniel Maleaadaaec92013-08-06 20:51:41 +00001966 def isIntelCompiler(self):
1967 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1968 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1969
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001970 def expectedCompilerVersion(self, compiler_version):
1971 """Returns True iff compiler_version[1] matches the current compiler version.
1972 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1973 Any operator other than the following defaults to an equality test:
1974 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1975 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001976 if (compiler_version == None):
1977 return True
1978 operator = str(compiler_version[0])
1979 version = compiler_version[1]
1980
1981 if (version == None):
1982 return True
1983 if (operator == '>'):
1984 return self.getCompilerVersion() > version
1985 if (operator == '>=' or operator == '=>'):
1986 return self.getCompilerVersion() >= version
1987 if (operator == '<'):
1988 return self.getCompilerVersion() < version
1989 if (operator == '<=' or operator == '=<'):
1990 return self.getCompilerVersion() <= version
1991 if (operator == '!=' or operator == '!' or operator == 'not'):
1992 return str(version) not in str(self.getCompilerVersion())
1993 return str(version) in str(self.getCompilerVersion())
1994
1995 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001996 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001997 if (compilers == None):
1998 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001999
2000 for compiler in compilers:
2001 if compiler in self.getCompiler():
2002 return True
2003
2004 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00002005
Ying Chen7091c2c2015-04-21 01:15:47 +00002006 def expectedArch(self, archs):
2007 """Returns True iff any element of archs is a sub-string of the current architecture."""
2008 if (archs == None):
2009 return True
2010
2011 for arch in archs:
2012 if arch in self.getArchitecture():
2013 return True
2014
2015 return False
2016
Johnny Chenfb4264c2011-08-01 19:50:58 +00002017 def getRunOptions(self):
2018 """Command line option for -A and -C to run this test again, called from
2019 self.dumpSessionInfo()."""
2020 arch = self.getArchitecture()
2021 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00002022 if arch:
2023 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00002024 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00002025 option_str = ""
2026 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00002027 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00002028 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00002029
2030 # ==================================================
2031 # Build methods supported through a plugin interface
2032 # ==================================================
2033
Ed Mastec97323e2014-04-01 18:47:58 +00002034 def getstdlibFlag(self):
2035 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00002036 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00002037 stdlibflag = "-stdlib=libc++"
2038 else:
2039 stdlibflag = ""
2040 return stdlibflag
2041
Matt Kopec7663b3a2013-09-25 17:44:00 +00002042 def getstdFlag(self):
2043 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002044 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002045 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002046 else:
2047 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002048 return stdflag
2049
2050 def buildDriver(self, sources, exe_name):
2051 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2052 or LLDB.framework).
2053 """
2054
2055 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002056 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002057
2058 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002059 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002060 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002061 d = {'CXX_SOURCES' : sources,
2062 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002063 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002064 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2065 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002066 }
Ed Maste372c24d2013-07-25 21:02:34 +00002067 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002068 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002069 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002070 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002071 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002072 elif sys.platform.startswith('win'):
2073 d = {'CXX_SOURCES' : sources,
2074 'EXE' : exe_name,
2075 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002076 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002077 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002078 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002079
2080 self.buildDefault(dictionary=d)
2081
Matt Kopec7663b3a2013-09-25 17:44:00 +00002082 def buildLibrary(self, sources, lib_name):
2083 """Platform specific way to build a default library. """
2084
2085 stdflag = self.getstdFlag()
2086
Greg Clayton22fd3b12015-10-26 17:52:16 +00002087 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002088 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002089 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002090 d = {'DYLIB_CXX_SOURCES' : sources,
2091 'DYLIB_NAME' : lib_name,
2092 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002093 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2094 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002095 }
Robert Flack4629c4b2015-05-15 18:54:32 +00002096 elif self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux' or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002097 d = {'DYLIB_CXX_SOURCES' : sources,
2098 'DYLIB_NAME' : lib_name,
2099 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002100 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002101 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002102 d = {'DYLIB_CXX_SOURCES' : sources,
2103 'DYLIB_NAME' : lib_name,
2104 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002105 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002106 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002107 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002108
2109 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002110
Daniel Malea55faa402013-05-02 21:44:31 +00002111 def buildProgram(self, sources, exe_name):
2112 """ Platform specific way to build an executable from C/C++ sources. """
2113 d = {'CXX_SOURCES' : sources,
2114 'EXE' : exe_name}
2115 self.buildDefault(dictionary=d)
2116
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002117 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002118 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002119 if lldb.skip_build_and_cleanup:
2120 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002121 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002122 if target_is_android():
2123 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002124 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002125 raise Exception("Don't know how to build default binary")
2126
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002127 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002128 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002129 if lldb.skip_build_and_cleanup:
2130 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002131 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002132 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002133 raise Exception("Don't know how to build binary with dsym")
2134
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002135 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002136 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002137 if lldb.skip_build_and_cleanup:
2138 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002139 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002140 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002141 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002142 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002143 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002144
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002145 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2146 """Platform specific way to build binaries with dwarf maps."""
2147 if lldb.skip_build_and_cleanup:
2148 return
2149 module = builder_module()
2150 if target_is_android():
2151 dictionary = append_android_envs(dictionary)
2152 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2153 raise Exception("Don't know how to build binary with dwo")
2154
Ryan Brown57bee1e2015-09-14 22:45:11 +00002155 def buildGo(self):
2156 """Build the default go binary.
2157 """
2158 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2159
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002160 def signBinary(self, binary_path):
2161 if sys.platform.startswith("darwin"):
2162 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2163 call(codesign_cmd, shell=True)
2164
Kuba Breckabeed8212014-09-04 01:03:18 +00002165 def findBuiltClang(self):
2166 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2167 paths_to_try = [
2168 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2169 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2170 "llvm-build/Release/x86_64/Release/bin/clang",
2171 "llvm-build/Debug/x86_64/Debug/bin/clang",
2172 ]
2173 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
2174 for p in paths_to_try:
2175 path = os.path.join(lldb_root_path, p)
2176 if os.path.exists(path):
2177 return path
Ilia Kd9953052015-03-12 07:19:41 +00002178
2179 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002180 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002181 if os.path.exists(path):
2182 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002183
2184 return os.environ["CC"]
2185
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002186 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002187 """ Returns a dictionary (which can be provided to build* functions above) which
2188 contains OS-specific build flags.
2189 """
2190 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002191 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002192
2193 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002194 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002195 use_libcxx = True
2196
2197 if use_libcxx and self.libcxxPath:
2198 cflags += "-stdlib=libc++ "
2199 if self.libcxxPath:
2200 libcxxInclude = os.path.join(self.libcxxPath, "include")
2201 libcxxLib = os.path.join(self.libcxxPath, "lib")
2202 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2203 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2204
Andrew Kaylor93132f52013-05-28 23:04:25 +00002205 if use_cpp11:
2206 cflags += "-std="
2207 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2208 cflags += "c++0x"
2209 else:
2210 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002211 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002212 cflags += " -stdlib=libc++"
2213 elif "clang" in self.getCompiler():
2214 cflags += " -stdlib=libstdc++"
2215
Andrew Kaylor93132f52013-05-28 23:04:25 +00002216 return {'CFLAGS_EXTRAS' : cflags,
2217 'LD_EXTRAS' : ldflags,
2218 }
2219
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002220 def cleanup(self, dictionary=None):
2221 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002222 if lldb.skip_build_and_cleanup:
2223 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002224 module = builder_module()
2225 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002226 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002227
Daniel Malea55faa402013-05-02 21:44:31 +00002228 def getLLDBLibraryEnvVal(self):
2229 """ Returns the path that the OS-specific library search environment variable
2230 (self.dylibPath) should be set to in order for a program to find the LLDB
2231 library. If an environment variable named self.dylibPath is already set,
2232 the new path is appended to it and returned.
2233 """
2234 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002235 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002236 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002237 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002238 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002239 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002240 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002241 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002242
Ed Maste437f8f62013-09-09 14:04:04 +00002243 def getLibcPlusPlusLibs(self):
Robert Flackfa5ad652015-05-13 20:17:34 +00002244 if self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux':
Ed Maste437f8f62013-09-09 14:04:04 +00002245 return ['libc++.so.1']
2246 else:
2247 return ['libc++.1.dylib','libc++abi.dylib']
2248
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002249# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2250# We change the test methods to create a new test method for each test for each debug info we are
2251# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2252# the new test method we remove the old method at the same time.
2253class LLDBTestCaseFactory(type):
2254 def __new__(cls, name, bases, attrs):
2255 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002256 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002257 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2258 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002259 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002260 def dsym_test_method(self, attrvalue=attrvalue):
2261 self.debug_info = "dsym"
2262 return attrvalue(self)
2263 dsym_method_name = attrname + "_dsym"
2264 dsym_test_method.__name__ = dsym_method_name
2265 newattrs[dsym_method_name] = dsym_test_method
2266
2267 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002268 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002269 def dwarf_test_method(self, attrvalue=attrvalue):
2270 self.debug_info = "dwarf"
2271 return attrvalue(self)
2272 dwarf_method_name = attrname + "_dwarf"
2273 dwarf_test_method.__name__ = dwarf_method_name
2274 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002275
2276 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002277 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002278 def dwo_test_method(self, attrvalue=attrvalue):
2279 self.debug_info = "dwo"
2280 return attrvalue(self)
2281 dwo_method_name = attrname + "_dwo"
2282 dwo_test_method.__name__ = dwo_method_name
2283 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002284 else:
2285 newattrs[attrname] = attrvalue
2286 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2287
Zachary Turner43a01e42015-10-20 21:06:05 +00002288# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2289@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002290class TestBase(Base):
2291 """
2292 This abstract base class is meant to be subclassed. It provides default
2293 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2294 among other things.
2295
2296 Important things for test class writers:
2297
2298 - Overwrite the mydir class attribute, otherwise your test class won't
2299 run. It specifies the relative directory to the top level 'test' so
2300 the test harness can change to the correct working directory before
2301 running your test.
2302
2303 - The setUp method sets up things to facilitate subsequent interactions
2304 with the debugger as part of the test. These include:
2305 - populate the test method name
2306 - create/get a debugger set with synchronous mode (self.dbg)
2307 - get the command interpreter from with the debugger (self.ci)
2308 - create a result object for use with the command interpreter
2309 (self.res)
2310 - plus other stuffs
2311
2312 - The tearDown method tries to perform some necessary cleanup on behalf
2313 of the test to return the debugger to a good state for the next test.
2314 These include:
2315 - execute any tearDown hooks registered by the test method with
2316 TestBase.addTearDownHook(); examples can be found in
2317 settings/TestSettings.py
2318 - kill the inferior process associated with each target, if any,
2319 and, then delete the target from the debugger's target list
2320 - perform build cleanup before running the next test method in the
2321 same test class; examples of registering for this service can be
2322 found in types/TestIntegerTypes.py with the call:
2323 - self.setTearDownCleanup(dictionary=d)
2324
2325 - Similarly setUpClass and tearDownClass perform classwise setup and
2326 teardown fixtures. The tearDownClass method invokes a default build
2327 cleanup for the entire test class; also, subclasses can implement the
2328 classmethod classCleanup(cls) to perform special class cleanup action.
2329
2330 - The instance methods runCmd and expect are used heavily by existing
2331 test cases to send a command to the command interpreter and to perform
2332 string/pattern matching on the output of such command execution. The
2333 expect method also provides a mode to peform string/pattern matching
2334 without running a command.
2335
2336 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2337 build the binaries used during a particular test scenario. A plugin
2338 should be provided for the sys.platform running the test suite. The
2339 Mac OS X implementation is located in plugins/darwin.py.
2340 """
2341
2342 # Maximum allowed attempts when launching the inferior process.
2343 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2344 maxLaunchCount = 3;
2345
2346 # Time to wait before the next launching attempt in second(s).
2347 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2348 timeWaitNextLaunch = 1.0;
2349
2350 def doDelay(self):
2351 """See option -w of dotest.py."""
2352 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
2353 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
2354 waitTime = 1.0
2355 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
2356 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
2357 time.sleep(waitTime)
2358
Enrico Granata165f8af2012-09-21 19:10:53 +00002359 # Returns the list of categories to which this test case belongs
2360 # by default, look for a ".categories" file, and read its contents
2361 # if no such file exists, traverse the hierarchy - we guarantee
2362 # a .categories to exist at the top level directory so we do not end up
2363 # looping endlessly - subclasses are free to define their own categories
2364 # in whatever way makes sense to them
2365 def getCategories(self):
2366 import inspect
2367 import os.path
2368 folder = inspect.getfile(self.__class__)
2369 folder = os.path.dirname(folder)
2370 while folder != '/':
2371 categories_file_name = os.path.join(folder,".categories")
2372 if os.path.exists(categories_file_name):
2373 categories_file = open(categories_file_name,'r')
2374 categories = categories_file.readline()
2375 categories_file.close()
2376 categories = str.replace(categories,'\n','')
2377 categories = str.replace(categories,'\r','')
2378 return categories.split(',')
2379 else:
2380 folder = os.path.dirname(folder)
2381 continue
2382
Johnny Chena74bb0a2011-08-01 18:46:13 +00002383 def setUp(self):
2384 #import traceback
2385 #traceback.print_stack()
2386
2387 # Works with the test driver to conditionally skip tests via decorators.
2388 Base.setUp(self)
2389
Johnny Chena74bb0a2011-08-01 18:46:13 +00002390 try:
2391 if lldb.blacklist:
2392 className = self.__class__.__name__
2393 classAndMethodName = "%s.%s" % (className, self._testMethodName)
2394 if className in lldb.blacklist:
2395 self.skipTest(lldb.blacklist.get(className))
2396 elif classAndMethodName in lldb.blacklist:
2397 self.skipTest(lldb.blacklist.get(classAndMethodName))
2398 except AttributeError:
2399 pass
2400
Johnny Chened492022011-06-21 00:53:00 +00002401 # Insert some delay between successive test cases if specified.
2402 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00002403
Johnny Chenf2b70232010-08-25 18:49:48 +00002404 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2405 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2406
Johnny Chen430eb762010-10-19 16:00:42 +00002407 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002408 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002409
Daniel Maleae0f8f572013-08-26 23:57:52 +00002410 #
2411 # Warning: MAJOR HACK AHEAD!
2412 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
2413 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
2414 # command, instead. See also runCmd() where it decorates the "file filename" call
2415 # with additional functionality when running testsuite remotely.
2416 #
2417 if lldb.lldbtest_remote_sandbox:
2418 def DecoratedCreateTarget(arg):
2419 self.runCmd("file %s" % arg)
2420 target = self.dbg.GetSelectedTarget()
2421 #
Greg Claytonc6947512013-12-13 19:18:59 +00002422 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00002423 # johnny @ 04/23/2012
2424 #
2425 def DecoratedLaunchSimple(argv, envp, wd):
2426 self.runCmd("run")
2427 return target.GetProcess()
2428 target.LaunchSimple = DecoratedLaunchSimple
2429
2430 return target
2431 self.dbg.CreateTarget = DecoratedCreateTarget
2432 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002433 print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
Daniel Maleae0f8f572013-08-26 23:57:52 +00002434
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002435 # We want our debugger to be synchronous.
2436 self.dbg.SetAsync(False)
2437
2438 # Retrieve the associated command interpreter instance.
2439 self.ci = self.dbg.GetCommandInterpreter()
2440 if not self.ci:
2441 raise Exception('Could not get the command interpreter')
2442
2443 # And the result object.
2444 self.res = lldb.SBCommandReturnObject()
2445
Johnny Chen44d24972012-04-16 18:55:15 +00002446 # Run global pre-flight code, if defined via the config file.
2447 if lldb.pre_flight:
2448 lldb.pre_flight(self)
2449
Enrico Granatabd0998a2015-10-02 22:53:32 +00002450 if lldb.remote_platform and lldb.remote_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002451 remote_test_dir = lldbutil.join_remote_paths(
2452 lldb.remote_platform_working_dir,
2453 self.getArchitecture(),
2454 str(self.test_number),
2455 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002456 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002457 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002458 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002459
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002460 # This function removes all files from the current working directory while leaving
2461 # the directories in place. The cleaup is required to reduce the disk space required
2462 # by the test suit while leaving the directories untached is neccessary because
2463 # sub-directories might belong to an other test
2464 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002465 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002466 # TODO: Replace the heuristic to remove the files with a logic what collects the
2467 # list of files we have to remove during test runs.
2468 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002469 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002470 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002471 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002472 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002473
Greg Clayton35c91342014-11-17 18:40:27 +00002474 def registerSharedLibrariesWithTarget(self, target, shlibs):
2475 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2476
2477 Any modules in the target that have their remote install file specification set will
2478 get uploaded to the remote host. This function registers the local copies of the
2479 shared libraries with the target and sets their remote install locations so they will
2480 be uploaded when the target is run.
2481 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002482 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002483 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002484
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002485 shlib_environment_var = self.platformContext.shlib_environment_var
2486 shlib_prefix = self.platformContext.shlib_prefix
2487 shlib_extension = '.' + self.platformContext.shlib_extension
2488
2489 working_dir = self.get_process_working_directory()
2490 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2491 # Add any shared libraries to our target if remote so they get
2492 # uploaded into the working directory on the remote side
2493 for name in shlibs:
2494 # The path can be a full path to a shared library, or a make file name like "Foo" for
2495 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2496 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2497 # of the shared library accordingly
2498 if os.path.exists(name):
2499 local_shlib_path = name # name is the full path to the local shared library
2500 else:
2501 # Check relative names
2502 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2503 if not os.path.exists(local_shlib_path):
2504 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002505 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002506 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002507
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002508 # Make sure we found the local shared library in the above code
2509 self.assertTrue(os.path.exists(local_shlib_path))
2510
2511 # Add the shared library to our target
2512 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2513 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002514 # We must set the remote install location if we want the shared library
2515 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002516 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002517 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002518
2519 return environment
2520
Enrico Granata44818162012-10-24 01:23:57 +00002521 # utility methods that tests can use to access the current objects
2522 def target(self):
2523 if not self.dbg:
2524 raise Exception('Invalid debugger instance')
2525 return self.dbg.GetSelectedTarget()
2526
2527 def process(self):
2528 if not self.dbg:
2529 raise Exception('Invalid debugger instance')
2530 return self.dbg.GetSelectedTarget().GetProcess()
2531
2532 def thread(self):
2533 if not self.dbg:
2534 raise Exception('Invalid debugger instance')
2535 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2536
2537 def frame(self):
2538 if not self.dbg:
2539 raise Exception('Invalid debugger instance')
2540 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2541
Greg Claytonc6947512013-12-13 19:18:59 +00002542 def get_process_working_directory(self):
2543 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2544 if lldb.remote_platform:
2545 # Remote tests set the platform working directory up in TestBase.setUp()
2546 return lldb.remote_platform.GetWorkingDirectory()
2547 else:
2548 # local tests change directory into each test subdirectory
2549 return os.getcwd()
2550
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002551 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002552 #import traceback
2553 #traceback.print_stack()
2554
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002555 # Ensure all the references to SB objects have gone away so that we can
2556 # be sure that all test-specific resources have been freed before we
2557 # attempt to delete the targets.
2558 gc.collect()
2559
Johnny Chen3794ad92011-06-15 21:24:24 +00002560 # Delete the target(s) from the debugger as a general cleanup step.
2561 # This includes terminating the process for each target, if any.
2562 # We'd like to reuse the debugger for our next test without incurring
2563 # the initialization overhead.
2564 targets = []
2565 for target in self.dbg:
2566 if target:
2567 targets.append(target)
2568 process = target.GetProcess()
2569 if process:
2570 rc = self.invoke(process, "Kill")
2571 self.assertTrue(rc.Success(), PROCESS_KILLED)
2572 for target in targets:
2573 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002574
Johnny Chen44d24972012-04-16 18:55:15 +00002575 # Run global post-flight code, if defined via the config file.
2576 if lldb.post_flight:
2577 lldb.post_flight(self)
2578
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002579 # Do this last, to make sure it's in reverse order from how we setup.
2580 Base.tearDown(self)
2581
Zachary Turner95812042015-03-26 18:54:21 +00002582 # This must be the last statement, otherwise teardown hooks or other
2583 # lines might depend on this still being active.
2584 del self.dbg
2585
Johnny Chen86268e42011-09-30 21:48:35 +00002586 def switch_to_thread_with_stop_reason(self, stop_reason):
2587 """
2588 Run the 'thread list' command, and select the thread with stop reason as
2589 'stop_reason'. If no such thread exists, no select action is done.
2590 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002591 from .lldbutil import stop_reason_to_str
Johnny Chen86268e42011-09-30 21:48:35 +00002592 self.runCmd('thread list')
2593 output = self.res.GetOutput()
2594 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2595 stop_reason_to_str(stop_reason))
2596 for line in output.splitlines():
2597 matched = thread_line_pattern.match(line)
2598 if matched:
2599 self.runCmd('thread select %s' % matched.group(1))
2600
Enrico Granata7594f142013-06-17 22:51:50 +00002601 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002602 """
2603 Ask the command interpreter to handle the command and then check its
2604 return status.
2605 """
2606 # Fail fast if 'cmd' is not meaningful.
2607 if not cmd or len(cmd) == 0:
2608 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002609
Johnny Chen8d55a342010-08-31 17:42:54 +00002610 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002611
Daniel Maleae0f8f572013-08-26 23:57:52 +00002612 # This is an opportunity to insert the 'platform target-install' command if we are told so
2613 # via the settig of lldb.lldbtest_remote_sandbox.
2614 if cmd.startswith("target create "):
2615 cmd = cmd.replace("target create ", "file ")
2616 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
2617 with recording(self, trace) as sbuf:
2618 the_rest = cmd.split("file ")[1]
2619 # Split the rest of the command line.
2620 atoms = the_rest.split()
2621 #
2622 # NOTE: This assumes that the options, if any, follow the file command,
2623 # instead of follow the specified target.
2624 #
2625 target = atoms[-1]
2626 # Now let's get the absolute pathname of our target.
2627 abs_target = os.path.abspath(target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002628 print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002629 fpath, fname = os.path.split(abs_target)
2630 parent_dir = os.path.split(fpath)[0]
2631 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
Zachary Turnerff890da2015-10-19 23:45:41 +00002632 print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002633 self.ci.HandleCommand(platform_target_install_command, self.res)
2634 # And this is the file command we want to execute, instead.
2635 #
2636 # Warning: SIDE EFFECT AHEAD!!!
2637 # Populate the remote executable pathname into the lldb namespace,
2638 # so that test cases can grab this thing out of the namespace.
2639 #
2640 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
2641 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002642 print("And this is the replaced file command: %s" % cmd, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002643
Johnny Chen63dfb272010-09-01 00:15:19 +00002644 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002645
Johnny Chen63dfb272010-09-01 00:15:19 +00002646 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002647 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002648
Johnny Chen150c3cc2010-10-15 01:18:29 +00002649 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002650 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002651 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002652 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002653 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002654 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002655 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002656 print("runCmd failed!", file=sbuf)
2657 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002658
Johnny Chenff3d01d2010-08-20 21:03:09 +00002659 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002660 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002661 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002662 # For process launch, wait some time before possible next try.
2663 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002664 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002665 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002666
Johnny Chen27f212d2010-08-19 23:26:59 +00002667 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002668 self.assertTrue(self.res.Succeeded(),
2669 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002670
Jim Ingham63dfc722012-09-22 00:05:11 +00002671 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2672 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2673
2674 Otherwise, all the arguments have the same meanings as for the expect function"""
2675
2676 trace = (True if traceAlways else trace)
2677
2678 if exe:
2679 # First run the command. If we are expecting error, set check=False.
2680 # Pass the assert message along since it provides more semantic info.
2681 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2682
2683 # Then compare the output against expected strings.
2684 output = self.res.GetError() if error else self.res.GetOutput()
2685
2686 # If error is True, the API client expects the command to fail!
2687 if error:
2688 self.assertFalse(self.res.Succeeded(),
2689 "Command '" + str + "' is expected to fail!")
2690 else:
2691 # No execution required, just compare str against the golden input.
2692 output = str
2693 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002694 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002695
2696 # The heading says either "Expecting" or "Not expecting".
2697 heading = "Expecting" if matching else "Not expecting"
2698
2699 for pattern in patterns:
2700 # Match Objects always have a boolean value of True.
2701 match_object = re.search(pattern, output)
2702 matched = bool(match_object)
2703 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002704 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2705 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002706 if matched:
2707 break
2708
2709 self.assertTrue(matched if matching else not matched,
2710 msg if msg else EXP_MSG(str, exe))
2711
2712 return match_object
2713
Enrico Granata7594f142013-06-17 22:51:50 +00002714 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 +00002715 """
2716 Similar to runCmd; with additional expect style output matching ability.
2717
2718 Ask the command interpreter to handle the command and then check its
2719 return status. The 'msg' parameter specifies an informational assert
2720 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002721 'startstr', matches the substrings contained in 'substrs', and regexp
2722 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002723
2724 If the keyword argument error is set to True, it signifies that the API
2725 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002726 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002727 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002728
2729 If the keyword argument matching is set to False, it signifies that the API
2730 client is expecting the output of the command not to match the golden
2731 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002732
2733 Finally, the required argument 'str' represents the lldb command to be
2734 sent to the command interpreter. In case the keyword argument 'exe' is
2735 set to False, the 'str' is treated as a string to be matched/not-matched
2736 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002737 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002738 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002739
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002740 if exe:
2741 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002742 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002743 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002744
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002745 # Then compare the output against expected strings.
2746 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002747
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002748 # If error is True, the API client expects the command to fail!
2749 if error:
2750 self.assertFalse(self.res.Succeeded(),
2751 "Command '" + str + "' is expected to fail!")
2752 else:
2753 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002754 if isinstance(str,lldb.SBCommandReturnObject):
2755 output = str.GetOutput()
2756 else:
2757 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002758 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002759 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002760
Johnny Chenea88e942010-09-21 21:08:53 +00002761 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002762 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002763
2764 # Start from the startstr, if specified.
2765 # If there's no startstr, set the initial state appropriately.
2766 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002767
Johnny Chen150c3cc2010-10-15 01:18:29 +00002768 if startstr:
2769 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002770 print("%s start string: %s" % (heading, startstr), file=sbuf)
2771 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002772
Johnny Chen86268e42011-09-30 21:48:35 +00002773 # Look for endstr, if specified.
2774 keepgoing = matched if matching else not matched
2775 if endstr:
2776 matched = output.endswith(endstr)
2777 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002778 print("%s end string: %s" % (heading, endstr), file=sbuf)
2779 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002780
Johnny Chenea88e942010-09-21 21:08:53 +00002781 # Look for sub strings, if specified.
2782 keepgoing = matched if matching else not matched
2783 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002784 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002785 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002786 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002787 print("%s sub string: %s" % (heading, str), file=sbuf)
2788 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002789 keepgoing = matched if matching else not matched
2790 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002791 break
2792
Johnny Chenea88e942010-09-21 21:08:53 +00002793 # Search for regular expression patterns, if specified.
2794 keepgoing = matched if matching else not matched
2795 if patterns and keepgoing:
2796 for pattern in patterns:
2797 # Match Objects always have a boolean value of True.
2798 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002799 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002800 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2801 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002802 keepgoing = matched if matching else not matched
2803 if not keepgoing:
2804 break
Johnny Chenea88e942010-09-21 21:08:53 +00002805
2806 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002807 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002808
Johnny Chenf3c59232010-08-25 22:52:45 +00002809 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002810 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002811 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002812
2813 method = getattr(obj, name)
2814 import inspect
2815 self.assertTrue(inspect.ismethod(method),
2816 name + "is a method name of object: " + str(obj))
2817 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002818 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002819 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002820 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002821
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002822 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2823 """Platform specific way to build the default binaries."""
2824 if lldb.skip_build_and_cleanup:
2825 return
2826 module = builder_module()
2827 if target_is_android():
2828 dictionary = append_android_envs(dictionary)
2829 if self.debug_info is None:
2830 return self.buildDefault(architecture, compiler, dictionary, clean)
2831 elif self.debug_info == "dsym":
2832 return self.buildDsym(architecture, compiler, dictionary, clean)
2833 elif self.debug_info == "dwarf":
2834 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002835 elif self.debug_info == "dwo":
2836 return self.buildDwo(architecture, compiler, dictionary, clean)
2837 else:
2838 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002839
Johnny Chenf359cf22011-05-27 23:36:52 +00002840 # =================================================
2841 # Misc. helper methods for debugging test execution
2842 # =================================================
2843
Johnny Chen56b92a72011-07-11 19:15:11 +00002844 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002845 """Debug print a SBValue object, if traceAlways is True."""
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002846 from .lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002847
Johnny Chen8d55a342010-08-31 17:42:54 +00002848 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002849 return
2850
2851 err = sys.stderr
2852 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002853 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2854 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2855 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2856 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2857 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2858 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2859 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2860 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2861 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002862
Johnny Chen36c5eb12011-08-05 20:17:27 +00002863 def DebugSBType(self, type):
2864 """Debug print a SBType object, if traceAlways is True."""
2865 if not traceAlways:
2866 return
2867
2868 err = sys.stderr
2869 err.write(type.GetName() + ":\n")
2870 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2871 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2872 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2873
Johnny Chenb877f1e2011-03-12 01:18:19 +00002874 def DebugPExpect(self, child):
2875 """Debug the spwaned pexpect object."""
2876 if not traceAlways:
2877 return
2878
Zachary Turnerff890da2015-10-19 23:45:41 +00002879 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002880
2881 @classmethod
2882 def RemoveTempFile(cls, file):
2883 if os.path.exists(file):
2884 os.remove(file)