blob: 787525af5d2f79fcab5440acbc3574b849a0508b [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
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +000040import gc
Vince Harron9753dd92015-05-10 15:22:09 +000041import glob
Johnny Chen90312a82010-09-21 22:34:45 +000042import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000043import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000044import re
Daniel Malea69207462013-06-05 21:07:02 +000045import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000046from subprocess import *
Johnny Chenf2b70232010-08-25 18:49:48 +000047import time
Johnny Chena33a93c2010-08-30 23:08:52 +000048import types
Zachary Turner43a01e42015-10-20 21:06:05 +000049
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000050# Third-party modules
51import unittest2
Zachary Turner43a01e42015-10-20 21:06:05 +000052from six import add_metaclass
Zachary Turner814236d2015-10-21 17:48:52 +000053from six import StringIO as SixStringIO
54from six.moves.urllib import parse as urlparse
Zachary Turnercd236b82015-10-26 18:48:24 +000055import six
Zachary Turnerc1b7cd72015-11-05 19:22:28 +000056
57# LLDB modules
58import lldb
59from . import lldbtest_config
60from . import lldbutil
61from . import test_categories
Siva Chandra8af91662015-06-05 00:22:49 +000062
Vince Harron85d19652015-05-21 19:09:29 +000063# dosep.py starts lots and lots of dotest instances
64# This option helps you find if two (or more) dotest instances are using the same
65# directory at the same time
66# Enable it to cause test failures and stderr messages if dotest instances try to run in
67# the same directory simultaneously
68# it is disabled by default because it litters the test directories with ".dirlock" files
69debug_confirm_directory_exclusivity = False
70
Johnny Chen707b3c92010-10-11 22:25:46 +000071# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000072# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000073
74# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000075if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
76 traceAlways = True
77else:
78 traceAlways = False
79
Johnny Chen707b3c92010-10-11 22:25:46 +000080# By default, doCleanup is True.
81if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
82 doCleanup = False
83else:
84 doCleanup = True
85
Johnny Chen8d55a342010-08-31 17:42:54 +000086
Johnny Chen00778092010-08-09 22:01:17 +000087#
88# Some commonly used assert messages.
89#
90
Johnny Chenaa902922010-09-17 22:45:27 +000091COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
92
Johnny Chen00778092010-08-09 22:01:17 +000093CURRENT_EXECUTABLE_SET = "Current executable set successfully"
94
Johnny Chen7d1d7532010-09-02 21:23:12 +000095PROCESS_IS_VALID = "Process is valid"
96
97PROCESS_KILLED = "Process is killed successfully"
98
Johnny Chend5f66fc2010-12-23 01:12:19 +000099PROCESS_EXITED = "Process exited successfully"
100
101PROCESS_STOPPED = "Process status should be stopped"
102
Sean Callanan05834cd2015-07-01 23:56:30 +0000103RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000104
Johnny Chen17941842010-08-09 23:44:24 +0000105RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000106
Johnny Chen67af43f2010-10-05 19:27:32 +0000107BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
108
Johnny Chen17941842010-08-09 23:44:24 +0000109BREAKPOINT_CREATED = "Breakpoint created successfully"
110
Johnny Chenf10af382010-12-04 00:07:24 +0000111BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
112
Johnny Chene76896c2010-08-17 21:33:31 +0000113BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
114
Johnny Chen17941842010-08-09 23:44:24 +0000115BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000116
Johnny Chen703dbd02010-09-30 17:06:24 +0000117BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
118
Johnny Chen164f1e12010-10-15 18:07:09 +0000119BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
120
Greg Clayton5db6b792012-10-24 18:24:14 +0000121MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
122
Johnny Chen89109ed12011-06-27 20:05:23 +0000123OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
124
Johnny Chen5b3a3572010-12-09 18:22:12 +0000125SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
126
Johnny Chenc70b02a2010-09-22 23:00:20 +0000127STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
128
Johnny Chen1691a162011-04-15 16:44:48 +0000129STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
130
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000131STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
132
Johnny Chen5d6c4642010-11-10 23:46:38 +0000133STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000134
Johnny Chen5d6c4642010-11-10 23:46:38 +0000135STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
136 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000137
Johnny Chen2e431ce2010-10-20 18:38:48 +0000138STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
139
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000140STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
141
Johnny Chenc066ab42010-10-14 01:22:03 +0000142STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
143
Johnny Chen00778092010-08-09 22:01:17 +0000144STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
145
Johnny Chenf68cc122011-09-15 21:09:59 +0000146STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
147
Johnny Chen3c884a02010-08-24 22:07:56 +0000148DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
149
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000150VALID_BREAKPOINT = "Got a valid breakpoint"
151
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000152VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
153
Johnny Chen7209d84f2011-05-06 23:26:12 +0000154VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
155
Johnny Chen5ee88192010-08-27 23:47:36 +0000156VALID_FILESPEC = "Got a valid filespec"
157
Johnny Chen025d1b82010-12-08 01:25:21 +0000158VALID_MODULE = "Got a valid module"
159
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000160VALID_PROCESS = "Got a valid process"
161
Johnny Chen025d1b82010-12-08 01:25:21 +0000162VALID_SYMBOL = "Got a valid symbol"
163
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000164VALID_TARGET = "Got a valid target"
165
Matthew Gardinerc928de32014-10-22 07:22:56 +0000166VALID_PLATFORM = "Got a valid platform"
167
Johnny Chen15f247a2012-02-03 20:43:00 +0000168VALID_TYPE = "Got a valid type"
169
Johnny Chen5819ab42011-07-15 22:28:10 +0000170VALID_VARIABLE = "Got a valid variable"
171
Johnny Chen981463d2010-08-25 19:00:04 +0000172VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000173
Johnny Chenf68cc122011-09-15 21:09:59 +0000174WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000175
Sean Callanan05834cd2015-07-01 23:56:30 +0000176def CMD_MSG(str):
177 '''A generic "Command '%s' returns successfully" message generator.'''
178 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000179
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000180def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000181 '''A generic message generator for the completion mechanism.'''
182 return "'%s' successfully completes to '%s'" % (str_before, str_after)
183
Johnny Chenc0c67f22010-11-09 18:42:22 +0000184def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000185 '''A generic "'%s' returns expected result" message generator if exe.
186 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000187 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000188
Johnny Chen3343f042010-10-19 19:11:38 +0000189def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000190 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000191 return "Value of setting '%s' is correct" % setting
192
Johnny Chen27c41232010-08-26 21:49:29 +0000193def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000194 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000195 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000196
Johnny Chen47ceb032010-10-11 23:52:19 +0000197def line_number(filename, string_to_match):
198 """Helper function to return the line number of the first matched string."""
199 with open(filename, 'r') as f:
200 for i, line in enumerate(f):
201 if line.find(string_to_match) != -1:
202 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000203 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000204 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000205
Johnny Chen67af43f2010-10-05 19:27:32 +0000206def pointer_size():
207 """Return the pointer size of the host system."""
208 import ctypes
209 a_pointer = ctypes.c_void_p(0xffff)
210 return 8 * ctypes.sizeof(a_pointer)
211
Johnny Chen57816732012-02-09 02:01:59 +0000212def is_exe(fpath):
213 """Returns true if fpath is an executable."""
214 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
215
216def which(program):
217 """Returns the full path to a program; None otherwise."""
218 fpath, fname = os.path.split(program)
219 if fpath:
220 if is_exe(program):
221 return program
222 else:
223 for path in os.environ["PATH"].split(os.pathsep):
224 exe_file = os.path.join(path, program)
225 if is_exe(exe_file):
226 return exe_file
227 return None
228
Zachary Turner814236d2015-10-21 17:48:52 +0000229class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000230 """
231 A nice little context manager for recording the debugger interactions into
232 our session object. If trace flag is ON, it also emits the interactions
233 into the stderr.
234 """
235 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000236 """Create a SixStringIO instance; record the session obj and trace flag."""
237 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000238 # The test might not have undergone the 'setUp(self)' phase yet, so that
239 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000240 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000241 self.trace = trace
242
243 def __enter__(self):
244 """
245 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000246 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000247 """
248 return self
249
250 def __exit__(self, type, value, tb):
251 """
252 Context management protocol on exit from the body of the with statement.
253 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000254 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000255 """
256 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000257 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000258 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000259 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000260 self.close()
261
Zachary Turner43a01e42015-10-20 21:06:05 +0000262@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000263class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000264
265 @abc.abstractproperty
266 def pid(self):
267 """Returns process PID if has been launched already."""
268
269 @abc.abstractmethod
270 def launch(self, executable, args):
271 """Launches new process with given executable and args."""
272
273 @abc.abstractmethod
274 def terminate(self):
275 """Terminates previously launched process.."""
276
277class _LocalProcess(_BaseProcess):
278
279 def __init__(self, trace_on):
280 self._proc = None
281 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000282 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000283
284 @property
285 def pid(self):
286 return self._proc.pid
287
288 def launch(self, executable, args):
289 self._proc = Popen([executable] + args,
290 stdout = open(os.devnull) if not self._trace_on else None,
291 stdin = PIPE)
292
293 def terminate(self):
294 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000295 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000296 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
297 for sig in signals_to_try:
298 try:
299 self._proc.send_signal(getattr(signal, sig))
300 time.sleep(self._delayafterterminate)
301 if self._proc.poll() != None:
302 return
303 except ValueError:
304 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000305 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000306 time.sleep(self._delayafterterminate)
307 if self._proc.poll() != None:
308 return
309 self._proc.kill()
310 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000311
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000312 def poll(self):
313 return self._proc.poll()
314
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000315class _RemoteProcess(_BaseProcess):
316
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000317 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000318 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000319 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000320
321 @property
322 def pid(self):
323 return self._pid
324
325 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000326 if self._install_remote:
327 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000328 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000329
330 dst_file_spec = lldb.SBFileSpec(dst_path, False)
331 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
332 if err.Fail():
333 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
334 else:
335 dst_path = executable
336 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000337
338 launch_info = lldb.SBLaunchInfo(args)
339 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000340 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000341
342 # Redirect stdout and stderr to /dev/null
343 launch_info.AddSuppressFileAction(1, False, True)
344 launch_info.AddSuppressFileAction(2, False, True)
345
346 err = lldb.remote_platform.Launch(launch_info)
347 if err.Fail():
348 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
349 self._pid = launch_info.GetProcessID()
350
351 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000352 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000353
Johnny Chen690fcef2010-10-15 23:55:05 +0000354# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000355# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000356def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000357 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000358
359 If the exit code was non-zero it raises a CalledProcessError. The
360 CalledProcessError object will have the return code in the returncode
361 attribute and output in the output attribute.
362
363 The arguments are the same as for the Popen constructor. Example:
364
365 >>> check_output(["ls", "-l", "/dev/null"])
366 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
367
368 The stdout argument is not allowed as it is used internally.
369 To capture standard error in the result, use stderr=STDOUT.
370
371 >>> check_output(["/bin/sh", "-c",
372 ... "ls -l non_existent_file ; exit 0"],
373 ... stderr=STDOUT)
374 'ls: non_existent_file: No such file or directory\n'
375 """
376
377 # Assign the sender object to variable 'test' and remove it from kwargs.
378 test = kwargs.pop('sender', None)
379
Zachary Turner9ef307b2014-07-22 16:19:29 +0000380 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
381 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000382 output = ""
383 error = ""
384 for shellCommand in commandList:
385 if 'stdout' in kwargs:
386 raise ValueError('stdout argument not allowed, it will be overridden.')
387 if 'shell' in kwargs and kwargs['shell']==False:
388 raise ValueError('shell=False not allowed')
389 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
390 pid = process.pid
391 this_output, this_error = process.communicate()
392 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000393
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000394 # Enable trace on failure return while tracking down FreeBSD buildbot issues
395 trace = traceAlways
396 if not trace and retcode and sys.platform.startswith("freebsd"):
397 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000398
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000399 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000400 print(file=sbuf)
401 print("os command:", shellCommand, file=sbuf)
402 print("with pid:", pid, file=sbuf)
403 print("stdout:", this_output, file=sbuf)
404 print("stderr:", this_error, file=sbuf)
405 print("retcode:", retcode, file=sbuf)
406 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000407
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000408 if retcode:
409 cmd = kwargs.get("args")
410 if cmd is None:
411 cmd = shellCommand
412 raise CalledProcessError(retcode, cmd)
413 output = output + this_output
414 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000415 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000416
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000417def getsource_if_available(obj):
418 """
419 Return the text of the source code for an object if available. Otherwise,
420 a print representation is returned.
421 """
422 import inspect
423 try:
424 return inspect.getsource(obj)
425 except:
426 return repr(obj)
427
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000428def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000429 if sys.platform.startswith("freebsd"):
430 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000431 return __import__("builder_" + sys.platform)
432
Siva Chandra8af91662015-06-05 00:22:49 +0000433def run_adb_command(cmd, device_id):
434 device_id_args = []
435 if device_id:
436 device_id_args = ["-s", device_id]
437 full_cmd = ["adb"] + device_id_args + cmd
438 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
439 stdout, stderr = p.communicate()
440 return p.returncode, stdout, stderr
441
Chaoren Line9bbabc2015-07-18 00:37:55 +0000442def append_android_envs(dictionary):
443 if dictionary is None:
444 dictionary = {}
445 dictionary["OS"] = "Android"
446 if android_device_api() >= 16:
447 dictionary["PIE"] = 1
448 return dictionary
449
Chaoren Lin9070f532015-07-17 22:13:29 +0000450def target_is_android():
451 if not hasattr(target_is_android, 'result'):
452 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
453 match = re.match(".*-.*-.*-android", triple)
454 target_is_android.result = match is not None
455 return target_is_android.result
456
Siva Chandra8af91662015-06-05 00:22:49 +0000457def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000458 if not hasattr(android_device_api, 'result'):
459 assert lldb.platform_url is not None
460 device_id = None
461 parsed_url = urlparse.urlparse(lldb.platform_url)
462 if parsed_url.scheme == "adb":
463 device_id = parsed_url.netloc.split(":")[0]
464 retcode, stdout, stderr = run_adb_command(
465 ["shell", "getprop", "ro.build.version.sdk"], device_id)
466 if retcode == 0:
467 android_device_api.result = int(stdout)
468 else:
469 raise LookupError(
470 ">>> Unable to determine the API level of the Android device.\n"
471 ">>> stdout:\n%s\n"
472 ">>> stderr:\n%s\n" % (stdout, stderr))
473 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000474
Johnny Chena74bb0a2011-08-01 18:46:13 +0000475#
476# Decorators for categorizing test cases.
477#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000478from functools import wraps
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000479def add_test_categories(cat):
480 """Decorate an item with test categories"""
481 cat = test_categories.validate(cat, True)
482 def impl(func):
483 func.getCategories = lambda test: cat
484 return func
485 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000486
Johnny Chena74bb0a2011-08-01 18:46:13 +0000487def benchmarks_test(func):
488 """Decorate the item as a benchmarks test."""
489 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
490 raise Exception("@benchmarks_test can only be used to decorate a test method")
491 @wraps(func)
492 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000493 if not lldb.just_do_benchmarks_test:
494 self.skipTest("benchmarks tests")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000495 return func(self, *args, **kwargs)
496
497 # Mark this function as such to separate them from the regular tests.
498 wrapper.__benchmarks_test__ = True
499 return wrapper
500
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000501def no_debug_info_test(func):
502 """Decorate the item as a test what don't use any debug info. If this annotation is specified
503 then the test runner won't generate a separate test for each debug info format. """
504 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
505 raise Exception("@no_debug_info_test can only be used to decorate a test method")
506 @wraps(func)
507 def wrapper(self, *args, **kwargs):
508 return func(self, *args, **kwargs)
509
510 # Mark this function as such to separate them from the regular tests.
511 wrapper.__no_debug_info_test__ = True
512 return wrapper
513
Johnny Chenf1548d42012-04-06 00:56:05 +0000514def dsym_test(func):
515 """Decorate the item as a dsym test."""
516 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
517 raise Exception("@dsym_test can only be used to decorate a test method")
518 @wraps(func)
519 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000520 if lldb.dont_do_dsym_test:
521 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000522 return func(self, *args, **kwargs)
523
524 # Mark this function as such to separate them from the regular tests.
525 wrapper.__dsym_test__ = True
526 return wrapper
527
528def dwarf_test(func):
529 """Decorate the item as a dwarf test."""
530 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
531 raise Exception("@dwarf_test can only be used to decorate a test method")
532 @wraps(func)
533 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000534 if lldb.dont_do_dwarf_test:
535 self.skipTest("dwarf tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000536 return func(self, *args, **kwargs)
537
538 # Mark this function as such to separate them from the regular tests.
539 wrapper.__dwarf_test__ = True
540 return wrapper
541
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000542def dwo_test(func):
543 """Decorate the item as a dwo test."""
544 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
545 raise Exception("@dwo_test can only be used to decorate a test method")
546 @wraps(func)
547 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000548 if lldb.dont_do_dwo_test:
549 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000550 return func(self, *args, **kwargs)
551
552 # Mark this function as such to separate them from the regular tests.
553 wrapper.__dwo_test__ = True
554 return wrapper
555
Todd Fialaa41d48c2014-04-28 04:49:40 +0000556def debugserver_test(func):
557 """Decorate the item as a debugserver test."""
558 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
559 raise Exception("@debugserver_test can only be used to decorate a test method")
560 @wraps(func)
561 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000562 if lldb.dont_do_debugserver_test:
563 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000564 return func(self, *args, **kwargs)
565
566 # Mark this function as such to separate them from the regular tests.
567 wrapper.__debugserver_test__ = True
568 return wrapper
569
570def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000571 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000572 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
573 raise Exception("@llgs_test can only be used to decorate a test method")
574 @wraps(func)
575 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000576 if lldb.dont_do_llgs_test:
577 self.skipTest("llgs tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000578 return func(self, *args, **kwargs)
579
580 # Mark this function as such to separate them from the regular tests.
581 wrapper.__llgs_test__ = True
582 return wrapper
583
Daniel Maleae0f8f572013-08-26 23:57:52 +0000584def not_remote_testsuite_ready(func):
585 """Decorate the item as a test which is not ready yet for remote testsuite."""
586 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
587 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
588 @wraps(func)
589 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000590 if lldb.lldbtest_remote_sandbox or lldb.remote_platform:
591 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000592 return func(self, *args, **kwargs)
593
594 # Mark this function as such to separate them from the regular tests.
595 wrapper.__not_ready_for_remote_testsuite_test__ = True
596 return wrapper
597
Ed Maste433790a2014-04-23 12:55:41 +0000598def expectedFailure(expected_fn, bugnumber=None):
599 def expectedFailure_impl(func):
600 @wraps(func)
601 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000602 from unittest2 import case
603 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000604 try:
Ed Maste433790a2014-04-23 12:55:41 +0000605 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000606 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000607 if expected_fn(self):
608 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000609 else:
610 raise
Ed Maste433790a2014-04-23 12:55:41 +0000611 if expected_fn(self):
612 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
613 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000614 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
615 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000616 if six.callable(bugnumber):
Ying Chen464d1e12015-03-27 00:26:52 +0000617 return expectedFailure_impl(bugnumber)
618 else:
619 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000620
Ying Chen7091c2c2015-04-21 01:15:47 +0000621# provide a function to xfail on defined oslist, compiler version, and archs
622# if none is specified for any argument, that argument won't be checked and thus means for all
623# for example,
624# @expectedFailureAll, xfail for all platform/compiler/arch,
625# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
626# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000627def expectedFailureAll(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None):
Ying Chen7091c2c2015-04-21 01:15:47 +0000628 def fn(self):
629 return ((oslist is None or self.getPlatform() in oslist) and
630 (compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))) and
Tamas Berghammercf6f92a2015-09-07 15:50:19 +0000631 self.expectedArch(archs) and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000632 (triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())) and
633 (debug_info is None or self.debug_info in debug_info))
Ying Chen7091c2c2015-04-21 01:15:47 +0000634 return expectedFailure(fn, bugnumber)
635
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000636def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000637 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
638
639def expectedFailureDwo(bugnumber=None):
640 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000641
642def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000643 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000644
645def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
646 if compiler_version is None:
647 compiler_version=['=', None]
648 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
649
Vince Harron8974ce22015-03-13 19:54:54 +0000650# to XFAIL a specific clang versions, try this
651# @expectedFailureClang('bugnumber', ['<=', '3.4'])
652def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000653 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000654
655def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000656 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000657
Matt Kopec0de53f02013-03-15 19:10:12 +0000658def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000659 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000660
Ed Maste433790a2014-04-23 12:55:41 +0000661def expectedFailureArch(arch, bugnumber=None):
662 def fn(self):
663 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000664 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000665
Enrico Granatae6cedc12013-02-23 01:05:23 +0000666def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000667 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000668
Matt Kopecee969f92013-09-26 23:30:59 +0000669def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000670 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000671
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000672def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000673 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000674 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000675 self.expectedCompiler(compilers) and
676 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000677 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000678
Chaoren Linf7160f32015-06-09 17:39:27 +0000679def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
680 def fn(self):
681 return (getHostPlatform() in oslist and
682 self.expectedCompiler(compilers))
683 return expectedFailure(fn, bugnumber)
684
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000685def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000686 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000687 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000688
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000689def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
690 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000691
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000692def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
693 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000694
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000695def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
696 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000697
Chaoren Linf7160f32015-06-09 17:39:27 +0000698def expectedFailureHostWindows(bugnumber=None, compilers=None):
699 return expectedFailureHostOS(['windows'], bugnumber, compilers)
700
Pavel Labath090152b2015-08-20 11:37:19 +0000701def matchAndroid(api_levels=None, archs=None):
702 def match(self):
703 if not target_is_android():
704 return False
705 if archs is not None and self.getArchitecture() not in archs:
706 return False
707 if api_levels is not None and android_device_api() not in api_levels:
708 return False
709 return True
710 return match
711
712
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000713def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000714 """ Mark a test as xfail for Android.
715
716 Arguments:
717 bugnumber - The LLVM pr associated with the problem.
718 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000719 for which a test is expected to fail. None means all API level.
720 arch - A sequence of architecture names specifying the architectures
721 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000722 """
Pavel Labath090152b2015-08-20 11:37:19 +0000723 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000724
Vince Harron7ac3ea42015-06-26 15:13:21 +0000725# if the test passes on the first try, we're done (success)
726# if the test fails once, then passes on the second try, raise an ExpectedFailure
727# if the test fails twice in a row, re-throw the exception from the second test run
728def expectedFlakey(expected_fn, bugnumber=None):
729 def expectedFailure_impl(func):
730 @wraps(func)
731 def wrapper(*args, **kwargs):
732 from unittest2 import case
733 self = args[0]
734 try:
735 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000736 # don't retry if the test case is already decorated with xfail or skip
737 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
738 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000739 except Exception:
740 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000741 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000742 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000743 self.tearDown()
744 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000745 func(*args, **kwargs)
746 except Exception:
747 # oh snap! two failures in a row, record a failure/error
748 raise
749 # record the expected failure
750 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
751 else:
752 raise
753 return wrapper
754 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
755 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000756 if six.callable(bugnumber):
Vince Harron7ac3ea42015-06-26 15:13:21 +0000757 return expectedFailure_impl(bugnumber)
758 else:
759 return expectedFailure_impl
760
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000761def expectedFlakeyDwarf(bugnumber=None):
762 def fn(self):
763 return self.debug_info == "dwarf"
764 return expectedFlakey(fn, bugnumber)
765
766def expectedFlakeyDsym(bugnumber=None):
767 def fn(self):
768 return self.debug_info == "dwarf"
769 return expectedFlakey(fn, bugnumber)
770
Vince Harron7ac3ea42015-06-26 15:13:21 +0000771def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
772 def fn(self):
773 return (self.getPlatform() in oslist and
774 self.expectedCompiler(compilers))
775 return expectedFlakey(fn, bugnumber)
776
777def expectedFlakeyDarwin(bugnumber=None, compilers=None):
778 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
779 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
780
781def expectedFlakeyLinux(bugnumber=None, compilers=None):
782 return expectedFlakeyOS(['linux'], bugnumber, compilers)
783
784def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
785 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
786
787def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
788 if compiler_version is None:
789 compiler_version=['=', None]
790 def fn(self):
791 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
792 return expectedFlakey(fn, bugnumber)
793
794# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
795def expectedFlakeyClang(bugnumber=None, compiler_version=None):
796 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
797
798# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
799def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
800 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
801
Pavel Labath63a579c2015-09-07 12:15:27 +0000802def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
803 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
804
Greg Clayton12514562013-12-05 22:22:32 +0000805def skipIfRemote(func):
806 """Decorate the item to skip tests if testing remotely."""
807 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
808 raise Exception("@skipIfRemote can only be used to decorate a test method")
809 @wraps(func)
810 def wrapper(*args, **kwargs):
811 from unittest2 import case
812 if lldb.remote_platform:
813 self = args[0]
814 self.skipTest("skip on remote platform")
815 else:
816 func(*args, **kwargs)
817 return wrapper
818
Siva Chandra4470f382015-06-17 22:32:27 +0000819def skipUnlessListedRemote(remote_list=None):
820 def myImpl(func):
821 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
822 raise Exception("@skipIfRemote can only be used to decorate a "
823 "test method")
824
825 @wraps(func)
826 def wrapper(*args, **kwargs):
827 if remote_list and lldb.remote_platform:
828 self = args[0]
829 triple = self.dbg.GetSelectedPlatform().GetTriple()
830 for r in remote_list:
831 if r in triple:
832 func(*args, **kwargs)
833 return
834 self.skipTest("skip on remote platform %s" % str(triple))
835 else:
836 func(*args, **kwargs)
837 return wrapper
838
839 return myImpl
840
Greg Clayton12514562013-12-05 22:22:32 +0000841def skipIfRemoteDueToDeadlock(func):
842 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
843 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
844 raise Exception("@skipIfRemote can only be used to decorate a test method")
845 @wraps(func)
846 def wrapper(*args, **kwargs):
847 from unittest2 import case
848 if lldb.remote_platform:
849 self = args[0]
850 self.skipTest("skip on remote platform (deadlocks)")
851 else:
852 func(*args, **kwargs)
853 return wrapper
854
Enrico Granatab633e432014-10-06 21:37:06 +0000855def skipIfNoSBHeaders(func):
856 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
857 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000858 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000859 @wraps(func)
860 def wrapper(*args, **kwargs):
861 from unittest2 import case
862 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000863 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000864 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000865 else:
866 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000867 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000868 if not os.path.exists(header):
869 self.skipTest("skip because LLDB.h header not found")
870 else:
871 func(*args, **kwargs)
872 return wrapper
873
Enrico Granata5f92a132015-11-05 00:46:25 +0000874def skipIfiOSSimulator(func):
875 """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
876 return unittest2.skipIf(hasattr(lldb, 'remote_platform_name') and lldb.remote_platform_name == 'ios-simulator', 'skip on the iOS Simulator')(func)
877
Robert Flack13c7ad92015-03-30 14:12:17 +0000878def skipIfFreeBSD(func):
879 """Decorate the item to skip tests that should be skipped on FreeBSD."""
880 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000881
Greg Claytone0d0a762015-04-02 18:24:03 +0000882def getDarwinOSTriples():
883 return ['darwin', 'macosx', 'ios']
884
Daniel Maleab3d41a22013-07-09 00:08:01 +0000885def skipIfDarwin(func):
886 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000887 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000888
Robert Flack13c7ad92015-03-30 14:12:17 +0000889def skipIfLinux(func):
890 """Decorate the item to skip tests that should be skipped on Linux."""
891 return skipIfPlatform(["linux"])(func)
892
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000893def skipUnlessHostLinux(func):
894 """Decorate the item to skip tests that should be skipped on any non Linux host."""
895 return skipUnlessHostPlatform(["linux"])(func)
896
Robert Flack13c7ad92015-03-30 14:12:17 +0000897def skipIfWindows(func):
898 """Decorate the item to skip tests that should be skipped on Windows."""
899 return skipIfPlatform(["windows"])(func)
900
Chaoren Line6eea5d2015-06-08 22:13:28 +0000901def skipIfHostWindows(func):
902 """Decorate the item to skip tests that should be skipped on Windows."""
903 return skipIfHostPlatform(["windows"])(func)
904
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000905def skipUnlessWindows(func):
906 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
907 return skipUnlessPlatform(["windows"])(func)
908
Robert Flack13c7ad92015-03-30 14:12:17 +0000909def skipUnlessDarwin(func):
910 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000911 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000912
Ryan Brown57bee1e2015-09-14 22:45:11 +0000913def skipUnlessGoInstalled(func):
914 """Decorate the item to skip tests when no Go compiler is available."""
915 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
916 raise Exception("@skipIfGcc can only be used to decorate a test method")
917 @wraps(func)
918 def wrapper(*args, **kwargs):
919 from unittest2 import case
920 self = args[0]
921 compiler = self.getGoCompilerVersion()
922 if not compiler:
923 self.skipTest("skipping because go compiler not found")
924 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000925 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +0000926 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +0000927 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
928 if not match_version:
929 # Couldn't determine version.
930 self.skipTest(
931 "skipping because go version could not be parsed "
932 "out of {}".format(compiler))
933 else:
934 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +0000935 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +0000936 compiler_strict_version = StrictVersion(match_version.group(1))
937 if compiler_strict_version < min_strict_version:
938 self.skipTest(
939 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +0000940 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +0000941 compiler_strict_version,
942 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +0000943 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +0000944 return wrapper
945
Robert Flack068898c2015-04-09 18:07:58 +0000946def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +0000947 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +0000948 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
949 if platform.startswith('freebsd'):
950 platform = 'freebsd'
951 return platform
952
Robert Flack6e1fd352015-05-15 12:39:33 +0000953def getHostPlatform():
954 """Returns the host platform running the test suite."""
955 # Attempts to return a platform name matching a target Triple platform.
956 if sys.platform.startswith('linux'):
957 return 'linux'
958 elif sys.platform.startswith('win32'):
959 return 'windows'
960 elif sys.platform.startswith('darwin'):
961 return 'darwin'
962 elif sys.platform.startswith('freebsd'):
963 return 'freebsd'
964 else:
965 return sys.platform
966
Robert Flackfb2f6c62015-04-17 08:02:18 +0000967def platformIsDarwin():
968 """Returns true if the OS triple for the selected platform is any valid apple OS"""
969 return getPlatform() in getDarwinOSTriples()
970
Robert Flack6e1fd352015-05-15 12:39:33 +0000971def skipIfHostIncompatibleWithRemote(func):
972 """Decorate the item to skip tests if binaries built on this host are incompatible."""
973 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
974 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
975 @wraps(func)
976 def wrapper(*args, **kwargs):
977 from unittest2 import case
978 self = args[0]
979 host_arch = self.getLldbArchitecture()
980 host_platform = getHostPlatform()
981 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +0000982 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +0000983 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
984 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
985 elif target_platform != host_platform:
986 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
987 else:
988 func(*args, **kwargs)
989 return wrapper
990
Chaoren Line6eea5d2015-06-08 22:13:28 +0000991def skipIfHostPlatform(oslist):
992 """Decorate the item to skip tests if running on one of the listed host platforms."""
993 return unittest2.skipIf(getHostPlatform() in oslist,
994 "skip on %s" % (", ".join(oslist)))
995
996def skipUnlessHostPlatform(oslist):
997 """Decorate the item to skip tests unless running on one of the listed host platforms."""
998 return unittest2.skipUnless(getHostPlatform() in oslist,
999 "requires on of %s" % (", ".join(oslist)))
1000
Zachary Turner793d9972015-08-14 23:29:24 +00001001def skipUnlessArch(archlist):
1002 """Decorate the item to skip tests unless running on one of the listed architectures."""
1003 def myImpl(func):
1004 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1005 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1006
1007 @wraps(func)
1008 def wrapper(*args, **kwargs):
1009 self = args[0]
1010 if self.getArchitecture() not in archlist:
1011 self.skipTest("skipping for architecture %s (requires one of %s)" %
1012 (self.getArchitecture(), ", ".join(archlist)))
1013 else:
1014 func(*args, **kwargs)
1015 return wrapper
1016
1017 return myImpl
1018
Robert Flack13c7ad92015-03-30 14:12:17 +00001019def skipIfPlatform(oslist):
1020 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001021 return unittest2.skipIf(getPlatform() in oslist,
1022 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001023
1024def skipUnlessPlatform(oslist):
1025 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001026 return unittest2.skipUnless(getPlatform() in oslist,
1027 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001028
Daniel Malea48359902013-05-14 20:48:54 +00001029def skipIfLinuxClang(func):
1030 """Decorate the item to skip tests that should be skipped if building on
1031 Linux with clang.
1032 """
1033 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1034 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1035 @wraps(func)
1036 def wrapper(*args, **kwargs):
1037 from unittest2 import case
1038 self = args[0]
1039 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001040 platform = self.getPlatform()
1041 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001042 self.skipTest("skipping because Clang is used on Linux")
1043 else:
1044 func(*args, **kwargs)
1045 return wrapper
1046
Ying Chen7091c2c2015-04-21 01:15:47 +00001047# provide a function to skip on defined oslist, compiler version, and archs
1048# if none is specified for any argument, that argument won't be checked and thus means for all
1049# for example,
1050# @skipIf, skip for all platform/compiler/arch,
1051# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1052# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1053
1054# TODO: refactor current code, to make skipIfxxx functions to call this function
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001055def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001056 def fn(self):
1057 return ((oslist is None or self.getPlatform() in oslist) and
1058 (compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))) and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001059 self.expectedArch(archs) and
1060 (debug_info is None or self.debug_info in debug_info))
1061 return skipTestIfFn(fn, bugnumber, skipReason="skipping because os:%s compiler: %s %s arch: %s debug info: %s"%(oslist, compiler, compiler_version, archs, debug_info))
1062
1063def skipIfDebugInfo(bugnumber=None, debug_info=None):
1064 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1065
Greg Claytonedea2372015-10-07 20:01:13 +00001066def skipIfDWO(bugnumber=None):
1067 return skipIfDebugInfo(bugnumber, ["dwo"])
1068
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001069def skipIfDwarf(bugnumber=None):
1070 return skipIfDebugInfo(bugnumber, ["dwarf"])
1071
1072def skipIfDsym(bugnumber=None):
1073 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001074
1075def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1076 def skipTestIfFn_impl(func):
1077 @wraps(func)
1078 def wrapper(*args, **kwargs):
1079 from unittest2 import case
1080 self = args[0]
1081 if expected_fn(self):
1082 self.skipTest(skipReason)
1083 else:
1084 func(*args, **kwargs)
1085 return wrapper
Zachary Turnercd236b82015-10-26 18:48:24 +00001086 if six.callable(bugnumber):
Ying Chen7091c2c2015-04-21 01:15:47 +00001087 return skipTestIfFn_impl(bugnumber)
1088 else:
1089 return skipTestIfFn_impl
1090
Daniel Maleabe230792013-01-24 23:52:09 +00001091def skipIfGcc(func):
1092 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1093 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001094 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001095 @wraps(func)
1096 def wrapper(*args, **kwargs):
1097 from unittest2 import case
1098 self = args[0]
1099 compiler = self.getCompiler()
1100 if "gcc" in compiler:
1101 self.skipTest("skipping because gcc is the test compiler")
1102 else:
1103 func(*args, **kwargs)
1104 return wrapper
1105
Matt Kopec0de53f02013-03-15 19:10:12 +00001106def skipIfIcc(func):
1107 """Decorate the item to skip tests that should be skipped if building with icc ."""
1108 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1109 raise Exception("@skipIfIcc can only be used to decorate a test method")
1110 @wraps(func)
1111 def wrapper(*args, **kwargs):
1112 from unittest2 import case
1113 self = args[0]
1114 compiler = self.getCompiler()
1115 if "icc" in compiler:
1116 self.skipTest("skipping because icc is the test compiler")
1117 else:
1118 func(*args, **kwargs)
1119 return wrapper
1120
Daniel Malea55faa402013-05-02 21:44:31 +00001121def skipIfi386(func):
1122 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1123 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1124 raise Exception("@skipIfi386 can only be used to decorate a test method")
1125 @wraps(func)
1126 def wrapper(*args, **kwargs):
1127 from unittest2 import case
1128 self = args[0]
1129 if "i386" == self.getArchitecture():
1130 self.skipTest("skipping because i386 is not a supported architecture")
1131 else:
1132 func(*args, **kwargs)
1133 return wrapper
1134
Pavel Labath090152b2015-08-20 11:37:19 +00001135def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001136 """Decorator to skip tests when the target is Android.
1137
1138 Arguments:
1139 api_levels - The API levels for which the test should be skipped. If
1140 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001141 arch - A sequence of architecture names specifying the architectures
1142 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001143 """
1144 def myImpl(func):
1145 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1146 raise Exception("@skipIfTargetAndroid can only be used to "
1147 "decorate a test method")
1148 @wraps(func)
1149 def wrapper(*args, **kwargs):
1150 from unittest2 import case
1151 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001152 if matchAndroid(api_levels, archs)(self):
1153 self.skipTest("skiped on Android target with API %d and architecture %s" %
1154 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001155 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001156 return wrapper
1157 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001158
Ilia Kd9953052015-03-12 07:19:41 +00001159def skipUnlessCompilerRt(func):
1160 """Decorate the item to skip tests if testing remotely."""
1161 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1162 raise Exception("@skipUnless can only be used to decorate a test method")
1163 @wraps(func)
1164 def wrapper(*args, **kwargs):
1165 from unittest2 import case
1166 import os.path
1167 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "projects", "compiler-rt")
1168 if not os.path.exists(compilerRtPath):
1169 self = args[0]
1170 self.skipTest("skip if compiler-rt not found")
1171 else:
1172 func(*args, **kwargs)
1173 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001174
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001175class _PlatformContext(object):
1176 """Value object class which contains platform-specific options."""
1177
1178 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1179 self.shlib_environment_var = shlib_environment_var
1180 self.shlib_prefix = shlib_prefix
1181 self.shlib_extension = shlib_extension
1182
1183
Johnny Chena74bb0a2011-08-01 18:46:13 +00001184class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001185 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001186 Abstract base for performing lldb (see TestBase) or other generic tests (see
1187 BenchBase for one example). lldbtest.Base works with the test driver to
1188 accomplish things.
1189
Johnny Chen8334dad2010-10-22 23:15:46 +00001190 """
Enrico Granata5020f952012-10-24 21:42:49 +00001191
Enrico Granata19186272012-10-24 21:44:48 +00001192 # The concrete subclass should override this attribute.
1193 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001194
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001195 # Keep track of the old current working directory.
1196 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001197
Greg Clayton4570d3e2013-12-10 23:19:29 +00001198 @staticmethod
1199 def compute_mydir(test_file):
1200 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1201
1202 mydir = TestBase.compute_mydir(__file__)'''
1203 test_dir = os.path.dirname(test_file)
1204 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1205
Johnny Chenfb4264c2011-08-01 19:50:58 +00001206 def TraceOn(self):
1207 """Returns True if we are in trace mode (tracing detailed test execution)."""
1208 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001209
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001210 @classmethod
1211 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001212 """
1213 Python unittest framework class setup fixture.
1214 Do current directory manipulation.
1215 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001216 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001217 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001218 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001219
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001220 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001221 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001222
1223 # Change current working directory if ${LLDB_TEST} is defined.
1224 # See also dotest.py which sets up ${LLDB_TEST}.
1225 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001226 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001227 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001228 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001229 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1230
Vince Harron85d19652015-05-21 19:09:29 +00001231 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001232 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001233 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1234 try:
1235 cls.dir_lock.try_acquire()
1236 # write the class that owns the lock into the lock file
1237 cls.dir_lock.handle.write(cls.__name__)
1238 except IOError as ioerror:
1239 # nothing else should have this directory lock
1240 # wait here until we get a lock
1241 cls.dir_lock.acquire()
1242 # read the previous owner from the lock file
1243 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001244 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 +00001245 raise ioerror
1246
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001247 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001248 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001249 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Robert Flackfb2f6c62015-04-17 08:02:18 +00001250 elif getPlatform() == "linux" or getPlatform() == "freebsd":
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001251 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001252 else:
1253 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001254
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001255 @classmethod
1256 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001257 """
1258 Python unittest framework class teardown fixture.
1259 Do class-wide cleanup.
1260 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001261
Johnny Chen0fddfb22011-11-17 19:57:27 +00001262 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001263 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001264 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001265 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001266
Johnny Chen707b3c92010-10-11 22:25:46 +00001267 # Subclass might have specific cleanup function defined.
1268 if getattr(cls, "classCleanup", None):
1269 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001270 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001271 try:
1272 cls.classCleanup()
1273 except:
1274 exc_type, exc_value, exc_tb = sys.exc_info()
1275 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001276
Vince Harron85d19652015-05-21 19:09:29 +00001277 if debug_confirm_directory_exclusivity:
1278 cls.dir_lock.release()
1279 del cls.dir_lock
1280
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001281 # Restore old working directory.
1282 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001283 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001284 os.chdir(cls.oldcwd)
1285
Johnny Chena74bb0a2011-08-01 18:46:13 +00001286 @classmethod
1287 def skipLongRunningTest(cls):
1288 """
1289 By default, we skip long running test case.
1290 This can be overridden by passing '-l' to the test driver (dotest.py).
1291 """
1292 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1293 return False
1294 else:
1295 return True
Johnny Chened492022011-06-21 00:53:00 +00001296
Vince Harron6d3d0f12015-05-10 22:01:59 +00001297 def enableLogChannelsForCurrentTest(self):
1298 if len(lldbtest_config.channels) == 0:
1299 return
1300
1301 # if debug channels are specified in lldbtest_config.channels,
1302 # create a new set of log files for every test
1303 log_basename = self.getLogBasenameForCurrentTest()
1304
1305 # confirm that the file is writeable
1306 host_log_path = "{}-host.log".format(log_basename)
1307 open(host_log_path, 'w').close()
1308
1309 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1310 for channel_with_categories in lldbtest_config.channels:
1311 channel_then_categories = channel_with_categories.split(' ', 1)
1312 channel = channel_then_categories[0]
1313 if len(channel_then_categories) > 1:
1314 categories = channel_then_categories[1]
1315 else:
1316 categories = "default"
1317
1318 if channel == "gdb-remote":
1319 # communicate gdb-remote categories to debugserver
1320 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1321
1322 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1323 if not self.res.Succeeded():
1324 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1325
1326 # Communicate log path name to debugserver & lldb-server
1327 server_log_path = "{}-server.log".format(log_basename)
1328 open(server_log_path, 'w').close()
1329 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1330
1331 # Communicate channels to lldb-server
1332 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1333
1334 if len(lldbtest_config.channels) == 0:
1335 return
1336
1337 def disableLogChannelsForCurrentTest(self):
1338 # close all log files that we opened
1339 for channel_and_categories in lldbtest_config.channels:
1340 # channel format - <channel-name> [<category0> [<category1> ...]]
1341 channel = channel_and_categories.split(' ', 1)[0]
1342 self.ci.HandleCommand("log disable " + channel, self.res)
1343 if not self.res.Succeeded():
1344 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1345
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001346 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001347 """Fixture for unittest test case setup.
1348
1349 It works with the test driver to conditionally skip tests and does other
1350 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001351 #import traceback
1352 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001353
Daniel Malea9115f072013-08-06 15:02:32 +00001354 if "LIBCXX_PATH" in os.environ:
1355 self.libcxxPath = os.environ["LIBCXX_PATH"]
1356 else:
1357 self.libcxxPath = None
1358
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001359 if "LLDBMI_EXEC" in os.environ:
1360 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1361 else:
1362 self.lldbMiExec = None
Vince Harron790d95c2015-05-18 19:39:03 +00001363
Johnny Chenebe51722011-10-07 19:21:09 +00001364 # If we spawn an lldb process for test (via pexpect), do not load the
1365 # init file unless told otherwise.
1366 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1367 self.lldbOption = ""
1368 else:
1369 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001370
Johnny Chen985e7402011-08-01 21:13:26 +00001371 # Assign the test method name to self.testMethodName.
1372 #
1373 # For an example of the use of this attribute, look at test/types dir.
1374 # There are a bunch of test cases under test/types and we don't want the
1375 # module cacheing subsystem to be confused with executable name "a.out"
1376 # used for all the test cases.
1377 self.testMethodName = self._testMethodName
1378
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001379 # Benchmarks test is decorated with @benchmarks_test,
1380 # which also sets the "__benchmarks_test__" attribute of the
1381 # function object to True.
1382 try:
1383 if lldb.just_do_benchmarks_test:
1384 testMethod = getattr(self, self._testMethodName)
1385 if getattr(testMethod, "__benchmarks_test__", False):
1386 pass
1387 else:
1388 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +00001389 except AttributeError:
1390 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001391
Johnny Chen985e7402011-08-01 21:13:26 +00001392 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1393 # with it using pexpect.
1394 self.child = None
1395 self.child_prompt = "(lldb) "
1396 # If the child is interacting with the embedded script interpreter,
1397 # there are two exits required during tear down, first to quit the
1398 # embedded script interpreter and second to quit the lldb command
1399 # interpreter.
1400 self.child_in_script_interpreter = False
1401
Johnny Chenfb4264c2011-08-01 19:50:58 +00001402 # These are for customized teardown cleanup.
1403 self.dict = None
1404 self.doTearDownCleanup = False
1405 # And in rare cases where there are multiple teardown cleanups.
1406 self.dicts = []
1407 self.doTearDownCleanups = False
1408
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001409 # List of spawned subproces.Popen objects
1410 self.subprocesses = []
1411
Daniel Malea69207462013-06-05 21:07:02 +00001412 # List of forked process PIDs
1413 self.forkedProcessPids = []
1414
Johnny Chenfb4264c2011-08-01 19:50:58 +00001415 # Create a string buffer to record the session info, to be dumped into a
1416 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001417 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001418
Vince Harron1f160372015-05-21 18:51:20 +00001419 session_file = "{}.log".format(self.log_basename)
Vince Harron35b17dc2015-05-21 18:20:21 +00001420 unbuffered = 0 # 0 is the constant for unbuffered
Vince Harron1f160372015-05-21 18:51:20 +00001421 self.session = open(session_file, "w", unbuffered)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001422
1423 # Optimistically set __errored__, __failed__, __expected__ to False
1424 # initially. If the test errored/failed, the session info
1425 # (self.session) is then dumped into a session specific file for
1426 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001427 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001428 self.__errored__ = False
1429 self.__failed__ = False
1430 self.__expected__ = False
1431 # We are also interested in unexpected success.
1432 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001433 # And skipped tests.
1434 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001435
1436 # See addTearDownHook(self, hook) which allows the client to add a hook
1437 # function to be run during tearDown() time.
1438 self.hooks = []
1439
1440 # See HideStdout(self).
1441 self.sys_stdout_hidden = False
1442
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001443 if self.platformContext:
1444 # set environment variable names for finding shared libraries
1445 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001446
Vince Harron6d3d0f12015-05-10 22:01:59 +00001447 # Create the debugger instance if necessary.
1448 try:
1449 self.dbg = lldb.DBG
1450 except AttributeError:
1451 self.dbg = lldb.SBDebugger.Create()
1452
1453 if not self.dbg:
1454 raise Exception('Invalid debugger instance')
1455
1456 # Retrieve the associated command interpreter instance.
1457 self.ci = self.dbg.GetCommandInterpreter()
1458 if not self.ci:
1459 raise Exception('Could not get the command interpreter')
1460
1461 # And the result object.
1462 self.res = lldb.SBCommandReturnObject()
1463
1464 self.enableLogChannelsForCurrentTest()
1465
Johnny Chen2a808582011-10-19 16:48:07 +00001466 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001467 """Perform the run hooks to bring lldb debugger to the desired state.
1468
Johnny Chen2a808582011-10-19 16:48:07 +00001469 By default, expect a pexpect spawned child and child prompt to be
1470 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1471 and child prompt and use self.runCmd() to run the hooks one by one.
1472
Johnny Chena737ba52011-10-19 01:06:21 +00001473 Note that child is a process spawned by pexpect.spawn(). If not, your
1474 test case is mostly likely going to fail.
1475
1476 See also dotest.py where lldb.runHooks are processed/populated.
1477 """
1478 if not lldb.runHooks:
1479 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001480 if use_cmd_api:
1481 for hook in lldb.runhooks:
1482 self.runCmd(hook)
1483 else:
1484 if not child or not child_prompt:
1485 self.fail("Both child and child_prompt need to be defined.")
1486 for hook in lldb.runHooks:
1487 child.sendline(hook)
1488 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001489
Daniel Malea249287a2013-02-19 16:08:57 +00001490 def setAsync(self, value):
1491 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1492 old_async = self.dbg.GetAsync()
1493 self.dbg.SetAsync(value)
1494 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1495
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001496 def cleanupSubprocesses(self):
1497 # Ensure any subprocesses are cleaned up
1498 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001499 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001500 del p
1501 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001502 # Ensure any forked processes are cleaned up
1503 for pid in self.forkedProcessPids:
1504 if os.path.exists("/proc/" + str(pid)):
1505 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001506
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001507 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001508 """ Creates a subprocess.Popen object with the specified executable and arguments,
1509 saves it in self.subprocesses, and returns the object.
1510 NOTE: if using this function, ensure you also call:
1511
1512 self.addTearDownHook(self.cleanupSubprocesses)
1513
1514 otherwise the test suite will leak processes.
1515 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001516 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001517 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001518 self.subprocesses.append(proc)
1519 return proc
1520
Daniel Malea69207462013-06-05 21:07:02 +00001521 def forkSubprocess(self, executable, args=[]):
1522 """ Fork a subprocess with its own group ID.
1523 NOTE: if using this function, ensure you also call:
1524
1525 self.addTearDownHook(self.cleanupSubprocesses)
1526
1527 otherwise the test suite will leak processes.
1528 """
1529 child_pid = os.fork()
1530 if child_pid == 0:
1531 # If more I/O support is required, this can be beefed up.
1532 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001533 os.dup2(fd, 1)
1534 os.dup2(fd, 2)
1535 # This call causes the child to have its of group ID
1536 os.setpgid(0,0)
1537 os.execvp(executable, [executable] + args)
1538 # Give the child time to get through the execvp() call
1539 time.sleep(0.1)
1540 self.forkedProcessPids.append(child_pid)
1541 return child_pid
1542
Johnny Chenfb4264c2011-08-01 19:50:58 +00001543 def HideStdout(self):
1544 """Hide output to stdout from the user.
1545
1546 During test execution, there might be cases where we don't want to show the
1547 standard output to the user. For example,
1548
Zachary Turner35d017f2015-10-23 17:04:29 +00001549 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001550
1551 tests whether command abbreviation for 'script' works or not. There is no
1552 need to show the 'Hello' output to the user as long as the 'script' command
1553 succeeds and we are not in TraceOn() mode (see the '-t' option).
1554
1555 In this case, the test method calls self.HideStdout(self) to redirect the
1556 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1557
1558 Note that you should only call this method at most once during a test case
1559 execution. Any subsequent call has no effect at all."""
1560 if self.sys_stdout_hidden:
1561 return
1562
1563 self.sys_stdout_hidden = True
1564 old_stdout = sys.stdout
1565 sys.stdout = open(os.devnull, 'w')
1566 def restore_stdout():
1567 sys.stdout = old_stdout
1568 self.addTearDownHook(restore_stdout)
1569
1570 # =======================================================================
1571 # Methods for customized teardown cleanups as well as execution of hooks.
1572 # =======================================================================
1573
1574 def setTearDownCleanup(self, dictionary=None):
1575 """Register a cleanup action at tearDown() time with a dictinary"""
1576 self.dict = dictionary
1577 self.doTearDownCleanup = True
1578
1579 def addTearDownCleanup(self, dictionary):
1580 """Add a cleanup action at tearDown() time with a dictinary"""
1581 self.dicts.append(dictionary)
1582 self.doTearDownCleanups = True
1583
1584 def addTearDownHook(self, hook):
1585 """
1586 Add a function to be run during tearDown() time.
1587
1588 Hooks are executed in a first come first serve manner.
1589 """
Zachary Turnercd236b82015-10-26 18:48:24 +00001590 if six.callable(hook):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001591 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001592 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001593 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001594
1595 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001596
Jim Inghamda3a3862014-10-16 23:02:14 +00001597 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001598 # This is for the case of directly spawning 'lldb' and interacting with it
1599 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001600 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001601 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001602 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001603 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001604 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001605 if self.child_in_script_interpreter:
1606 self.child.sendline('quit()')
1607 self.child.expect_exact(self.child_prompt)
1608 self.child.sendline('settings set interpreter.prompt-on-quit false')
1609 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001610 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001611 except (ValueError, pexpect.ExceptionPexpect):
1612 # child is already terminated
1613 pass
1614 except OSError as exception:
1615 import errno
1616 if exception.errno != errno.EIO:
1617 # unexpected error
1618 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001619 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001620 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001621 finally:
1622 # Give it one final blow to make sure the child is terminated.
1623 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001624
1625 def tearDown(self):
1626 """Fixture for unittest test case teardown."""
1627 #import traceback
1628 #traceback.print_stack()
1629
1630 self.deletePexpectChild()
1631
Johnny Chenfb4264c2011-08-01 19:50:58 +00001632 # Check and run any hook functions.
1633 for hook in reversed(self.hooks):
1634 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001635 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001636 import inspect
1637 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001638 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001639 hook()
1640 elif hook_argc == 1:
1641 hook(self)
1642 else:
1643 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001644
1645 del self.hooks
1646
1647 # Perform registered teardown cleanup.
1648 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001649 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001650
1651 # In rare cases where there are multiple teardown cleanups added.
1652 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001653 if self.dicts:
1654 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001655 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001656
Vince Harron9753dd92015-05-10 15:22:09 +00001657 self.disableLogChannelsForCurrentTest()
1658
Johnny Chenfb4264c2011-08-01 19:50:58 +00001659 # =========================================================
1660 # Various callbacks to allow introspection of test progress
1661 # =========================================================
1662
1663 def markError(self):
1664 """Callback invoked when an error (unexpected exception) errored."""
1665 self.__errored__ = True
1666 with recording(self, False) as sbuf:
1667 # False because there's no need to write "ERROR" to the stderr twice.
1668 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001669 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001670
Zachary Turnerb1490b62015-08-26 19:44:56 +00001671 def markCleanupError(self):
1672 """Callback invoked when an error occurs while a test is cleaning up."""
1673 self.__cleanup_errored__ = True
1674 with recording(self, False) as sbuf:
1675 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1676 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001677 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001678
Johnny Chenfb4264c2011-08-01 19:50:58 +00001679 def markFailure(self):
1680 """Callback invoked when a failure (test assertion failure) occurred."""
1681 self.__failed__ = True
1682 with recording(self, False) as sbuf:
1683 # False because there's no need to write "FAIL" to the stderr twice.
1684 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001685 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001686
Enrico Granatae6cedc12013-02-23 01:05:23 +00001687 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001688 """Callback invoked when an expected failure/error occurred."""
1689 self.__expected__ = True
1690 with recording(self, False) as sbuf:
1691 # False because there's no need to write "expected failure" to the
1692 # stderr twice.
1693 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001694 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001695 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001696 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001697 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001698
Johnny Chenc5cc6252011-08-15 23:09:08 +00001699 def markSkippedTest(self):
1700 """Callback invoked when a test is skipped."""
1701 self.__skipped__ = True
1702 with recording(self, False) as sbuf:
1703 # False because there's no need to write "skipped test" to the
1704 # stderr twice.
1705 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001706 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001707
Enrico Granatae6cedc12013-02-23 01:05:23 +00001708 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001709 """Callback invoked when an unexpected success occurred."""
1710 self.__unexpected__ = True
1711 with recording(self, False) as sbuf:
1712 # False because there's no need to write "unexpected success" to the
1713 # stderr twice.
1714 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001715 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001716 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001717 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001718 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001719
Greg Clayton70995582015-01-07 22:25:50 +00001720 def getRerunArgs(self):
1721 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001722
1723 def getLogBasenameForCurrentTest(self, prefix=None):
1724 """
1725 returns a partial path that can be used as the beginning of the name of multiple
1726 log files pertaining to this test
1727
1728 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1729 """
1730 dname = os.path.join(os.environ["LLDB_TEST"],
1731 os.environ["LLDB_SESSION_DIRNAME"])
1732 if not os.path.isdir(dname):
1733 os.mkdir(dname)
1734
1735 compiler = self.getCompiler()
1736
1737 if compiler[1] == ':':
1738 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001739 if os.path.altsep is not None:
1740 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001741
Vince Harron19e300f2015-05-12 00:50:54 +00001742 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001743 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001744 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001745
1746 if prefix is not None:
1747 fname = "{}-{}".format(prefix, fname)
1748
1749 return os.path.join(dname, fname)
1750
Johnny Chenfb4264c2011-08-01 19:50:58 +00001751 def dumpSessionInfo(self):
1752 """
1753 Dump the debugger interactions leading to a test error/failure. This
1754 allows for more convenient postmortem analysis.
1755
1756 See also LLDBTestResult (dotest.py) which is a singlton class derived
1757 from TextTestResult and overwrites addError, addFailure, and
1758 addExpectedFailure methods to allow us to to mark the test instance as
1759 such.
1760 """
1761
1762 # We are here because self.tearDown() detected that this test instance
1763 # either errored or failed. The lldb.test_result singleton contains
1764 # two lists (erros and failures) which get populated by the unittest
1765 # framework. Look over there for stack trace information.
1766 #
1767 # The lists contain 2-tuples of TestCase instances and strings holding
1768 # formatted tracebacks.
1769 #
1770 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001771
Vince Harron35b17dc2015-05-21 18:20:21 +00001772 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001773 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001774 if self.__errored__:
1775 pairs = lldb.test_result.errors
1776 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001777 elif self.__cleanup_errored__:
Zachary Turnerb1490b62015-08-26 19:44:56 +00001778 pairs = lldb.test_result.cleanup_errors
1779 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001780 elif self.__failed__:
1781 pairs = lldb.test_result.failures
1782 prefix = 'Failure'
1783 elif self.__expected__:
1784 pairs = lldb.test_result.expectedFailures
1785 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001786 elif self.__skipped__:
1787 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001788 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001789 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001790 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001791 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001792
Johnny Chenc5cc6252011-08-15 23:09:08 +00001793 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001794 for test, traceback in pairs:
1795 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001796 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001797
Vince Harron35b17dc2015-05-21 18:20:21 +00001798 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001799 testMethod = getattr(self, self._testMethodName)
1800 if getattr(testMethod, "__benchmarks_test__", False):
1801 benchmarks = True
1802 else:
1803 benchmarks = False
1804
Vince Harron35b17dc2015-05-21 18:20:21 +00001805 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001806 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1807 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1808 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001809 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001810 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001811 self.session.close()
1812 del self.session
1813
1814 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001815 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001816
1817 if prefix != 'Success' or lldbtest_config.log_success:
1818 # keep all log files, rename them to include prefix
1819 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1820 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001821 if os.path.isfile(src):
1822 dst = src.replace(self.log_basename, dst_log_basename)
1823 if os.name == "nt" and os.path.isfile(dst):
1824 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1825 # it silently replaces the destination. Ultimately this means that atomic renames are not
1826 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1827 # destination first if it already exists.
1828 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001829
Zachary Turner306278f2015-05-26 20:26:29 +00001830 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001831 else:
1832 # success! (and we don't want log files) delete log files
1833 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001834 try:
1835 os.unlink(log_file)
1836 except:
1837 # We've seen consistent unlink failures on Windows, perhaps because the
1838 # just-created log file is being scanned by anti-virus. Empirically, this
1839 # sleep-and-retry approach allows tests to succeed much more reliably.
1840 # Attempts to figure out exactly what process was still holding a file handle
1841 # have failed because running instrumentation like Process Monitor seems to
1842 # slow things down enough that the problem becomes much less consistent.
1843 time.sleep(0.5)
1844 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001845
1846 # ====================================================
1847 # Config. methods supported through a plugin interface
1848 # (enables reading of the current test configuration)
1849 # ====================================================
1850
1851 def getArchitecture(self):
1852 """Returns the architecture in effect the test suite is running with."""
1853 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001854 arch = module.getArchitecture()
1855 if arch == 'amd64':
1856 arch = 'x86_64'
1857 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001858
Vince Harron02613762015-05-04 00:17:53 +00001859 def getLldbArchitecture(self):
1860 """Returns the architecture of the lldb binary."""
1861 if not hasattr(self, 'lldbArchitecture'):
1862
1863 # spawn local process
1864 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001865 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001866 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001867 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001868 "-o",
1869 "quit"
1870 ]
1871
1872 output = check_output(command)
1873 str = output.decode("utf-8");
1874
1875 for line in str.splitlines():
1876 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1877 if m:
1878 self.lldbArchitecture = m.group(1)
1879 break
1880
1881 return self.lldbArchitecture
1882
Johnny Chenfb4264c2011-08-01 19:50:58 +00001883 def getCompiler(self):
1884 """Returns the compiler in effect the test suite is running with."""
1885 module = builder_module()
1886 return module.getCompiler()
1887
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001888 def getCompilerBinary(self):
1889 """Returns the compiler binary the test suite is running with."""
1890 return self.getCompiler().split()[0]
1891
Daniel Malea0aea0162013-02-27 17:29:46 +00001892 def getCompilerVersion(self):
1893 """ Returns a string that represents the compiler version.
1894 Supports: llvm, clang.
1895 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00001896 from .lldbutil import which
Daniel Malea0aea0162013-02-27 17:29:46 +00001897 version = 'unknown'
1898
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001899 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001900 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001901 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001902 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001903 if m:
1904 version = m.group(1)
1905 return version
1906
Ryan Brown57bee1e2015-09-14 22:45:11 +00001907 def getGoCompilerVersion(self):
1908 """ Returns a string that represents the go compiler version, or None if go is not found.
1909 """
1910 compiler = which("go")
1911 if compiler:
1912 version_output = system([[compiler, "version"]])[0]
1913 for line in version_output.split(os.linesep):
1914 m = re.search('go version (devel|go\\S+)', line)
1915 if m:
1916 return m.group(1)
1917 return None
1918
Greg Claytone0d0a762015-04-02 18:24:03 +00001919 def platformIsDarwin(self):
1920 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00001921 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00001922
Robert Flack13c7ad92015-03-30 14:12:17 +00001923 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00001924 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001925 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00001926
Daniel Maleaadaaec92013-08-06 20:51:41 +00001927 def isIntelCompiler(self):
1928 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1929 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1930
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001931 def expectedCompilerVersion(self, compiler_version):
1932 """Returns True iff compiler_version[1] matches the current compiler version.
1933 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1934 Any operator other than the following defaults to an equality test:
1935 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1936 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001937 if (compiler_version == None):
1938 return True
1939 operator = str(compiler_version[0])
1940 version = compiler_version[1]
1941
1942 if (version == None):
1943 return True
1944 if (operator == '>'):
1945 return self.getCompilerVersion() > version
1946 if (operator == '>=' or operator == '=>'):
1947 return self.getCompilerVersion() >= version
1948 if (operator == '<'):
1949 return self.getCompilerVersion() < version
1950 if (operator == '<=' or operator == '=<'):
1951 return self.getCompilerVersion() <= version
1952 if (operator == '!=' or operator == '!' or operator == 'not'):
1953 return str(version) not in str(self.getCompilerVersion())
1954 return str(version) in str(self.getCompilerVersion())
1955
1956 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001957 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001958 if (compilers == None):
1959 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001960
1961 for compiler in compilers:
1962 if compiler in self.getCompiler():
1963 return True
1964
1965 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001966
Ying Chen7091c2c2015-04-21 01:15:47 +00001967 def expectedArch(self, archs):
1968 """Returns True iff any element of archs is a sub-string of the current architecture."""
1969 if (archs == None):
1970 return True
1971
1972 for arch in archs:
1973 if arch in self.getArchitecture():
1974 return True
1975
1976 return False
1977
Johnny Chenfb4264c2011-08-01 19:50:58 +00001978 def getRunOptions(self):
1979 """Command line option for -A and -C to run this test again, called from
1980 self.dumpSessionInfo()."""
1981 arch = self.getArchitecture()
1982 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001983 if arch:
1984 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001985 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001986 option_str = ""
1987 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001988 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001989 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001990
1991 # ==================================================
1992 # Build methods supported through a plugin interface
1993 # ==================================================
1994
Ed Mastec97323e2014-04-01 18:47:58 +00001995 def getstdlibFlag(self):
1996 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00001997 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00001998 stdlibflag = "-stdlib=libc++"
1999 else:
2000 stdlibflag = ""
2001 return stdlibflag
2002
Matt Kopec7663b3a2013-09-25 17:44:00 +00002003 def getstdFlag(self):
2004 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002005 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002006 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002007 else:
2008 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002009 return stdflag
2010
2011 def buildDriver(self, sources, exe_name):
2012 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2013 or LLDB.framework).
2014 """
2015
2016 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002017 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002018
2019 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002020 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002021 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002022 d = {'CXX_SOURCES' : sources,
2023 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002024 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002025 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2026 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002027 }
Ed Maste372c24d2013-07-25 21:02:34 +00002028 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 +00002029 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002030 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002031 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002032 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002033 elif sys.platform.startswith('win'):
2034 d = {'CXX_SOURCES' : sources,
2035 'EXE' : exe_name,
2036 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002037 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002038 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002039 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002040
2041 self.buildDefault(dictionary=d)
2042
Matt Kopec7663b3a2013-09-25 17:44:00 +00002043 def buildLibrary(self, sources, lib_name):
2044 """Platform specific way to build a default library. """
2045
2046 stdflag = self.getstdFlag()
2047
Greg Clayton22fd3b12015-10-26 17:52:16 +00002048 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002049 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002050 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002051 d = {'DYLIB_CXX_SOURCES' : sources,
2052 'DYLIB_NAME' : lib_name,
2053 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002054 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2055 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002056 }
Robert Flack4629c4b2015-05-15 18:54:32 +00002057 elif self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux' or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002058 d = {'DYLIB_CXX_SOURCES' : sources,
2059 'DYLIB_NAME' : lib_name,
2060 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002061 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002062 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002063 d = {'DYLIB_CXX_SOURCES' : sources,
2064 'DYLIB_NAME' : lib_name,
2065 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002066 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002067 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002068 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002069
2070 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002071
Daniel Malea55faa402013-05-02 21:44:31 +00002072 def buildProgram(self, sources, exe_name):
2073 """ Platform specific way to build an executable from C/C++ sources. """
2074 d = {'CXX_SOURCES' : sources,
2075 'EXE' : exe_name}
2076 self.buildDefault(dictionary=d)
2077
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002078 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002079 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002080 if lldb.skip_build_and_cleanup:
2081 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002082 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002083 if target_is_android():
2084 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002085 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002086 raise Exception("Don't know how to build default binary")
2087
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002088 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002089 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002090 if lldb.skip_build_and_cleanup:
2091 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002092 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002093 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002094 raise Exception("Don't know how to build binary with dsym")
2095
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002096 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002097 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002098 if lldb.skip_build_and_cleanup:
2099 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002100 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002101 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002102 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002103 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002104 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002105
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002106 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2107 """Platform specific way to build binaries with dwarf maps."""
2108 if lldb.skip_build_and_cleanup:
2109 return
2110 module = builder_module()
2111 if target_is_android():
2112 dictionary = append_android_envs(dictionary)
2113 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2114 raise Exception("Don't know how to build binary with dwo")
2115
Ryan Brown57bee1e2015-09-14 22:45:11 +00002116 def buildGo(self):
2117 """Build the default go binary.
2118 """
2119 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2120
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002121 def signBinary(self, binary_path):
2122 if sys.platform.startswith("darwin"):
2123 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2124 call(codesign_cmd, shell=True)
2125
Kuba Breckabeed8212014-09-04 01:03:18 +00002126 def findBuiltClang(self):
2127 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2128 paths_to_try = [
2129 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2130 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2131 "llvm-build/Release/x86_64/Release/bin/clang",
2132 "llvm-build/Debug/x86_64/Debug/bin/clang",
2133 ]
2134 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
2135 for p in paths_to_try:
2136 path = os.path.join(lldb_root_path, p)
2137 if os.path.exists(path):
2138 return path
Ilia Kd9953052015-03-12 07:19:41 +00002139
2140 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002141 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002142 if os.path.exists(path):
2143 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002144
2145 return os.environ["CC"]
2146
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002147 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002148 """ Returns a dictionary (which can be provided to build* functions above) which
2149 contains OS-specific build flags.
2150 """
2151 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002152 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002153
2154 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002155 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002156 use_libcxx = True
2157
2158 if use_libcxx and self.libcxxPath:
2159 cflags += "-stdlib=libc++ "
2160 if self.libcxxPath:
2161 libcxxInclude = os.path.join(self.libcxxPath, "include")
2162 libcxxLib = os.path.join(self.libcxxPath, "lib")
2163 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2164 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2165
Andrew Kaylor93132f52013-05-28 23:04:25 +00002166 if use_cpp11:
2167 cflags += "-std="
2168 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2169 cflags += "c++0x"
2170 else:
2171 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002172 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002173 cflags += " -stdlib=libc++"
2174 elif "clang" in self.getCompiler():
2175 cflags += " -stdlib=libstdc++"
2176
Andrew Kaylor93132f52013-05-28 23:04:25 +00002177 return {'CFLAGS_EXTRAS' : cflags,
2178 'LD_EXTRAS' : ldflags,
2179 }
2180
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002181 def cleanup(self, dictionary=None):
2182 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002183 if lldb.skip_build_and_cleanup:
2184 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002185 module = builder_module()
2186 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002187 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002188
Daniel Malea55faa402013-05-02 21:44:31 +00002189 def getLLDBLibraryEnvVal(self):
2190 """ Returns the path that the OS-specific library search environment variable
2191 (self.dylibPath) should be set to in order for a program to find the LLDB
2192 library. If an environment variable named self.dylibPath is already set,
2193 the new path is appended to it and returned.
2194 """
2195 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002196 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002197 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002198 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002199 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002200 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002201 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002202 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002203
Ed Maste437f8f62013-09-09 14:04:04 +00002204 def getLibcPlusPlusLibs(self):
Robert Flackfa5ad652015-05-13 20:17:34 +00002205 if self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux':
Ed Maste437f8f62013-09-09 14:04:04 +00002206 return ['libc++.so.1']
2207 else:
2208 return ['libc++.1.dylib','libc++abi.dylib']
2209
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002210# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2211# We change the test methods to create a new test method for each test for each debug info we are
2212# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2213# the new test method we remove the old method at the same time.
2214class LLDBTestCaseFactory(type):
2215 def __new__(cls, name, bases, attrs):
2216 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002217 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002218 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2219 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002220 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002221 def dsym_test_method(self, attrvalue=attrvalue):
2222 self.debug_info = "dsym"
2223 return attrvalue(self)
2224 dsym_method_name = attrname + "_dsym"
2225 dsym_test_method.__name__ = dsym_method_name
2226 newattrs[dsym_method_name] = dsym_test_method
2227
2228 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002229 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002230 def dwarf_test_method(self, attrvalue=attrvalue):
2231 self.debug_info = "dwarf"
2232 return attrvalue(self)
2233 dwarf_method_name = attrname + "_dwarf"
2234 dwarf_test_method.__name__ = dwarf_method_name
2235 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002236
2237 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002238 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002239 def dwo_test_method(self, attrvalue=attrvalue):
2240 self.debug_info = "dwo"
2241 return attrvalue(self)
2242 dwo_method_name = attrname + "_dwo"
2243 dwo_test_method.__name__ = dwo_method_name
2244 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002245 else:
2246 newattrs[attrname] = attrvalue
2247 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2248
Zachary Turner43a01e42015-10-20 21:06:05 +00002249# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2250@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002251class TestBase(Base):
2252 """
2253 This abstract base class is meant to be subclassed. It provides default
2254 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2255 among other things.
2256
2257 Important things for test class writers:
2258
2259 - Overwrite the mydir class attribute, otherwise your test class won't
2260 run. It specifies the relative directory to the top level 'test' so
2261 the test harness can change to the correct working directory before
2262 running your test.
2263
2264 - The setUp method sets up things to facilitate subsequent interactions
2265 with the debugger as part of the test. These include:
2266 - populate the test method name
2267 - create/get a debugger set with synchronous mode (self.dbg)
2268 - get the command interpreter from with the debugger (self.ci)
2269 - create a result object for use with the command interpreter
2270 (self.res)
2271 - plus other stuffs
2272
2273 - The tearDown method tries to perform some necessary cleanup on behalf
2274 of the test to return the debugger to a good state for the next test.
2275 These include:
2276 - execute any tearDown hooks registered by the test method with
2277 TestBase.addTearDownHook(); examples can be found in
2278 settings/TestSettings.py
2279 - kill the inferior process associated with each target, if any,
2280 and, then delete the target from the debugger's target list
2281 - perform build cleanup before running the next test method in the
2282 same test class; examples of registering for this service can be
2283 found in types/TestIntegerTypes.py with the call:
2284 - self.setTearDownCleanup(dictionary=d)
2285
2286 - Similarly setUpClass and tearDownClass perform classwise setup and
2287 teardown fixtures. The tearDownClass method invokes a default build
2288 cleanup for the entire test class; also, subclasses can implement the
2289 classmethod classCleanup(cls) to perform special class cleanup action.
2290
2291 - The instance methods runCmd and expect are used heavily by existing
2292 test cases to send a command to the command interpreter and to perform
2293 string/pattern matching on the output of such command execution. The
2294 expect method also provides a mode to peform string/pattern matching
2295 without running a command.
2296
2297 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2298 build the binaries used during a particular test scenario. A plugin
2299 should be provided for the sys.platform running the test suite. The
2300 Mac OS X implementation is located in plugins/darwin.py.
2301 """
2302
2303 # Maximum allowed attempts when launching the inferior process.
2304 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2305 maxLaunchCount = 3;
2306
2307 # Time to wait before the next launching attempt in second(s).
2308 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2309 timeWaitNextLaunch = 1.0;
2310
2311 def doDelay(self):
2312 """See option -w of dotest.py."""
2313 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
2314 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
2315 waitTime = 1.0
2316 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
2317 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
2318 time.sleep(waitTime)
2319
Enrico Granata165f8af2012-09-21 19:10:53 +00002320 # Returns the list of categories to which this test case belongs
2321 # by default, look for a ".categories" file, and read its contents
2322 # if no such file exists, traverse the hierarchy - we guarantee
2323 # a .categories to exist at the top level directory so we do not end up
2324 # looping endlessly - subclasses are free to define their own categories
2325 # in whatever way makes sense to them
2326 def getCategories(self):
2327 import inspect
2328 import os.path
2329 folder = inspect.getfile(self.__class__)
2330 folder = os.path.dirname(folder)
2331 while folder != '/':
2332 categories_file_name = os.path.join(folder,".categories")
2333 if os.path.exists(categories_file_name):
2334 categories_file = open(categories_file_name,'r')
2335 categories = categories_file.readline()
2336 categories_file.close()
2337 categories = str.replace(categories,'\n','')
2338 categories = str.replace(categories,'\r','')
2339 return categories.split(',')
2340 else:
2341 folder = os.path.dirname(folder)
2342 continue
2343
Johnny Chena74bb0a2011-08-01 18:46:13 +00002344 def setUp(self):
2345 #import traceback
2346 #traceback.print_stack()
2347
2348 # Works with the test driver to conditionally skip tests via decorators.
2349 Base.setUp(self)
2350
Johnny Chena74bb0a2011-08-01 18:46:13 +00002351 try:
2352 if lldb.blacklist:
2353 className = self.__class__.__name__
2354 classAndMethodName = "%s.%s" % (className, self._testMethodName)
2355 if className in lldb.blacklist:
2356 self.skipTest(lldb.blacklist.get(className))
2357 elif classAndMethodName in lldb.blacklist:
2358 self.skipTest(lldb.blacklist.get(classAndMethodName))
2359 except AttributeError:
2360 pass
2361
Johnny Chened492022011-06-21 00:53:00 +00002362 # Insert some delay between successive test cases if specified.
2363 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00002364
Johnny Chenf2b70232010-08-25 18:49:48 +00002365 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2366 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2367
Johnny Chen430eb762010-10-19 16:00:42 +00002368 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002369 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002370
Daniel Maleae0f8f572013-08-26 23:57:52 +00002371 #
2372 # Warning: MAJOR HACK AHEAD!
2373 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
2374 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
2375 # command, instead. See also runCmd() where it decorates the "file filename" call
2376 # with additional functionality when running testsuite remotely.
2377 #
2378 if lldb.lldbtest_remote_sandbox:
2379 def DecoratedCreateTarget(arg):
2380 self.runCmd("file %s" % arg)
2381 target = self.dbg.GetSelectedTarget()
2382 #
Greg Claytonc6947512013-12-13 19:18:59 +00002383 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00002384 # johnny @ 04/23/2012
2385 #
2386 def DecoratedLaunchSimple(argv, envp, wd):
2387 self.runCmd("run")
2388 return target.GetProcess()
2389 target.LaunchSimple = DecoratedLaunchSimple
2390
2391 return target
2392 self.dbg.CreateTarget = DecoratedCreateTarget
2393 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002394 print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
Daniel Maleae0f8f572013-08-26 23:57:52 +00002395
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002396 # We want our debugger to be synchronous.
2397 self.dbg.SetAsync(False)
2398
2399 # Retrieve the associated command interpreter instance.
2400 self.ci = self.dbg.GetCommandInterpreter()
2401 if not self.ci:
2402 raise Exception('Could not get the command interpreter')
2403
2404 # And the result object.
2405 self.res = lldb.SBCommandReturnObject()
2406
Johnny Chen44d24972012-04-16 18:55:15 +00002407 # Run global pre-flight code, if defined via the config file.
2408 if lldb.pre_flight:
2409 lldb.pre_flight(self)
2410
Enrico Granatabd0998a2015-10-02 22:53:32 +00002411 if lldb.remote_platform and lldb.remote_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002412 remote_test_dir = lldbutil.join_remote_paths(
2413 lldb.remote_platform_working_dir,
2414 self.getArchitecture(),
2415 str(self.test_number),
2416 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002417 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002418 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002419 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002420
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002421 # This function removes all files from the current working directory while leaving
2422 # the directories in place. The cleaup is required to reduce the disk space required
2423 # by the test suit while leaving the directories untached is neccessary because
2424 # sub-directories might belong to an other test
2425 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002426 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002427 # TODO: Replace the heuristic to remove the files with a logic what collects the
2428 # list of files we have to remove during test runs.
2429 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002430 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002431 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002432 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002433 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002434
Greg Clayton35c91342014-11-17 18:40:27 +00002435 def registerSharedLibrariesWithTarget(self, target, shlibs):
2436 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2437
2438 Any modules in the target that have their remote install file specification set will
2439 get uploaded to the remote host. This function registers the local copies of the
2440 shared libraries with the target and sets their remote install locations so they will
2441 be uploaded when the target is run.
2442 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002443 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002444 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002445
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002446 shlib_environment_var = self.platformContext.shlib_environment_var
2447 shlib_prefix = self.platformContext.shlib_prefix
2448 shlib_extension = '.' + self.platformContext.shlib_extension
2449
2450 working_dir = self.get_process_working_directory()
2451 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2452 # Add any shared libraries to our target if remote so they get
2453 # uploaded into the working directory on the remote side
2454 for name in shlibs:
2455 # The path can be a full path to a shared library, or a make file name like "Foo" for
2456 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2457 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2458 # of the shared library accordingly
2459 if os.path.exists(name):
2460 local_shlib_path = name # name is the full path to the local shared library
2461 else:
2462 # Check relative names
2463 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2464 if not os.path.exists(local_shlib_path):
2465 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002466 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002467 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002468
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002469 # Make sure we found the local shared library in the above code
2470 self.assertTrue(os.path.exists(local_shlib_path))
2471
2472 # Add the shared library to our target
2473 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2474 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002475 # We must set the remote install location if we want the shared library
2476 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002477 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002478 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002479
2480 return environment
2481
Enrico Granata44818162012-10-24 01:23:57 +00002482 # utility methods that tests can use to access the current objects
2483 def target(self):
2484 if not self.dbg:
2485 raise Exception('Invalid debugger instance')
2486 return self.dbg.GetSelectedTarget()
2487
2488 def process(self):
2489 if not self.dbg:
2490 raise Exception('Invalid debugger instance')
2491 return self.dbg.GetSelectedTarget().GetProcess()
2492
2493 def thread(self):
2494 if not self.dbg:
2495 raise Exception('Invalid debugger instance')
2496 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2497
2498 def frame(self):
2499 if not self.dbg:
2500 raise Exception('Invalid debugger instance')
2501 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2502
Greg Claytonc6947512013-12-13 19:18:59 +00002503 def get_process_working_directory(self):
2504 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2505 if lldb.remote_platform:
2506 # Remote tests set the platform working directory up in TestBase.setUp()
2507 return lldb.remote_platform.GetWorkingDirectory()
2508 else:
2509 # local tests change directory into each test subdirectory
2510 return os.getcwd()
2511
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002512 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002513 #import traceback
2514 #traceback.print_stack()
2515
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002516 # Ensure all the references to SB objects have gone away so that we can
2517 # be sure that all test-specific resources have been freed before we
2518 # attempt to delete the targets.
2519 gc.collect()
2520
Johnny Chen3794ad92011-06-15 21:24:24 +00002521 # Delete the target(s) from the debugger as a general cleanup step.
2522 # This includes terminating the process for each target, if any.
2523 # We'd like to reuse the debugger for our next test without incurring
2524 # the initialization overhead.
2525 targets = []
2526 for target in self.dbg:
2527 if target:
2528 targets.append(target)
2529 process = target.GetProcess()
2530 if process:
2531 rc = self.invoke(process, "Kill")
2532 self.assertTrue(rc.Success(), PROCESS_KILLED)
2533 for target in targets:
2534 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002535
Johnny Chen44d24972012-04-16 18:55:15 +00002536 # Run global post-flight code, if defined via the config file.
2537 if lldb.post_flight:
2538 lldb.post_flight(self)
2539
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002540 # Do this last, to make sure it's in reverse order from how we setup.
2541 Base.tearDown(self)
2542
Zachary Turner95812042015-03-26 18:54:21 +00002543 # This must be the last statement, otherwise teardown hooks or other
2544 # lines might depend on this still being active.
2545 del self.dbg
2546
Johnny Chen86268e42011-09-30 21:48:35 +00002547 def switch_to_thread_with_stop_reason(self, stop_reason):
2548 """
2549 Run the 'thread list' command, and select the thread with stop reason as
2550 'stop_reason'. If no such thread exists, no select action is done.
2551 """
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002552 from .lldbutil import stop_reason_to_str
Johnny Chen86268e42011-09-30 21:48:35 +00002553 self.runCmd('thread list')
2554 output = self.res.GetOutput()
2555 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2556 stop_reason_to_str(stop_reason))
2557 for line in output.splitlines():
2558 matched = thread_line_pattern.match(line)
2559 if matched:
2560 self.runCmd('thread select %s' % matched.group(1))
2561
Enrico Granata7594f142013-06-17 22:51:50 +00002562 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002563 """
2564 Ask the command interpreter to handle the command and then check its
2565 return status.
2566 """
2567 # Fail fast if 'cmd' is not meaningful.
2568 if not cmd or len(cmd) == 0:
2569 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002570
Johnny Chen8d55a342010-08-31 17:42:54 +00002571 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002572
Daniel Maleae0f8f572013-08-26 23:57:52 +00002573 # This is an opportunity to insert the 'platform target-install' command if we are told so
2574 # via the settig of lldb.lldbtest_remote_sandbox.
2575 if cmd.startswith("target create "):
2576 cmd = cmd.replace("target create ", "file ")
2577 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
2578 with recording(self, trace) as sbuf:
2579 the_rest = cmd.split("file ")[1]
2580 # Split the rest of the command line.
2581 atoms = the_rest.split()
2582 #
2583 # NOTE: This assumes that the options, if any, follow the file command,
2584 # instead of follow the specified target.
2585 #
2586 target = atoms[-1]
2587 # Now let's get the absolute pathname of our target.
2588 abs_target = os.path.abspath(target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002589 print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002590 fpath, fname = os.path.split(abs_target)
2591 parent_dir = os.path.split(fpath)[0]
2592 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
Zachary Turnerff890da2015-10-19 23:45:41 +00002593 print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002594 self.ci.HandleCommand(platform_target_install_command, self.res)
2595 # And this is the file command we want to execute, instead.
2596 #
2597 # Warning: SIDE EFFECT AHEAD!!!
2598 # Populate the remote executable pathname into the lldb namespace,
2599 # so that test cases can grab this thing out of the namespace.
2600 #
2601 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
2602 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002603 print("And this is the replaced file command: %s" % cmd, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002604
Johnny Chen63dfb272010-09-01 00:15:19 +00002605 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002606
Johnny Chen63dfb272010-09-01 00:15:19 +00002607 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002608 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002609
Johnny Chen150c3cc2010-10-15 01:18:29 +00002610 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002611 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002612 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002613 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002614 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002615 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002616 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002617 print("runCmd failed!", file=sbuf)
2618 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002619
Johnny Chenff3d01d2010-08-20 21:03:09 +00002620 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002621 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002622 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002623 # For process launch, wait some time before possible next try.
2624 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002625 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002626 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002627
Johnny Chen27f212d2010-08-19 23:26:59 +00002628 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002629 self.assertTrue(self.res.Succeeded(),
2630 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002631
Jim Ingham63dfc722012-09-22 00:05:11 +00002632 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2633 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2634
2635 Otherwise, all the arguments have the same meanings as for the expect function"""
2636
2637 trace = (True if traceAlways else trace)
2638
2639 if exe:
2640 # First run the command. If we are expecting error, set check=False.
2641 # Pass the assert message along since it provides more semantic info.
2642 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2643
2644 # Then compare the output against expected strings.
2645 output = self.res.GetError() if error else self.res.GetOutput()
2646
2647 # If error is True, the API client expects the command to fail!
2648 if error:
2649 self.assertFalse(self.res.Succeeded(),
2650 "Command '" + str + "' is expected to fail!")
2651 else:
2652 # No execution required, just compare str against the golden input.
2653 output = str
2654 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002655 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002656
2657 # The heading says either "Expecting" or "Not expecting".
2658 heading = "Expecting" if matching else "Not expecting"
2659
2660 for pattern in patterns:
2661 # Match Objects always have a boolean value of True.
2662 match_object = re.search(pattern, output)
2663 matched = bool(match_object)
2664 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002665 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2666 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002667 if matched:
2668 break
2669
2670 self.assertTrue(matched if matching else not matched,
2671 msg if msg else EXP_MSG(str, exe))
2672
2673 return match_object
2674
Enrico Granata7594f142013-06-17 22:51:50 +00002675 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 +00002676 """
2677 Similar to runCmd; with additional expect style output matching ability.
2678
2679 Ask the command interpreter to handle the command and then check its
2680 return status. The 'msg' parameter specifies an informational assert
2681 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002682 'startstr', matches the substrings contained in 'substrs', and regexp
2683 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002684
2685 If the keyword argument error is set to True, it signifies that the API
2686 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002687 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002688 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002689
2690 If the keyword argument matching is set to False, it signifies that the API
2691 client is expecting the output of the command not to match the golden
2692 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002693
2694 Finally, the required argument 'str' represents the lldb command to be
2695 sent to the command interpreter. In case the keyword argument 'exe' is
2696 set to False, the 'str' is treated as a string to be matched/not-matched
2697 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002698 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002699 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002700
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002701 if exe:
2702 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002703 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002704 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002705
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002706 # Then compare the output against expected strings.
2707 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002708
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002709 # If error is True, the API client expects the command to fail!
2710 if error:
2711 self.assertFalse(self.res.Succeeded(),
2712 "Command '" + str + "' is expected to fail!")
2713 else:
2714 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002715 if isinstance(str,lldb.SBCommandReturnObject):
2716 output = str.GetOutput()
2717 else:
2718 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002719 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002720 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002721
Johnny Chenea88e942010-09-21 21:08:53 +00002722 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002723 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002724
2725 # Start from the startstr, if specified.
2726 # If there's no startstr, set the initial state appropriately.
2727 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002728
Johnny Chen150c3cc2010-10-15 01:18:29 +00002729 if startstr:
2730 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002731 print("%s start string: %s" % (heading, startstr), file=sbuf)
2732 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002733
Johnny Chen86268e42011-09-30 21:48:35 +00002734 # Look for endstr, if specified.
2735 keepgoing = matched if matching else not matched
2736 if endstr:
2737 matched = output.endswith(endstr)
2738 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002739 print("%s end string: %s" % (heading, endstr), file=sbuf)
2740 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002741
Johnny Chenea88e942010-09-21 21:08:53 +00002742 # Look for sub strings, if specified.
2743 keepgoing = matched if matching else not matched
2744 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002745 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002746 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002747 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002748 print("%s sub string: %s" % (heading, str), file=sbuf)
2749 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002750 keepgoing = matched if matching else not matched
2751 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002752 break
2753
Johnny Chenea88e942010-09-21 21:08:53 +00002754 # Search for regular expression patterns, if specified.
2755 keepgoing = matched if matching else not matched
2756 if patterns and keepgoing:
2757 for pattern in patterns:
2758 # Match Objects always have a boolean value of True.
2759 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002760 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002761 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2762 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002763 keepgoing = matched if matching else not matched
2764 if not keepgoing:
2765 break
Johnny Chenea88e942010-09-21 21:08:53 +00002766
2767 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002768 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002769
Johnny Chenf3c59232010-08-25 22:52:45 +00002770 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002771 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002772 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002773
2774 method = getattr(obj, name)
2775 import inspect
2776 self.assertTrue(inspect.ismethod(method),
2777 name + "is a method name of object: " + str(obj))
2778 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002779 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002780 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002781 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002782
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002783 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2784 """Platform specific way to build the default binaries."""
2785 if lldb.skip_build_and_cleanup:
2786 return
2787 module = builder_module()
2788 if target_is_android():
2789 dictionary = append_android_envs(dictionary)
2790 if self.debug_info is None:
2791 return self.buildDefault(architecture, compiler, dictionary, clean)
2792 elif self.debug_info == "dsym":
2793 return self.buildDsym(architecture, compiler, dictionary, clean)
2794 elif self.debug_info == "dwarf":
2795 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002796 elif self.debug_info == "dwo":
2797 return self.buildDwo(architecture, compiler, dictionary, clean)
2798 else:
2799 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002800
Johnny Chenf359cf22011-05-27 23:36:52 +00002801 # =================================================
2802 # Misc. helper methods for debugging test execution
2803 # =================================================
2804
Johnny Chen56b92a72011-07-11 19:15:11 +00002805 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002806 """Debug print a SBValue object, if traceAlways is True."""
Zachary Turnerc1b7cd72015-11-05 19:22:28 +00002807 from .lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002808
Johnny Chen8d55a342010-08-31 17:42:54 +00002809 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002810 return
2811
2812 err = sys.stderr
2813 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002814 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2815 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2816 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2817 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2818 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2819 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2820 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2821 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2822 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002823
Johnny Chen36c5eb12011-08-05 20:17:27 +00002824 def DebugSBType(self, type):
2825 """Debug print a SBType object, if traceAlways is True."""
2826 if not traceAlways:
2827 return
2828
2829 err = sys.stderr
2830 err.write(type.GetName() + ":\n")
2831 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2832 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2833 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2834
Johnny Chenb877f1e2011-03-12 01:18:19 +00002835 def DebugPExpect(self, child):
2836 """Debug the spwaned pexpect object."""
2837 if not traceAlways:
2838 return
2839
Zachary Turnerff890da2015-10-19 23:45:41 +00002840 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002841
2842 @classmethod
2843 def RemoveTempFile(cls, file):
2844 if os.path.exists(file):
2845 os.remove(file)