blob: 8fbb0e9216964060dd13af208e367119f4d53691 [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
35
Zachary Turner43a01e42015-10-20 21:06:05 +000036import lldb_shared
37
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000038import abc
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +000039import gc
Vince Harron9753dd92015-05-10 15:22:09 +000040import glob
Johnny Chen90312a82010-09-21 22:34:45 +000041import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000042import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000043import re
Daniel Malea69207462013-06-05 21:07:02 +000044import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000045from subprocess import *
Johnny Chenf2b70232010-08-25 18:49:48 +000046import time
Johnny Chena33a93c2010-08-30 23:08:52 +000047import types
Johnny Chen73258832010-08-05 23:42:46 +000048import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +000049import lldb
Vince Harron9753dd92015-05-10 15:22:09 +000050import lldbtest_config
Chaoren Lin3e2bdb42015-05-11 17:53:39 +000051import lldbutil
Pavel Labathdc8b2d32015-10-26 09:28:32 +000052import test_categories
Zachary Turner43a01e42015-10-20 21:06:05 +000053
54from six import add_metaclass
Zachary Turner814236d2015-10-21 17:48:52 +000055from six import StringIO as SixStringIO
56from six.moves.urllib import parse as urlparse
Siva Chandra8af91662015-06-05 00:22:49 +000057
Vince Harron85d19652015-05-21 19:09:29 +000058# dosep.py starts lots and lots of dotest instances
59# This option helps you find if two (or more) dotest instances are using the same
60# directory at the same time
61# Enable it to cause test failures and stderr messages if dotest instances try to run in
62# the same directory simultaneously
63# it is disabled by default because it litters the test directories with ".dirlock" files
64debug_confirm_directory_exclusivity = False
65
Johnny Chen707b3c92010-10-11 22:25:46 +000066# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000067# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000068
69# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000070if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
71 traceAlways = True
72else:
73 traceAlways = False
74
Johnny Chen707b3c92010-10-11 22:25:46 +000075# By default, doCleanup is True.
76if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
77 doCleanup = False
78else:
79 doCleanup = True
80
Johnny Chen8d55a342010-08-31 17:42:54 +000081
Johnny Chen00778092010-08-09 22:01:17 +000082#
83# Some commonly used assert messages.
84#
85
Johnny Chenaa902922010-09-17 22:45:27 +000086COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
87
Johnny Chen00778092010-08-09 22:01:17 +000088CURRENT_EXECUTABLE_SET = "Current executable set successfully"
89
Johnny Chen7d1d7532010-09-02 21:23:12 +000090PROCESS_IS_VALID = "Process is valid"
91
92PROCESS_KILLED = "Process is killed successfully"
93
Johnny Chend5f66fc2010-12-23 01:12:19 +000094PROCESS_EXITED = "Process exited successfully"
95
96PROCESS_STOPPED = "Process status should be stopped"
97
Sean Callanan05834cd2015-07-01 23:56:30 +000098RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +000099
Johnny Chen17941842010-08-09 23:44:24 +0000100RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000101
Johnny Chen67af43f2010-10-05 19:27:32 +0000102BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
103
Johnny Chen17941842010-08-09 23:44:24 +0000104BREAKPOINT_CREATED = "Breakpoint created successfully"
105
Johnny Chenf10af382010-12-04 00:07:24 +0000106BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
107
Johnny Chene76896c2010-08-17 21:33:31 +0000108BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
109
Johnny Chen17941842010-08-09 23:44:24 +0000110BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000111
Johnny Chen703dbd02010-09-30 17:06:24 +0000112BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
113
Johnny Chen164f1e12010-10-15 18:07:09 +0000114BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
115
Greg Clayton5db6b792012-10-24 18:24:14 +0000116MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
117
Johnny Chen89109ed12011-06-27 20:05:23 +0000118OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
119
Johnny Chen5b3a3572010-12-09 18:22:12 +0000120SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
121
Johnny Chenc70b02a2010-09-22 23:00:20 +0000122STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
123
Johnny Chen1691a162011-04-15 16:44:48 +0000124STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
125
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000126STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
127
Johnny Chen5d6c4642010-11-10 23:46:38 +0000128STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000129
Johnny Chen5d6c4642010-11-10 23:46:38 +0000130STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
131 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000132
Johnny Chen2e431ce2010-10-20 18:38:48 +0000133STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
134
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000135STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
136
Johnny Chenc066ab42010-10-14 01:22:03 +0000137STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
138
Johnny Chen00778092010-08-09 22:01:17 +0000139STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
140
Johnny Chenf68cc122011-09-15 21:09:59 +0000141STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
142
Johnny Chen3c884a02010-08-24 22:07:56 +0000143DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
144
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000145VALID_BREAKPOINT = "Got a valid breakpoint"
146
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000147VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
148
Johnny Chen7209d84f2011-05-06 23:26:12 +0000149VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
150
Johnny Chen5ee88192010-08-27 23:47:36 +0000151VALID_FILESPEC = "Got a valid filespec"
152
Johnny Chen025d1b82010-12-08 01:25:21 +0000153VALID_MODULE = "Got a valid module"
154
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000155VALID_PROCESS = "Got a valid process"
156
Johnny Chen025d1b82010-12-08 01:25:21 +0000157VALID_SYMBOL = "Got a valid symbol"
158
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000159VALID_TARGET = "Got a valid target"
160
Matthew Gardinerc928de32014-10-22 07:22:56 +0000161VALID_PLATFORM = "Got a valid platform"
162
Johnny Chen15f247a2012-02-03 20:43:00 +0000163VALID_TYPE = "Got a valid type"
164
Johnny Chen5819ab42011-07-15 22:28:10 +0000165VALID_VARIABLE = "Got a valid variable"
166
Johnny Chen981463d2010-08-25 19:00:04 +0000167VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000168
Johnny Chenf68cc122011-09-15 21:09:59 +0000169WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000170
Sean Callanan05834cd2015-07-01 23:56:30 +0000171def CMD_MSG(str):
172 '''A generic "Command '%s' returns successfully" message generator.'''
173 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000174
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000175def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000176 '''A generic message generator for the completion mechanism.'''
177 return "'%s' successfully completes to '%s'" % (str_before, str_after)
178
Johnny Chenc0c67f22010-11-09 18:42:22 +0000179def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000180 '''A generic "'%s' returns expected result" message generator if exe.
181 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000182 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000183
Johnny Chen3343f042010-10-19 19:11:38 +0000184def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000185 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000186 return "Value of setting '%s' is correct" % setting
187
Johnny Chen27c41232010-08-26 21:49:29 +0000188def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000189 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000190 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000191
Johnny Chen47ceb032010-10-11 23:52:19 +0000192def line_number(filename, string_to_match):
193 """Helper function to return the line number of the first matched string."""
194 with open(filename, 'r') as f:
195 for i, line in enumerate(f):
196 if line.find(string_to_match) != -1:
197 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000198 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000199 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000200
Johnny Chen67af43f2010-10-05 19:27:32 +0000201def pointer_size():
202 """Return the pointer size of the host system."""
203 import ctypes
204 a_pointer = ctypes.c_void_p(0xffff)
205 return 8 * ctypes.sizeof(a_pointer)
206
Johnny Chen57816732012-02-09 02:01:59 +0000207def is_exe(fpath):
208 """Returns true if fpath is an executable."""
209 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
210
211def which(program):
212 """Returns the full path to a program; None otherwise."""
213 fpath, fname = os.path.split(program)
214 if fpath:
215 if is_exe(program):
216 return program
217 else:
218 for path in os.environ["PATH"].split(os.pathsep):
219 exe_file = os.path.join(path, program)
220 if is_exe(exe_file):
221 return exe_file
222 return None
223
Zachary Turner814236d2015-10-21 17:48:52 +0000224class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000225 """
226 A nice little context manager for recording the debugger interactions into
227 our session object. If trace flag is ON, it also emits the interactions
228 into the stderr.
229 """
230 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000231 """Create a SixStringIO instance; record the session obj and trace flag."""
232 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000233 # The test might not have undergone the 'setUp(self)' phase yet, so that
234 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000235 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000236 self.trace = trace
237
238 def __enter__(self):
239 """
240 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000241 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000242 """
243 return self
244
245 def __exit__(self, type, value, tb):
246 """
247 Context management protocol on exit from the body of the with statement.
248 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000249 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000250 """
251 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000252 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000253 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000254 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000255 self.close()
256
Zachary Turner43a01e42015-10-20 21:06:05 +0000257@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000258class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000259
260 @abc.abstractproperty
261 def pid(self):
262 """Returns process PID if has been launched already."""
263
264 @abc.abstractmethod
265 def launch(self, executable, args):
266 """Launches new process with given executable and args."""
267
268 @abc.abstractmethod
269 def terminate(self):
270 """Terminates previously launched process.."""
271
272class _LocalProcess(_BaseProcess):
273
274 def __init__(self, trace_on):
275 self._proc = None
276 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000277 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000278
279 @property
280 def pid(self):
281 return self._proc.pid
282
283 def launch(self, executable, args):
284 self._proc = Popen([executable] + args,
285 stdout = open(os.devnull) if not self._trace_on else None,
286 stdin = PIPE)
287
288 def terminate(self):
289 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000290 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000291 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
292 for sig in signals_to_try:
293 try:
294 self._proc.send_signal(getattr(signal, sig))
295 time.sleep(self._delayafterterminate)
296 if self._proc.poll() != None:
297 return
298 except ValueError:
299 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000300 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000301 time.sleep(self._delayafterterminate)
302 if self._proc.poll() != None:
303 return
304 self._proc.kill()
305 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000306
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000307 def poll(self):
308 return self._proc.poll()
309
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000310class _RemoteProcess(_BaseProcess):
311
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000312 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000313 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000314 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000315
316 @property
317 def pid(self):
318 return self._pid
319
320 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000321 if self._install_remote:
322 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000323 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000324
325 dst_file_spec = lldb.SBFileSpec(dst_path, False)
326 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
327 if err.Fail():
328 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
329 else:
330 dst_path = executable
331 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000332
333 launch_info = lldb.SBLaunchInfo(args)
334 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000335 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000336
337 # Redirect stdout and stderr to /dev/null
338 launch_info.AddSuppressFileAction(1, False, True)
339 launch_info.AddSuppressFileAction(2, False, True)
340
341 err = lldb.remote_platform.Launch(launch_info)
342 if err.Fail():
343 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
344 self._pid = launch_info.GetProcessID()
345
346 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000347 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000348
Johnny Chen690fcef2010-10-15 23:55:05 +0000349# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000350# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000351def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000352 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000353
354 If the exit code was non-zero it raises a CalledProcessError. The
355 CalledProcessError object will have the return code in the returncode
356 attribute and output in the output attribute.
357
358 The arguments are the same as for the Popen constructor. Example:
359
360 >>> check_output(["ls", "-l", "/dev/null"])
361 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
362
363 The stdout argument is not allowed as it is used internally.
364 To capture standard error in the result, use stderr=STDOUT.
365
366 >>> check_output(["/bin/sh", "-c",
367 ... "ls -l non_existent_file ; exit 0"],
368 ... stderr=STDOUT)
369 'ls: non_existent_file: No such file or directory\n'
370 """
371
372 # Assign the sender object to variable 'test' and remove it from kwargs.
373 test = kwargs.pop('sender', None)
374
Zachary Turner9ef307b2014-07-22 16:19:29 +0000375 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
376 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000377 output = ""
378 error = ""
379 for shellCommand in commandList:
380 if 'stdout' in kwargs:
381 raise ValueError('stdout argument not allowed, it will be overridden.')
382 if 'shell' in kwargs and kwargs['shell']==False:
383 raise ValueError('shell=False not allowed')
384 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
385 pid = process.pid
386 this_output, this_error = process.communicate()
387 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000388
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000389 # Enable trace on failure return while tracking down FreeBSD buildbot issues
390 trace = traceAlways
391 if not trace and retcode and sys.platform.startswith("freebsd"):
392 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000393
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000394 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000395 print(file=sbuf)
396 print("os command:", shellCommand, file=sbuf)
397 print("with pid:", pid, file=sbuf)
398 print("stdout:", this_output, file=sbuf)
399 print("stderr:", this_error, file=sbuf)
400 print("retcode:", retcode, file=sbuf)
401 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000402
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000403 if retcode:
404 cmd = kwargs.get("args")
405 if cmd is None:
406 cmd = shellCommand
407 raise CalledProcessError(retcode, cmd)
408 output = output + this_output
409 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000410 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000411
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000412def getsource_if_available(obj):
413 """
414 Return the text of the source code for an object if available. Otherwise,
415 a print representation is returned.
416 """
417 import inspect
418 try:
419 return inspect.getsource(obj)
420 except:
421 return repr(obj)
422
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000423def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000424 if sys.platform.startswith("freebsd"):
425 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000426 return __import__("builder_" + sys.platform)
427
Siva Chandra8af91662015-06-05 00:22:49 +0000428def run_adb_command(cmd, device_id):
429 device_id_args = []
430 if device_id:
431 device_id_args = ["-s", device_id]
432 full_cmd = ["adb"] + device_id_args + cmd
433 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
434 stdout, stderr = p.communicate()
435 return p.returncode, stdout, stderr
436
Chaoren Line9bbabc2015-07-18 00:37:55 +0000437def append_android_envs(dictionary):
438 if dictionary is None:
439 dictionary = {}
440 dictionary["OS"] = "Android"
441 if android_device_api() >= 16:
442 dictionary["PIE"] = 1
443 return dictionary
444
Chaoren Lin9070f532015-07-17 22:13:29 +0000445def target_is_android():
446 if not hasattr(target_is_android, 'result'):
447 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
448 match = re.match(".*-.*-.*-android", triple)
449 target_is_android.result = match is not None
450 return target_is_android.result
451
Siva Chandra8af91662015-06-05 00:22:49 +0000452def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000453 if not hasattr(android_device_api, 'result'):
454 assert lldb.platform_url is not None
455 device_id = None
456 parsed_url = urlparse.urlparse(lldb.platform_url)
457 if parsed_url.scheme == "adb":
458 device_id = parsed_url.netloc.split(":")[0]
459 retcode, stdout, stderr = run_adb_command(
460 ["shell", "getprop", "ro.build.version.sdk"], device_id)
461 if retcode == 0:
462 android_device_api.result = int(stdout)
463 else:
464 raise LookupError(
465 ">>> Unable to determine the API level of the Android device.\n"
466 ">>> stdout:\n%s\n"
467 ">>> stderr:\n%s\n" % (stdout, stderr))
468 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000469
Johnny Chena74bb0a2011-08-01 18:46:13 +0000470#
471# Decorators for categorizing test cases.
472#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000473from functools import wraps
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000474def add_test_categories(cat):
475 """Decorate an item with test categories"""
476 cat = test_categories.validate(cat, True)
477 def impl(func):
478 func.getCategories = lambda test: cat
479 return func
480 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000481
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000482def lldbmi_test(func):
483 """Decorate the item as a lldb-mi only test."""
484 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
485 raise Exception("@lldbmi_test can only be used to decorate a test method")
486 @wraps(func)
487 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000488 if lldb.dont_do_lldbmi_test:
489 self.skipTest("lldb-mi tests")
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000490 return func(self, *args, **kwargs)
491
492 # Mark this function as such to separate them from lldb command line tests.
493 wrapper.__lldbmi_test__ = True
494 return wrapper
495
Johnny Chena74bb0a2011-08-01 18:46:13 +0000496def benchmarks_test(func):
497 """Decorate the item as a benchmarks test."""
498 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
499 raise Exception("@benchmarks_test can only be used to decorate a test method")
500 @wraps(func)
501 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000502 if not lldb.just_do_benchmarks_test:
503 self.skipTest("benchmarks tests")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000504 return func(self, *args, **kwargs)
505
506 # Mark this function as such to separate them from the regular tests.
507 wrapper.__benchmarks_test__ = True
508 return wrapper
509
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000510def no_debug_info_test(func):
511 """Decorate the item as a test what don't use any debug info. If this annotation is specified
512 then the test runner won't generate a separate test for each debug info format. """
513 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
514 raise Exception("@no_debug_info_test can only be used to decorate a test method")
515 @wraps(func)
516 def wrapper(self, *args, **kwargs):
517 return func(self, *args, **kwargs)
518
519 # Mark this function as such to separate them from the regular tests.
520 wrapper.__no_debug_info_test__ = True
521 return wrapper
522
Johnny Chenf1548d42012-04-06 00:56:05 +0000523def dsym_test(func):
524 """Decorate the item as a dsym test."""
525 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
526 raise Exception("@dsym_test can only be used to decorate a test method")
527 @wraps(func)
528 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000529 if lldb.dont_do_dsym_test:
530 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000531 return func(self, *args, **kwargs)
532
533 # Mark this function as such to separate them from the regular tests.
534 wrapper.__dsym_test__ = True
535 return wrapper
536
537def dwarf_test(func):
538 """Decorate the item as a dwarf test."""
539 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
540 raise Exception("@dwarf_test can only be used to decorate a test method")
541 @wraps(func)
542 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000543 if lldb.dont_do_dwarf_test:
544 self.skipTest("dwarf tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000545 return func(self, *args, **kwargs)
546
547 # Mark this function as such to separate them from the regular tests.
548 wrapper.__dwarf_test__ = True
549 return wrapper
550
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000551def dwo_test(func):
552 """Decorate the item as a dwo test."""
553 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
554 raise Exception("@dwo_test can only be used to decorate a test method")
555 @wraps(func)
556 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000557 if lldb.dont_do_dwo_test:
558 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000559 return func(self, *args, **kwargs)
560
561 # Mark this function as such to separate them from the regular tests.
562 wrapper.__dwo_test__ = True
563 return wrapper
564
Todd Fialaa41d48c2014-04-28 04:49:40 +0000565def debugserver_test(func):
566 """Decorate the item as a debugserver test."""
567 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
568 raise Exception("@debugserver_test can only be used to decorate a test method")
569 @wraps(func)
570 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000571 if lldb.dont_do_debugserver_test:
572 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000573 return func(self, *args, **kwargs)
574
575 # Mark this function as such to separate them from the regular tests.
576 wrapper.__debugserver_test__ = True
577 return wrapper
578
579def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000580 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000581 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
582 raise Exception("@llgs_test can only be used to decorate a test method")
583 @wraps(func)
584 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000585 if lldb.dont_do_llgs_test:
586 self.skipTest("llgs tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000587 return func(self, *args, **kwargs)
588
589 # Mark this function as such to separate them from the regular tests.
590 wrapper.__llgs_test__ = True
591 return wrapper
592
Daniel Maleae0f8f572013-08-26 23:57:52 +0000593def not_remote_testsuite_ready(func):
594 """Decorate the item as a test which is not ready yet for remote testsuite."""
595 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
596 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
597 @wraps(func)
598 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000599 if lldb.lldbtest_remote_sandbox or lldb.remote_platform:
600 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000601 return func(self, *args, **kwargs)
602
603 # Mark this function as such to separate them from the regular tests.
604 wrapper.__not_ready_for_remote_testsuite_test__ = True
605 return wrapper
606
Ed Maste433790a2014-04-23 12:55:41 +0000607def expectedFailure(expected_fn, bugnumber=None):
608 def expectedFailure_impl(func):
609 @wraps(func)
610 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000611 from unittest2 import case
612 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000613 try:
Ed Maste433790a2014-04-23 12:55:41 +0000614 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000615 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000616 if expected_fn(self):
617 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000618 else:
619 raise
Ed Maste433790a2014-04-23 12:55:41 +0000620 if expected_fn(self):
621 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
622 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000623 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
624 # return decorator in this case, so it will be used to decorating original method
625 if callable(bugnumber):
626 return expectedFailure_impl(bugnumber)
627 else:
628 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000629
Ying Chen7091c2c2015-04-21 01:15:47 +0000630# provide a function to xfail on defined oslist, compiler version, and archs
631# if none is specified for any argument, that argument won't be checked and thus means for all
632# for example,
633# @expectedFailureAll, xfail for all platform/compiler/arch,
634# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
635# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000636def expectedFailureAll(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None):
Ying Chen7091c2c2015-04-21 01:15:47 +0000637 def fn(self):
638 return ((oslist is None or self.getPlatform() in oslist) and
639 (compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))) and
Tamas Berghammercf6f92a2015-09-07 15:50:19 +0000640 self.expectedArch(archs) and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000641 (triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())) and
642 (debug_info is None or self.debug_info in debug_info))
Ying Chen7091c2c2015-04-21 01:15:47 +0000643 return expectedFailure(fn, bugnumber)
644
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000645def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000646 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
647
648def expectedFailureDwo(bugnumber=None):
649 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000650
651def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000652 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000653
654def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
655 if compiler_version is None:
656 compiler_version=['=', None]
657 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
658
Vince Harron8974ce22015-03-13 19:54:54 +0000659# to XFAIL a specific clang versions, try this
660# @expectedFailureClang('bugnumber', ['<=', '3.4'])
661def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000662 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000663
664def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000665 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000666
Matt Kopec0de53f02013-03-15 19:10:12 +0000667def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000668 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000669
Ed Maste433790a2014-04-23 12:55:41 +0000670def expectedFailureArch(arch, bugnumber=None):
671 def fn(self):
672 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000673 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000674
Enrico Granatae6cedc12013-02-23 01:05:23 +0000675def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000676 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000677
Matt Kopecee969f92013-09-26 23:30:59 +0000678def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000679 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000680
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000681def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000682 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000683 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000684 self.expectedCompiler(compilers) and
685 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000686 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000687
Chaoren Linf7160f32015-06-09 17:39:27 +0000688def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
689 def fn(self):
690 return (getHostPlatform() in oslist and
691 self.expectedCompiler(compilers))
692 return expectedFailure(fn, bugnumber)
693
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000694def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000695 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000696 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000697
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000698def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
699 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000700
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000701def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
702 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000703
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000704def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
705 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000706
Chaoren Linf7160f32015-06-09 17:39:27 +0000707def expectedFailureHostWindows(bugnumber=None, compilers=None):
708 return expectedFailureHostOS(['windows'], bugnumber, compilers)
709
Pavel Labath090152b2015-08-20 11:37:19 +0000710def matchAndroid(api_levels=None, archs=None):
711 def match(self):
712 if not target_is_android():
713 return False
714 if archs is not None and self.getArchitecture() not in archs:
715 return False
716 if api_levels is not None and android_device_api() not in api_levels:
717 return False
718 return True
719 return match
720
721
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000722def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000723 """ Mark a test as xfail for Android.
724
725 Arguments:
726 bugnumber - The LLVM pr associated with the problem.
727 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000728 for which a test is expected to fail. None means all API level.
729 arch - A sequence of architecture names specifying the architectures
730 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000731 """
Pavel Labath090152b2015-08-20 11:37:19 +0000732 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000733
Vince Harron7ac3ea42015-06-26 15:13:21 +0000734# if the test passes on the first try, we're done (success)
735# if the test fails once, then passes on the second try, raise an ExpectedFailure
736# if the test fails twice in a row, re-throw the exception from the second test run
737def expectedFlakey(expected_fn, bugnumber=None):
738 def expectedFailure_impl(func):
739 @wraps(func)
740 def wrapper(*args, **kwargs):
741 from unittest2 import case
742 self = args[0]
743 try:
744 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000745 # don't retry if the test case is already decorated with xfail or skip
746 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
747 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000748 except Exception:
749 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000750 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000751 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000752 self.tearDown()
753 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000754 func(*args, **kwargs)
755 except Exception:
756 # oh snap! two failures in a row, record a failure/error
757 raise
758 # record the expected failure
759 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
760 else:
761 raise
762 return wrapper
763 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
764 # return decorator in this case, so it will be used to decorating original method
765 if callable(bugnumber):
766 return expectedFailure_impl(bugnumber)
767 else:
768 return expectedFailure_impl
769
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000770def expectedFlakeyDwarf(bugnumber=None):
771 def fn(self):
772 return self.debug_info == "dwarf"
773 return expectedFlakey(fn, bugnumber)
774
775def expectedFlakeyDsym(bugnumber=None):
776 def fn(self):
777 return self.debug_info == "dwarf"
778 return expectedFlakey(fn, bugnumber)
779
Vince Harron7ac3ea42015-06-26 15:13:21 +0000780def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
781 def fn(self):
782 return (self.getPlatform() in oslist and
783 self.expectedCompiler(compilers))
784 return expectedFlakey(fn, bugnumber)
785
786def expectedFlakeyDarwin(bugnumber=None, compilers=None):
787 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
788 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
789
790def expectedFlakeyLinux(bugnumber=None, compilers=None):
791 return expectedFlakeyOS(['linux'], bugnumber, compilers)
792
793def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
794 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
795
796def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
797 if compiler_version is None:
798 compiler_version=['=', None]
799 def fn(self):
800 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
801 return expectedFlakey(fn, bugnumber)
802
803# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
804def expectedFlakeyClang(bugnumber=None, compiler_version=None):
805 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
806
807# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
808def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
809 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
810
Pavel Labath63a579c2015-09-07 12:15:27 +0000811def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
812 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
813
Greg Clayton12514562013-12-05 22:22:32 +0000814def skipIfRemote(func):
815 """Decorate the item to skip tests if testing remotely."""
816 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
817 raise Exception("@skipIfRemote can only be used to decorate a test method")
818 @wraps(func)
819 def wrapper(*args, **kwargs):
820 from unittest2 import case
821 if lldb.remote_platform:
822 self = args[0]
823 self.skipTest("skip on remote platform")
824 else:
825 func(*args, **kwargs)
826 return wrapper
827
Siva Chandra4470f382015-06-17 22:32:27 +0000828def skipUnlessListedRemote(remote_list=None):
829 def myImpl(func):
830 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
831 raise Exception("@skipIfRemote can only be used to decorate a "
832 "test method")
833
834 @wraps(func)
835 def wrapper(*args, **kwargs):
836 if remote_list and lldb.remote_platform:
837 self = args[0]
838 triple = self.dbg.GetSelectedPlatform().GetTriple()
839 for r in remote_list:
840 if r in triple:
841 func(*args, **kwargs)
842 return
843 self.skipTest("skip on remote platform %s" % str(triple))
844 else:
845 func(*args, **kwargs)
846 return wrapper
847
848 return myImpl
849
Greg Clayton12514562013-12-05 22:22:32 +0000850def skipIfRemoteDueToDeadlock(func):
851 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
852 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
853 raise Exception("@skipIfRemote can only be used to decorate a test method")
854 @wraps(func)
855 def wrapper(*args, **kwargs):
856 from unittest2 import case
857 if lldb.remote_platform:
858 self = args[0]
859 self.skipTest("skip on remote platform (deadlocks)")
860 else:
861 func(*args, **kwargs)
862 return wrapper
863
Enrico Granatab633e432014-10-06 21:37:06 +0000864def skipIfNoSBHeaders(func):
865 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
866 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000867 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000868 @wraps(func)
869 def wrapper(*args, **kwargs):
870 from unittest2 import case
871 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000872 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000873 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000874 else:
875 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000876 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000877 if not os.path.exists(header):
878 self.skipTest("skip because LLDB.h header not found")
879 else:
880 func(*args, **kwargs)
881 return wrapper
882
Robert Flack13c7ad92015-03-30 14:12:17 +0000883def skipIfFreeBSD(func):
884 """Decorate the item to skip tests that should be skipped on FreeBSD."""
885 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000886
Greg Claytone0d0a762015-04-02 18:24:03 +0000887def getDarwinOSTriples():
888 return ['darwin', 'macosx', 'ios']
889
Daniel Maleab3d41a22013-07-09 00:08:01 +0000890def skipIfDarwin(func):
891 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000892 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000893
Robert Flack13c7ad92015-03-30 14:12:17 +0000894def skipIfLinux(func):
895 """Decorate the item to skip tests that should be skipped on Linux."""
896 return skipIfPlatform(["linux"])(func)
897
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000898def skipUnlessHostLinux(func):
899 """Decorate the item to skip tests that should be skipped on any non Linux host."""
900 return skipUnlessHostPlatform(["linux"])(func)
901
Robert Flack13c7ad92015-03-30 14:12:17 +0000902def skipIfWindows(func):
903 """Decorate the item to skip tests that should be skipped on Windows."""
904 return skipIfPlatform(["windows"])(func)
905
Chaoren Line6eea5d2015-06-08 22:13:28 +0000906def skipIfHostWindows(func):
907 """Decorate the item to skip tests that should be skipped on Windows."""
908 return skipIfHostPlatform(["windows"])(func)
909
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000910def skipUnlessWindows(func):
911 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
912 return skipUnlessPlatform(["windows"])(func)
913
Robert Flack13c7ad92015-03-30 14:12:17 +0000914def skipUnlessDarwin(func):
915 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000916 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000917
Ryan Brown57bee1e2015-09-14 22:45:11 +0000918def skipUnlessGoInstalled(func):
919 """Decorate the item to skip tests when no Go compiler is available."""
920 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
921 raise Exception("@skipIfGcc can only be used to decorate a test method")
922 @wraps(func)
923 def wrapper(*args, **kwargs):
924 from unittest2 import case
925 self = args[0]
926 compiler = self.getGoCompilerVersion()
927 if not compiler:
928 self.skipTest("skipping because go compiler not found")
929 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000930 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +0000931 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +0000932 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
933 if not match_version:
934 # Couldn't determine version.
935 self.skipTest(
936 "skipping because go version could not be parsed "
937 "out of {}".format(compiler))
938 else:
939 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +0000940 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +0000941 compiler_strict_version = StrictVersion(match_version.group(1))
942 if compiler_strict_version < min_strict_version:
943 self.skipTest(
944 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +0000945 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +0000946 compiler_strict_version,
947 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +0000948 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +0000949 return wrapper
950
Robert Flack068898c2015-04-09 18:07:58 +0000951def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +0000952 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +0000953 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
954 if platform.startswith('freebsd'):
955 platform = 'freebsd'
956 return platform
957
Robert Flack6e1fd352015-05-15 12:39:33 +0000958def getHostPlatform():
959 """Returns the host platform running the test suite."""
960 # Attempts to return a platform name matching a target Triple platform.
961 if sys.platform.startswith('linux'):
962 return 'linux'
963 elif sys.platform.startswith('win32'):
964 return 'windows'
965 elif sys.platform.startswith('darwin'):
966 return 'darwin'
967 elif sys.platform.startswith('freebsd'):
968 return 'freebsd'
969 else:
970 return sys.platform
971
Robert Flackfb2f6c62015-04-17 08:02:18 +0000972def platformIsDarwin():
973 """Returns true if the OS triple for the selected platform is any valid apple OS"""
974 return getPlatform() in getDarwinOSTriples()
975
Robert Flack6e1fd352015-05-15 12:39:33 +0000976def skipIfHostIncompatibleWithRemote(func):
977 """Decorate the item to skip tests if binaries built on this host are incompatible."""
978 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
979 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
980 @wraps(func)
981 def wrapper(*args, **kwargs):
982 from unittest2 import case
983 self = args[0]
984 host_arch = self.getLldbArchitecture()
985 host_platform = getHostPlatform()
986 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +0000987 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +0000988 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
989 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
990 elif target_platform != host_platform:
991 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
992 else:
993 func(*args, **kwargs)
994 return wrapper
995
Chaoren Line6eea5d2015-06-08 22:13:28 +0000996def skipIfHostPlatform(oslist):
997 """Decorate the item to skip tests if running on one of the listed host platforms."""
998 return unittest2.skipIf(getHostPlatform() in oslist,
999 "skip on %s" % (", ".join(oslist)))
1000
1001def skipUnlessHostPlatform(oslist):
1002 """Decorate the item to skip tests unless running on one of the listed host platforms."""
1003 return unittest2.skipUnless(getHostPlatform() in oslist,
1004 "requires on of %s" % (", ".join(oslist)))
1005
Zachary Turner793d9972015-08-14 23:29:24 +00001006def skipUnlessArch(archlist):
1007 """Decorate the item to skip tests unless running on one of the listed architectures."""
1008 def myImpl(func):
1009 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1010 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1011
1012 @wraps(func)
1013 def wrapper(*args, **kwargs):
1014 self = args[0]
1015 if self.getArchitecture() not in archlist:
1016 self.skipTest("skipping for architecture %s (requires one of %s)" %
1017 (self.getArchitecture(), ", ".join(archlist)))
1018 else:
1019 func(*args, **kwargs)
1020 return wrapper
1021
1022 return myImpl
1023
Robert Flack13c7ad92015-03-30 14:12:17 +00001024def skipIfPlatform(oslist):
1025 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001026 return unittest2.skipIf(getPlatform() in oslist,
1027 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001028
1029def skipUnlessPlatform(oslist):
1030 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001031 return unittest2.skipUnless(getPlatform() in oslist,
1032 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001033
Daniel Malea48359902013-05-14 20:48:54 +00001034def skipIfLinuxClang(func):
1035 """Decorate the item to skip tests that should be skipped if building on
1036 Linux with clang.
1037 """
1038 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1039 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1040 @wraps(func)
1041 def wrapper(*args, **kwargs):
1042 from unittest2 import case
1043 self = args[0]
1044 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001045 platform = self.getPlatform()
1046 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001047 self.skipTest("skipping because Clang is used on Linux")
1048 else:
1049 func(*args, **kwargs)
1050 return wrapper
1051
Ying Chen7091c2c2015-04-21 01:15:47 +00001052# provide a function to skip on defined oslist, compiler version, and archs
1053# if none is specified for any argument, that argument won't be checked and thus means for all
1054# for example,
1055# @skipIf, skip for all platform/compiler/arch,
1056# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1057# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1058
1059# TODO: refactor current code, to make skipIfxxx functions to call this function
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001060def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001061 def fn(self):
1062 return ((oslist is None or self.getPlatform() in oslist) and
1063 (compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))) and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001064 self.expectedArch(archs) and
1065 (debug_info is None or self.debug_info in debug_info))
1066 return skipTestIfFn(fn, bugnumber, skipReason="skipping because os:%s compiler: %s %s arch: %s debug info: %s"%(oslist, compiler, compiler_version, archs, debug_info))
1067
1068def skipIfDebugInfo(bugnumber=None, debug_info=None):
1069 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1070
Greg Claytonedea2372015-10-07 20:01:13 +00001071def skipIfDWO(bugnumber=None):
1072 return skipIfDebugInfo(bugnumber, ["dwo"])
1073
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001074def skipIfDwarf(bugnumber=None):
1075 return skipIfDebugInfo(bugnumber, ["dwarf"])
1076
1077def skipIfDsym(bugnumber=None):
1078 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001079
1080def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1081 def skipTestIfFn_impl(func):
1082 @wraps(func)
1083 def wrapper(*args, **kwargs):
1084 from unittest2 import case
1085 self = args[0]
1086 if expected_fn(self):
1087 self.skipTest(skipReason)
1088 else:
1089 func(*args, **kwargs)
1090 return wrapper
1091 if callable(bugnumber):
1092 return skipTestIfFn_impl(bugnumber)
1093 else:
1094 return skipTestIfFn_impl
1095
Daniel Maleabe230792013-01-24 23:52:09 +00001096def skipIfGcc(func):
1097 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1098 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001099 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001100 @wraps(func)
1101 def wrapper(*args, **kwargs):
1102 from unittest2 import case
1103 self = args[0]
1104 compiler = self.getCompiler()
1105 if "gcc" in compiler:
1106 self.skipTest("skipping because gcc is the test compiler")
1107 else:
1108 func(*args, **kwargs)
1109 return wrapper
1110
Matt Kopec0de53f02013-03-15 19:10:12 +00001111def skipIfIcc(func):
1112 """Decorate the item to skip tests that should be skipped if building with icc ."""
1113 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1114 raise Exception("@skipIfIcc can only be used to decorate a test method")
1115 @wraps(func)
1116 def wrapper(*args, **kwargs):
1117 from unittest2 import case
1118 self = args[0]
1119 compiler = self.getCompiler()
1120 if "icc" in compiler:
1121 self.skipTest("skipping because icc is the test compiler")
1122 else:
1123 func(*args, **kwargs)
1124 return wrapper
1125
Daniel Malea55faa402013-05-02 21:44:31 +00001126def skipIfi386(func):
1127 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1128 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1129 raise Exception("@skipIfi386 can only be used to decorate a test method")
1130 @wraps(func)
1131 def wrapper(*args, **kwargs):
1132 from unittest2 import case
1133 self = args[0]
1134 if "i386" == self.getArchitecture():
1135 self.skipTest("skipping because i386 is not a supported architecture")
1136 else:
1137 func(*args, **kwargs)
1138 return wrapper
1139
Pavel Labath090152b2015-08-20 11:37:19 +00001140def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001141 """Decorator to skip tests when the target is Android.
1142
1143 Arguments:
1144 api_levels - The API levels for which the test should be skipped. If
1145 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001146 arch - A sequence of architecture names specifying the architectures
1147 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001148 """
1149 def myImpl(func):
1150 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1151 raise Exception("@skipIfTargetAndroid can only be used to "
1152 "decorate a test method")
1153 @wraps(func)
1154 def wrapper(*args, **kwargs):
1155 from unittest2 import case
1156 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001157 if matchAndroid(api_levels, archs)(self):
1158 self.skipTest("skiped on Android target with API %d and architecture %s" %
1159 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001160 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001161 return wrapper
1162 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001163
Ilia Kd9953052015-03-12 07:19:41 +00001164def skipUnlessCompilerRt(func):
1165 """Decorate the item to skip tests if testing remotely."""
1166 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1167 raise Exception("@skipUnless can only be used to decorate a test method")
1168 @wraps(func)
1169 def wrapper(*args, **kwargs):
1170 from unittest2 import case
1171 import os.path
1172 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "projects", "compiler-rt")
1173 if not os.path.exists(compilerRtPath):
1174 self = args[0]
1175 self.skipTest("skip if compiler-rt not found")
1176 else:
1177 func(*args, **kwargs)
1178 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001179
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001180class _PlatformContext(object):
1181 """Value object class which contains platform-specific options."""
1182
1183 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1184 self.shlib_environment_var = shlib_environment_var
1185 self.shlib_prefix = shlib_prefix
1186 self.shlib_extension = shlib_extension
1187
1188
Johnny Chena74bb0a2011-08-01 18:46:13 +00001189class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001190 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001191 Abstract base for performing lldb (see TestBase) or other generic tests (see
1192 BenchBase for one example). lldbtest.Base works with the test driver to
1193 accomplish things.
1194
Johnny Chen8334dad2010-10-22 23:15:46 +00001195 """
Enrico Granata5020f952012-10-24 21:42:49 +00001196
Enrico Granata19186272012-10-24 21:44:48 +00001197 # The concrete subclass should override this attribute.
1198 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001199
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001200 # Keep track of the old current working directory.
1201 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001202
Greg Clayton4570d3e2013-12-10 23:19:29 +00001203 @staticmethod
1204 def compute_mydir(test_file):
1205 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1206
1207 mydir = TestBase.compute_mydir(__file__)'''
1208 test_dir = os.path.dirname(test_file)
1209 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1210
Johnny Chenfb4264c2011-08-01 19:50:58 +00001211 def TraceOn(self):
1212 """Returns True if we are in trace mode (tracing detailed test execution)."""
1213 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001214
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001215 @classmethod
1216 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001217 """
1218 Python unittest framework class setup fixture.
1219 Do current directory manipulation.
1220 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001221 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001222 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001223 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001224
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001225 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001226 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001227
1228 # Change current working directory if ${LLDB_TEST} is defined.
1229 # See also dotest.py which sets up ${LLDB_TEST}.
1230 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001231 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001232 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001233 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001234 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1235
Vince Harron85d19652015-05-21 19:09:29 +00001236 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001237 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001238 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1239 try:
1240 cls.dir_lock.try_acquire()
1241 # write the class that owns the lock into the lock file
1242 cls.dir_lock.handle.write(cls.__name__)
1243 except IOError as ioerror:
1244 # nothing else should have this directory lock
1245 # wait here until we get a lock
1246 cls.dir_lock.acquire()
1247 # read the previous owner from the lock file
1248 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001249 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 +00001250 raise ioerror
1251
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001252 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001253 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001254 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Robert Flackfb2f6c62015-04-17 08:02:18 +00001255 elif getPlatform() == "linux" or getPlatform() == "freebsd":
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001256 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001257 else:
1258 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001259
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001260 @classmethod
1261 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001262 """
1263 Python unittest framework class teardown fixture.
1264 Do class-wide cleanup.
1265 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001266
Johnny Chen0fddfb22011-11-17 19:57:27 +00001267 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001268 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001269 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001270 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001271
Johnny Chen707b3c92010-10-11 22:25:46 +00001272 # Subclass might have specific cleanup function defined.
1273 if getattr(cls, "classCleanup", None):
1274 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001275 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001276 try:
1277 cls.classCleanup()
1278 except:
1279 exc_type, exc_value, exc_tb = sys.exc_info()
1280 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001281
Vince Harron85d19652015-05-21 19:09:29 +00001282 if debug_confirm_directory_exclusivity:
1283 cls.dir_lock.release()
1284 del cls.dir_lock
1285
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001286 # Restore old working directory.
1287 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001288 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001289 os.chdir(cls.oldcwd)
1290
Johnny Chena74bb0a2011-08-01 18:46:13 +00001291 @classmethod
1292 def skipLongRunningTest(cls):
1293 """
1294 By default, we skip long running test case.
1295 This can be overridden by passing '-l' to the test driver (dotest.py).
1296 """
1297 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1298 return False
1299 else:
1300 return True
Johnny Chened492022011-06-21 00:53:00 +00001301
Vince Harron6d3d0f12015-05-10 22:01:59 +00001302 def enableLogChannelsForCurrentTest(self):
1303 if len(lldbtest_config.channels) == 0:
1304 return
1305
1306 # if debug channels are specified in lldbtest_config.channels,
1307 # create a new set of log files for every test
1308 log_basename = self.getLogBasenameForCurrentTest()
1309
1310 # confirm that the file is writeable
1311 host_log_path = "{}-host.log".format(log_basename)
1312 open(host_log_path, 'w').close()
1313
1314 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1315 for channel_with_categories in lldbtest_config.channels:
1316 channel_then_categories = channel_with_categories.split(' ', 1)
1317 channel = channel_then_categories[0]
1318 if len(channel_then_categories) > 1:
1319 categories = channel_then_categories[1]
1320 else:
1321 categories = "default"
1322
1323 if channel == "gdb-remote":
1324 # communicate gdb-remote categories to debugserver
1325 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1326
1327 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1328 if not self.res.Succeeded():
1329 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1330
1331 # Communicate log path name to debugserver & lldb-server
1332 server_log_path = "{}-server.log".format(log_basename)
1333 open(server_log_path, 'w').close()
1334 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1335
1336 # Communicate channels to lldb-server
1337 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1338
1339 if len(lldbtest_config.channels) == 0:
1340 return
1341
1342 def disableLogChannelsForCurrentTest(self):
1343 # close all log files that we opened
1344 for channel_and_categories in lldbtest_config.channels:
1345 # channel format - <channel-name> [<category0> [<category1> ...]]
1346 channel = channel_and_categories.split(' ', 1)[0]
1347 self.ci.HandleCommand("log disable " + channel, self.res)
1348 if not self.res.Succeeded():
1349 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1350
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001351 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001352 """Fixture for unittest test case setup.
1353
1354 It works with the test driver to conditionally skip tests and does other
1355 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001356 #import traceback
1357 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001358
Daniel Malea9115f072013-08-06 15:02:32 +00001359 if "LIBCXX_PATH" in os.environ:
1360 self.libcxxPath = os.environ["LIBCXX_PATH"]
1361 else:
1362 self.libcxxPath = None
1363
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001364 if "LLDBMI_EXEC" in os.environ:
1365 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1366 else:
1367 self.lldbMiExec = None
1368 self.dont_do_lldbmi_test = True
Vince Harron790d95c2015-05-18 19:39:03 +00001369
Johnny Chenebe51722011-10-07 19:21:09 +00001370 # If we spawn an lldb process for test (via pexpect), do not load the
1371 # init file unless told otherwise.
1372 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1373 self.lldbOption = ""
1374 else:
1375 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001376
Johnny Chen985e7402011-08-01 21:13:26 +00001377 # Assign the test method name to self.testMethodName.
1378 #
1379 # For an example of the use of this attribute, look at test/types dir.
1380 # There are a bunch of test cases under test/types and we don't want the
1381 # module cacheing subsystem to be confused with executable name "a.out"
1382 # used for all the test cases.
1383 self.testMethodName = self._testMethodName
1384
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001385 # lldb-mi only test is decorated with @lldbmi_test,
1386 # which also sets the "__lldbmi_test__" attribute of the
1387 # function object to True.
1388 try:
1389 if lldb.just_do_lldbmi_test:
1390 testMethod = getattr(self, self._testMethodName)
1391 if getattr(testMethod, "__lldbmi_test__", False):
1392 pass
1393 else:
1394 self.skipTest("non lldb-mi test")
1395 except AttributeError:
1396 pass
1397
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001398 # Benchmarks test is decorated with @benchmarks_test,
1399 # which also sets the "__benchmarks_test__" attribute of the
1400 # function object to True.
1401 try:
1402 if lldb.just_do_benchmarks_test:
1403 testMethod = getattr(self, self._testMethodName)
1404 if getattr(testMethod, "__benchmarks_test__", False):
1405 pass
1406 else:
1407 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +00001408 except AttributeError:
1409 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001410
Johnny Chen985e7402011-08-01 21:13:26 +00001411 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1412 # with it using pexpect.
1413 self.child = None
1414 self.child_prompt = "(lldb) "
1415 # If the child is interacting with the embedded script interpreter,
1416 # there are two exits required during tear down, first to quit the
1417 # embedded script interpreter and second to quit the lldb command
1418 # interpreter.
1419 self.child_in_script_interpreter = False
1420
Johnny Chenfb4264c2011-08-01 19:50:58 +00001421 # These are for customized teardown cleanup.
1422 self.dict = None
1423 self.doTearDownCleanup = False
1424 # And in rare cases where there are multiple teardown cleanups.
1425 self.dicts = []
1426 self.doTearDownCleanups = False
1427
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001428 # List of spawned subproces.Popen objects
1429 self.subprocesses = []
1430
Daniel Malea69207462013-06-05 21:07:02 +00001431 # List of forked process PIDs
1432 self.forkedProcessPids = []
1433
Johnny Chenfb4264c2011-08-01 19:50:58 +00001434 # Create a string buffer to record the session info, to be dumped into a
1435 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001436 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001437
Vince Harron1f160372015-05-21 18:51:20 +00001438 session_file = "{}.log".format(self.log_basename)
Vince Harron35b17dc2015-05-21 18:20:21 +00001439 unbuffered = 0 # 0 is the constant for unbuffered
Vince Harron1f160372015-05-21 18:51:20 +00001440 self.session = open(session_file, "w", unbuffered)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001441
1442 # Optimistically set __errored__, __failed__, __expected__ to False
1443 # initially. If the test errored/failed, the session info
1444 # (self.session) is then dumped into a session specific file for
1445 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001446 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001447 self.__errored__ = False
1448 self.__failed__ = False
1449 self.__expected__ = False
1450 # We are also interested in unexpected success.
1451 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001452 # And skipped tests.
1453 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001454
1455 # See addTearDownHook(self, hook) which allows the client to add a hook
1456 # function to be run during tearDown() time.
1457 self.hooks = []
1458
1459 # See HideStdout(self).
1460 self.sys_stdout_hidden = False
1461
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001462 if self.platformContext:
1463 # set environment variable names for finding shared libraries
1464 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001465
Vince Harron6d3d0f12015-05-10 22:01:59 +00001466 # Create the debugger instance if necessary.
1467 try:
1468 self.dbg = lldb.DBG
1469 except AttributeError:
1470 self.dbg = lldb.SBDebugger.Create()
1471
1472 if not self.dbg:
1473 raise Exception('Invalid debugger instance')
1474
1475 # Retrieve the associated command interpreter instance.
1476 self.ci = self.dbg.GetCommandInterpreter()
1477 if not self.ci:
1478 raise Exception('Could not get the command interpreter')
1479
1480 # And the result object.
1481 self.res = lldb.SBCommandReturnObject()
1482
1483 self.enableLogChannelsForCurrentTest()
1484
Johnny Chen2a808582011-10-19 16:48:07 +00001485 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001486 """Perform the run hooks to bring lldb debugger to the desired state.
1487
Johnny Chen2a808582011-10-19 16:48:07 +00001488 By default, expect a pexpect spawned child and child prompt to be
1489 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1490 and child prompt and use self.runCmd() to run the hooks one by one.
1491
Johnny Chena737ba52011-10-19 01:06:21 +00001492 Note that child is a process spawned by pexpect.spawn(). If not, your
1493 test case is mostly likely going to fail.
1494
1495 See also dotest.py where lldb.runHooks are processed/populated.
1496 """
1497 if not lldb.runHooks:
1498 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001499 if use_cmd_api:
1500 for hook in lldb.runhooks:
1501 self.runCmd(hook)
1502 else:
1503 if not child or not child_prompt:
1504 self.fail("Both child and child_prompt need to be defined.")
1505 for hook in lldb.runHooks:
1506 child.sendline(hook)
1507 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001508
Daniel Malea249287a2013-02-19 16:08:57 +00001509 def setAsync(self, value):
1510 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1511 old_async = self.dbg.GetAsync()
1512 self.dbg.SetAsync(value)
1513 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1514
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001515 def cleanupSubprocesses(self):
1516 # Ensure any subprocesses are cleaned up
1517 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001518 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001519 del p
1520 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001521 # Ensure any forked processes are cleaned up
1522 for pid in self.forkedProcessPids:
1523 if os.path.exists("/proc/" + str(pid)):
1524 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001525
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001526 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001527 """ Creates a subprocess.Popen object with the specified executable and arguments,
1528 saves it in self.subprocesses, and returns the object.
1529 NOTE: if using this function, ensure you also call:
1530
1531 self.addTearDownHook(self.cleanupSubprocesses)
1532
1533 otherwise the test suite will leak processes.
1534 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001535 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001536 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001537 self.subprocesses.append(proc)
1538 return proc
1539
Daniel Malea69207462013-06-05 21:07:02 +00001540 def forkSubprocess(self, executable, args=[]):
1541 """ Fork a subprocess with its own group ID.
1542 NOTE: if using this function, ensure you also call:
1543
1544 self.addTearDownHook(self.cleanupSubprocesses)
1545
1546 otherwise the test suite will leak processes.
1547 """
1548 child_pid = os.fork()
1549 if child_pid == 0:
1550 # If more I/O support is required, this can be beefed up.
1551 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001552 os.dup2(fd, 1)
1553 os.dup2(fd, 2)
1554 # This call causes the child to have its of group ID
1555 os.setpgid(0,0)
1556 os.execvp(executable, [executable] + args)
1557 # Give the child time to get through the execvp() call
1558 time.sleep(0.1)
1559 self.forkedProcessPids.append(child_pid)
1560 return child_pid
1561
Johnny Chenfb4264c2011-08-01 19:50:58 +00001562 def HideStdout(self):
1563 """Hide output to stdout from the user.
1564
1565 During test execution, there might be cases where we don't want to show the
1566 standard output to the user. For example,
1567
Zachary Turner35d017f2015-10-23 17:04:29 +00001568 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001569
1570 tests whether command abbreviation for 'script' works or not. There is no
1571 need to show the 'Hello' output to the user as long as the 'script' command
1572 succeeds and we are not in TraceOn() mode (see the '-t' option).
1573
1574 In this case, the test method calls self.HideStdout(self) to redirect the
1575 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1576
1577 Note that you should only call this method at most once during a test case
1578 execution. Any subsequent call has no effect at all."""
1579 if self.sys_stdout_hidden:
1580 return
1581
1582 self.sys_stdout_hidden = True
1583 old_stdout = sys.stdout
1584 sys.stdout = open(os.devnull, 'w')
1585 def restore_stdout():
1586 sys.stdout = old_stdout
1587 self.addTearDownHook(restore_stdout)
1588
1589 # =======================================================================
1590 # Methods for customized teardown cleanups as well as execution of hooks.
1591 # =======================================================================
1592
1593 def setTearDownCleanup(self, dictionary=None):
1594 """Register a cleanup action at tearDown() time with a dictinary"""
1595 self.dict = dictionary
1596 self.doTearDownCleanup = True
1597
1598 def addTearDownCleanup(self, dictionary):
1599 """Add a cleanup action at tearDown() time with a dictinary"""
1600 self.dicts.append(dictionary)
1601 self.doTearDownCleanups = True
1602
1603 def addTearDownHook(self, hook):
1604 """
1605 Add a function to be run during tearDown() time.
1606
1607 Hooks are executed in a first come first serve manner.
1608 """
1609 if callable(hook):
1610 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001611 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001612 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001613
1614 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001615
Jim Inghamda3a3862014-10-16 23:02:14 +00001616 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001617 # This is for the case of directly spawning 'lldb' and interacting with it
1618 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001619 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001620 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001621 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001622 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001623 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001624 if self.child_in_script_interpreter:
1625 self.child.sendline('quit()')
1626 self.child.expect_exact(self.child_prompt)
1627 self.child.sendline('settings set interpreter.prompt-on-quit false')
1628 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001629 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001630 except (ValueError, pexpect.ExceptionPexpect):
1631 # child is already terminated
1632 pass
1633 except OSError as exception:
1634 import errno
1635 if exception.errno != errno.EIO:
1636 # unexpected error
1637 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001638 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001639 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001640 finally:
1641 # Give it one final blow to make sure the child is terminated.
1642 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001643
1644 def tearDown(self):
1645 """Fixture for unittest test case teardown."""
1646 #import traceback
1647 #traceback.print_stack()
1648
1649 self.deletePexpectChild()
1650
Johnny Chenfb4264c2011-08-01 19:50:58 +00001651 # Check and run any hook functions.
1652 for hook in reversed(self.hooks):
1653 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001654 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001655 import inspect
1656 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001657 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001658 hook()
1659 elif hook_argc == 1:
1660 hook(self)
1661 else:
1662 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001663
1664 del self.hooks
1665
1666 # Perform registered teardown cleanup.
1667 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001668 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001669
1670 # In rare cases where there are multiple teardown cleanups added.
1671 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001672 if self.dicts:
1673 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001674 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001675
Vince Harron9753dd92015-05-10 15:22:09 +00001676 self.disableLogChannelsForCurrentTest()
1677
Johnny Chenfb4264c2011-08-01 19:50:58 +00001678 # =========================================================
1679 # Various callbacks to allow introspection of test progress
1680 # =========================================================
1681
1682 def markError(self):
1683 """Callback invoked when an error (unexpected exception) errored."""
1684 self.__errored__ = True
1685 with recording(self, False) as sbuf:
1686 # False because there's no need to write "ERROR" to the stderr twice.
1687 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001688 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001689
Zachary Turnerb1490b62015-08-26 19:44:56 +00001690 def markCleanupError(self):
1691 """Callback invoked when an error occurs while a test is cleaning up."""
1692 self.__cleanup_errored__ = True
1693 with recording(self, False) as sbuf:
1694 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1695 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001696 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001697
Johnny Chenfb4264c2011-08-01 19:50:58 +00001698 def markFailure(self):
1699 """Callback invoked when a failure (test assertion failure) occurred."""
1700 self.__failed__ = True
1701 with recording(self, False) as sbuf:
1702 # False because there's no need to write "FAIL" to the stderr twice.
1703 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001704 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001705
Enrico Granatae6cedc12013-02-23 01:05:23 +00001706 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001707 """Callback invoked when an expected failure/error occurred."""
1708 self.__expected__ = True
1709 with recording(self, False) as sbuf:
1710 # False because there's no need to write "expected failure" to the
1711 # stderr twice.
1712 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001713 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001714 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001715 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001716 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001717
Johnny Chenc5cc6252011-08-15 23:09:08 +00001718 def markSkippedTest(self):
1719 """Callback invoked when a test is skipped."""
1720 self.__skipped__ = True
1721 with recording(self, False) as sbuf:
1722 # False because there's no need to write "skipped test" to the
1723 # stderr twice.
1724 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001725 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001726
Enrico Granatae6cedc12013-02-23 01:05:23 +00001727 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001728 """Callback invoked when an unexpected success occurred."""
1729 self.__unexpected__ = True
1730 with recording(self, False) as sbuf:
1731 # False because there's no need to write "unexpected success" to the
1732 # stderr twice.
1733 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001734 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001735 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001736 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001737 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001738
Greg Clayton70995582015-01-07 22:25:50 +00001739 def getRerunArgs(self):
1740 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001741
1742 def getLogBasenameForCurrentTest(self, prefix=None):
1743 """
1744 returns a partial path that can be used as the beginning of the name of multiple
1745 log files pertaining to this test
1746
1747 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1748 """
1749 dname = os.path.join(os.environ["LLDB_TEST"],
1750 os.environ["LLDB_SESSION_DIRNAME"])
1751 if not os.path.isdir(dname):
1752 os.mkdir(dname)
1753
1754 compiler = self.getCompiler()
1755
1756 if compiler[1] == ':':
1757 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001758 if os.path.altsep is not None:
1759 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001760
Vince Harron19e300f2015-05-12 00:50:54 +00001761 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001762 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001763 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001764
1765 if prefix is not None:
1766 fname = "{}-{}".format(prefix, fname)
1767
1768 return os.path.join(dname, fname)
1769
Johnny Chenfb4264c2011-08-01 19:50:58 +00001770 def dumpSessionInfo(self):
1771 """
1772 Dump the debugger interactions leading to a test error/failure. This
1773 allows for more convenient postmortem analysis.
1774
1775 See also LLDBTestResult (dotest.py) which is a singlton class derived
1776 from TextTestResult and overwrites addError, addFailure, and
1777 addExpectedFailure methods to allow us to to mark the test instance as
1778 such.
1779 """
1780
1781 # We are here because self.tearDown() detected that this test instance
1782 # either errored or failed. The lldb.test_result singleton contains
1783 # two lists (erros and failures) which get populated by the unittest
1784 # framework. Look over there for stack trace information.
1785 #
1786 # The lists contain 2-tuples of TestCase instances and strings holding
1787 # formatted tracebacks.
1788 #
1789 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001790
Vince Harron35b17dc2015-05-21 18:20:21 +00001791 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001792 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001793 if self.__errored__:
1794 pairs = lldb.test_result.errors
1795 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001796 elif self.__cleanup_errored__:
Zachary Turnerb1490b62015-08-26 19:44:56 +00001797 pairs = lldb.test_result.cleanup_errors
1798 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001799 elif self.__failed__:
1800 pairs = lldb.test_result.failures
1801 prefix = 'Failure'
1802 elif self.__expected__:
1803 pairs = lldb.test_result.expectedFailures
1804 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001805 elif self.__skipped__:
1806 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001807 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001808 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001809 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001810 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001811
Johnny Chenc5cc6252011-08-15 23:09:08 +00001812 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001813 for test, traceback in pairs:
1814 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001815 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001816
Vince Harron35b17dc2015-05-21 18:20:21 +00001817 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001818 testMethod = getattr(self, self._testMethodName)
1819 if getattr(testMethod, "__benchmarks_test__", False):
1820 benchmarks = True
1821 else:
1822 benchmarks = False
1823
Vince Harron35b17dc2015-05-21 18:20:21 +00001824 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001825 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1826 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1827 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001828 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001829 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001830 self.session.close()
1831 del self.session
1832
1833 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001834 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001835
1836 if prefix != 'Success' or lldbtest_config.log_success:
1837 # keep all log files, rename them to include prefix
1838 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1839 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001840 if os.path.isfile(src):
1841 dst = src.replace(self.log_basename, dst_log_basename)
1842 if os.name == "nt" and os.path.isfile(dst):
1843 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1844 # it silently replaces the destination. Ultimately this means that atomic renames are not
1845 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1846 # destination first if it already exists.
1847 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001848
Zachary Turner306278f2015-05-26 20:26:29 +00001849 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001850 else:
1851 # success! (and we don't want log files) delete log files
1852 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001853 try:
1854 os.unlink(log_file)
1855 except:
1856 # We've seen consistent unlink failures on Windows, perhaps because the
1857 # just-created log file is being scanned by anti-virus. Empirically, this
1858 # sleep-and-retry approach allows tests to succeed much more reliably.
1859 # Attempts to figure out exactly what process was still holding a file handle
1860 # have failed because running instrumentation like Process Monitor seems to
1861 # slow things down enough that the problem becomes much less consistent.
1862 time.sleep(0.5)
1863 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001864
1865 # ====================================================
1866 # Config. methods supported through a plugin interface
1867 # (enables reading of the current test configuration)
1868 # ====================================================
1869
1870 def getArchitecture(self):
1871 """Returns the architecture in effect the test suite is running with."""
1872 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001873 arch = module.getArchitecture()
1874 if arch == 'amd64':
1875 arch = 'x86_64'
1876 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001877
Vince Harron02613762015-05-04 00:17:53 +00001878 def getLldbArchitecture(self):
1879 """Returns the architecture of the lldb binary."""
1880 if not hasattr(self, 'lldbArchitecture'):
1881
1882 # spawn local process
1883 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001884 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001885 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001886 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001887 "-o",
1888 "quit"
1889 ]
1890
1891 output = check_output(command)
1892 str = output.decode("utf-8");
1893
1894 for line in str.splitlines():
1895 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1896 if m:
1897 self.lldbArchitecture = m.group(1)
1898 break
1899
1900 return self.lldbArchitecture
1901
Johnny Chenfb4264c2011-08-01 19:50:58 +00001902 def getCompiler(self):
1903 """Returns the compiler in effect the test suite is running with."""
1904 module = builder_module()
1905 return module.getCompiler()
1906
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001907 def getCompilerBinary(self):
1908 """Returns the compiler binary the test suite is running with."""
1909 return self.getCompiler().split()[0]
1910
Daniel Malea0aea0162013-02-27 17:29:46 +00001911 def getCompilerVersion(self):
1912 """ Returns a string that represents the compiler version.
1913 Supports: llvm, clang.
1914 """
1915 from lldbutil import which
1916 version = 'unknown'
1917
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001918 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001919 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001920 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001921 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001922 if m:
1923 version = m.group(1)
1924 return version
1925
Ryan Brown57bee1e2015-09-14 22:45:11 +00001926 def getGoCompilerVersion(self):
1927 """ Returns a string that represents the go compiler version, or None if go is not found.
1928 """
1929 compiler = which("go")
1930 if compiler:
1931 version_output = system([[compiler, "version"]])[0]
1932 for line in version_output.split(os.linesep):
1933 m = re.search('go version (devel|go\\S+)', line)
1934 if m:
1935 return m.group(1)
1936 return None
1937
Greg Claytone0d0a762015-04-02 18:24:03 +00001938 def platformIsDarwin(self):
1939 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00001940 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00001941
Robert Flack13c7ad92015-03-30 14:12:17 +00001942 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00001943 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001944 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00001945
Daniel Maleaadaaec92013-08-06 20:51:41 +00001946 def isIntelCompiler(self):
1947 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1948 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1949
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001950 def expectedCompilerVersion(self, compiler_version):
1951 """Returns True iff compiler_version[1] matches the current compiler version.
1952 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1953 Any operator other than the following defaults to an equality test:
1954 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1955 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001956 if (compiler_version == None):
1957 return True
1958 operator = str(compiler_version[0])
1959 version = compiler_version[1]
1960
1961 if (version == None):
1962 return True
1963 if (operator == '>'):
1964 return self.getCompilerVersion() > version
1965 if (operator == '>=' or operator == '=>'):
1966 return self.getCompilerVersion() >= version
1967 if (operator == '<'):
1968 return self.getCompilerVersion() < version
1969 if (operator == '<=' or operator == '=<'):
1970 return self.getCompilerVersion() <= version
1971 if (operator == '!=' or operator == '!' or operator == 'not'):
1972 return str(version) not in str(self.getCompilerVersion())
1973 return str(version) in str(self.getCompilerVersion())
1974
1975 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001976 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001977 if (compilers == None):
1978 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001979
1980 for compiler in compilers:
1981 if compiler in self.getCompiler():
1982 return True
1983
1984 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001985
Ying Chen7091c2c2015-04-21 01:15:47 +00001986 def expectedArch(self, archs):
1987 """Returns True iff any element of archs is a sub-string of the current architecture."""
1988 if (archs == None):
1989 return True
1990
1991 for arch in archs:
1992 if arch in self.getArchitecture():
1993 return True
1994
1995 return False
1996
Johnny Chenfb4264c2011-08-01 19:50:58 +00001997 def getRunOptions(self):
1998 """Command line option for -A and -C to run this test again, called from
1999 self.dumpSessionInfo()."""
2000 arch = self.getArchitecture()
2001 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00002002 if arch:
2003 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00002004 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00002005 option_str = ""
2006 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00002007 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00002008 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00002009
2010 # ==================================================
2011 # Build methods supported through a plugin interface
2012 # ==================================================
2013
Ed Mastec97323e2014-04-01 18:47:58 +00002014 def getstdlibFlag(self):
2015 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00002016 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00002017 stdlibflag = "-stdlib=libc++"
2018 else:
2019 stdlibflag = ""
2020 return stdlibflag
2021
Matt Kopec7663b3a2013-09-25 17:44:00 +00002022 def getstdFlag(self):
2023 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002024 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002025 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002026 else:
2027 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002028 return stdflag
2029
2030 def buildDriver(self, sources, exe_name):
2031 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2032 or LLDB.framework).
2033 """
2034
2035 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002036 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002037
2038 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002039 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002040 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002041 d = {'CXX_SOURCES' : sources,
2042 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002043 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002044 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2045 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002046 }
Ed Maste372c24d2013-07-25 21:02:34 +00002047 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 +00002048 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002049 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002050 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002051 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002052 elif sys.platform.startswith('win'):
2053 d = {'CXX_SOURCES' : sources,
2054 'EXE' : exe_name,
2055 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002056 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002057 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002058 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002059
2060 self.buildDefault(dictionary=d)
2061
Matt Kopec7663b3a2013-09-25 17:44:00 +00002062 def buildLibrary(self, sources, lib_name):
2063 """Platform specific way to build a default library. """
2064
2065 stdflag = self.getstdFlag()
2066
Greg Clayton22fd3b12015-10-26 17:52:16 +00002067 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002068 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002069 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002070 d = {'DYLIB_CXX_SOURCES' : sources,
2071 'DYLIB_NAME' : lib_name,
2072 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002073 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2074 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002075 }
Robert Flack4629c4b2015-05-15 18:54:32 +00002076 elif self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux' or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002077 d = {'DYLIB_CXX_SOURCES' : sources,
2078 'DYLIB_NAME' : lib_name,
2079 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002080 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002081 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002082 d = {'DYLIB_CXX_SOURCES' : sources,
2083 'DYLIB_NAME' : lib_name,
2084 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002085 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002086 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002087 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002088
2089 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002090
Daniel Malea55faa402013-05-02 21:44:31 +00002091 def buildProgram(self, sources, exe_name):
2092 """ Platform specific way to build an executable from C/C++ sources. """
2093 d = {'CXX_SOURCES' : sources,
2094 'EXE' : exe_name}
2095 self.buildDefault(dictionary=d)
2096
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002097 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002098 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002099 if lldb.skip_build_and_cleanup:
2100 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002101 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002102 if target_is_android():
2103 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002104 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002105 raise Exception("Don't know how to build default binary")
2106
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002107 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002108 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002109 if lldb.skip_build_and_cleanup:
2110 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002111 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002112 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002113 raise Exception("Don't know how to build binary with dsym")
2114
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002115 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002116 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002117 if lldb.skip_build_and_cleanup:
2118 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002119 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002120 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002121 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002122 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002123 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002124
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002125 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2126 """Platform specific way to build binaries with dwarf maps."""
2127 if lldb.skip_build_and_cleanup:
2128 return
2129 module = builder_module()
2130 if target_is_android():
2131 dictionary = append_android_envs(dictionary)
2132 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2133 raise Exception("Don't know how to build binary with dwo")
2134
Ryan Brown57bee1e2015-09-14 22:45:11 +00002135 def buildGo(self):
2136 """Build the default go binary.
2137 """
2138 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2139
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002140 def signBinary(self, binary_path):
2141 if sys.platform.startswith("darwin"):
2142 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2143 call(codesign_cmd, shell=True)
2144
Kuba Breckabeed8212014-09-04 01:03:18 +00002145 def findBuiltClang(self):
2146 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2147 paths_to_try = [
2148 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2149 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2150 "llvm-build/Release/x86_64/Release/bin/clang",
2151 "llvm-build/Debug/x86_64/Debug/bin/clang",
2152 ]
2153 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
2154 for p in paths_to_try:
2155 path = os.path.join(lldb_root_path, p)
2156 if os.path.exists(path):
2157 return path
Ilia Kd9953052015-03-12 07:19:41 +00002158
2159 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002160 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002161 if os.path.exists(path):
2162 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002163
2164 return os.environ["CC"]
2165
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002166 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002167 """ Returns a dictionary (which can be provided to build* functions above) which
2168 contains OS-specific build flags.
2169 """
2170 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002171 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002172
2173 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002174 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002175 use_libcxx = True
2176
2177 if use_libcxx and self.libcxxPath:
2178 cflags += "-stdlib=libc++ "
2179 if self.libcxxPath:
2180 libcxxInclude = os.path.join(self.libcxxPath, "include")
2181 libcxxLib = os.path.join(self.libcxxPath, "lib")
2182 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2183 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2184
Andrew Kaylor93132f52013-05-28 23:04:25 +00002185 if use_cpp11:
2186 cflags += "-std="
2187 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2188 cflags += "c++0x"
2189 else:
2190 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002191 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002192 cflags += " -stdlib=libc++"
2193 elif "clang" in self.getCompiler():
2194 cflags += " -stdlib=libstdc++"
2195
Andrew Kaylor93132f52013-05-28 23:04:25 +00002196 return {'CFLAGS_EXTRAS' : cflags,
2197 'LD_EXTRAS' : ldflags,
2198 }
2199
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002200 def cleanup(self, dictionary=None):
2201 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002202 if lldb.skip_build_and_cleanup:
2203 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002204 module = builder_module()
2205 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002206 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002207
Daniel Malea55faa402013-05-02 21:44:31 +00002208 def getLLDBLibraryEnvVal(self):
2209 """ Returns the path that the OS-specific library search environment variable
2210 (self.dylibPath) should be set to in order for a program to find the LLDB
2211 library. If an environment variable named self.dylibPath is already set,
2212 the new path is appended to it and returned.
2213 """
2214 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002215 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002216 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002217 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002218 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002219 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002220 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002221 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002222
Ed Maste437f8f62013-09-09 14:04:04 +00002223 def getLibcPlusPlusLibs(self):
Robert Flackfa5ad652015-05-13 20:17:34 +00002224 if self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux':
Ed Maste437f8f62013-09-09 14:04:04 +00002225 return ['libc++.so.1']
2226 else:
2227 return ['libc++.1.dylib','libc++abi.dylib']
2228
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002229# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2230# We change the test methods to create a new test method for each test for each debug info we are
2231# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2232# the new test method we remove the old method at the same time.
2233class LLDBTestCaseFactory(type):
2234 def __new__(cls, name, bases, attrs):
2235 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002236 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002237 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2238 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002239 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002240 def dsym_test_method(self, attrvalue=attrvalue):
2241 self.debug_info = "dsym"
2242 return attrvalue(self)
2243 dsym_method_name = attrname + "_dsym"
2244 dsym_test_method.__name__ = dsym_method_name
2245 newattrs[dsym_method_name] = dsym_test_method
2246
2247 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002248 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002249 def dwarf_test_method(self, attrvalue=attrvalue):
2250 self.debug_info = "dwarf"
2251 return attrvalue(self)
2252 dwarf_method_name = attrname + "_dwarf"
2253 dwarf_test_method.__name__ = dwarf_method_name
2254 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002255
2256 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002257 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002258 def dwo_test_method(self, attrvalue=attrvalue):
2259 self.debug_info = "dwo"
2260 return attrvalue(self)
2261 dwo_method_name = attrname + "_dwo"
2262 dwo_test_method.__name__ = dwo_method_name
2263 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002264 else:
2265 newattrs[attrname] = attrvalue
2266 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2267
Zachary Turner43a01e42015-10-20 21:06:05 +00002268# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2269@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002270class TestBase(Base):
2271 """
2272 This abstract base class is meant to be subclassed. It provides default
2273 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2274 among other things.
2275
2276 Important things for test class writers:
2277
2278 - Overwrite the mydir class attribute, otherwise your test class won't
2279 run. It specifies the relative directory to the top level 'test' so
2280 the test harness can change to the correct working directory before
2281 running your test.
2282
2283 - The setUp method sets up things to facilitate subsequent interactions
2284 with the debugger as part of the test. These include:
2285 - populate the test method name
2286 - create/get a debugger set with synchronous mode (self.dbg)
2287 - get the command interpreter from with the debugger (self.ci)
2288 - create a result object for use with the command interpreter
2289 (self.res)
2290 - plus other stuffs
2291
2292 - The tearDown method tries to perform some necessary cleanup on behalf
2293 of the test to return the debugger to a good state for the next test.
2294 These include:
2295 - execute any tearDown hooks registered by the test method with
2296 TestBase.addTearDownHook(); examples can be found in
2297 settings/TestSettings.py
2298 - kill the inferior process associated with each target, if any,
2299 and, then delete the target from the debugger's target list
2300 - perform build cleanup before running the next test method in the
2301 same test class; examples of registering for this service can be
2302 found in types/TestIntegerTypes.py with the call:
2303 - self.setTearDownCleanup(dictionary=d)
2304
2305 - Similarly setUpClass and tearDownClass perform classwise setup and
2306 teardown fixtures. The tearDownClass method invokes a default build
2307 cleanup for the entire test class; also, subclasses can implement the
2308 classmethod classCleanup(cls) to perform special class cleanup action.
2309
2310 - The instance methods runCmd and expect are used heavily by existing
2311 test cases to send a command to the command interpreter and to perform
2312 string/pattern matching on the output of such command execution. The
2313 expect method also provides a mode to peform string/pattern matching
2314 without running a command.
2315
2316 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2317 build the binaries used during a particular test scenario. A plugin
2318 should be provided for the sys.platform running the test suite. The
2319 Mac OS X implementation is located in plugins/darwin.py.
2320 """
2321
2322 # Maximum allowed attempts when launching the inferior process.
2323 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2324 maxLaunchCount = 3;
2325
2326 # Time to wait before the next launching attempt in second(s).
2327 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2328 timeWaitNextLaunch = 1.0;
2329
2330 def doDelay(self):
2331 """See option -w of dotest.py."""
2332 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
2333 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
2334 waitTime = 1.0
2335 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
2336 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
2337 time.sleep(waitTime)
2338
Enrico Granata165f8af2012-09-21 19:10:53 +00002339 # Returns the list of categories to which this test case belongs
2340 # by default, look for a ".categories" file, and read its contents
2341 # if no such file exists, traverse the hierarchy - we guarantee
2342 # a .categories to exist at the top level directory so we do not end up
2343 # looping endlessly - subclasses are free to define their own categories
2344 # in whatever way makes sense to them
2345 def getCategories(self):
2346 import inspect
2347 import os.path
2348 folder = inspect.getfile(self.__class__)
2349 folder = os.path.dirname(folder)
2350 while folder != '/':
2351 categories_file_name = os.path.join(folder,".categories")
2352 if os.path.exists(categories_file_name):
2353 categories_file = open(categories_file_name,'r')
2354 categories = categories_file.readline()
2355 categories_file.close()
2356 categories = str.replace(categories,'\n','')
2357 categories = str.replace(categories,'\r','')
2358 return categories.split(',')
2359 else:
2360 folder = os.path.dirname(folder)
2361 continue
2362
Johnny Chena74bb0a2011-08-01 18:46:13 +00002363 def setUp(self):
2364 #import traceback
2365 #traceback.print_stack()
2366
2367 # Works with the test driver to conditionally skip tests via decorators.
2368 Base.setUp(self)
2369
Johnny Chena74bb0a2011-08-01 18:46:13 +00002370 try:
2371 if lldb.blacklist:
2372 className = self.__class__.__name__
2373 classAndMethodName = "%s.%s" % (className, self._testMethodName)
2374 if className in lldb.blacklist:
2375 self.skipTest(lldb.blacklist.get(className))
2376 elif classAndMethodName in lldb.blacklist:
2377 self.skipTest(lldb.blacklist.get(classAndMethodName))
2378 except AttributeError:
2379 pass
2380
Johnny Chened492022011-06-21 00:53:00 +00002381 # Insert some delay between successive test cases if specified.
2382 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00002383
Johnny Chenf2b70232010-08-25 18:49:48 +00002384 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2385 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2386
Johnny Chen430eb762010-10-19 16:00:42 +00002387 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002388 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002389
Daniel Maleae0f8f572013-08-26 23:57:52 +00002390 #
2391 # Warning: MAJOR HACK AHEAD!
2392 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
2393 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
2394 # command, instead. See also runCmd() where it decorates the "file filename" call
2395 # with additional functionality when running testsuite remotely.
2396 #
2397 if lldb.lldbtest_remote_sandbox:
2398 def DecoratedCreateTarget(arg):
2399 self.runCmd("file %s" % arg)
2400 target = self.dbg.GetSelectedTarget()
2401 #
Greg Claytonc6947512013-12-13 19:18:59 +00002402 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00002403 # johnny @ 04/23/2012
2404 #
2405 def DecoratedLaunchSimple(argv, envp, wd):
2406 self.runCmd("run")
2407 return target.GetProcess()
2408 target.LaunchSimple = DecoratedLaunchSimple
2409
2410 return target
2411 self.dbg.CreateTarget = DecoratedCreateTarget
2412 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002413 print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
Daniel Maleae0f8f572013-08-26 23:57:52 +00002414
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002415 # We want our debugger to be synchronous.
2416 self.dbg.SetAsync(False)
2417
2418 # Retrieve the associated command interpreter instance.
2419 self.ci = self.dbg.GetCommandInterpreter()
2420 if not self.ci:
2421 raise Exception('Could not get the command interpreter')
2422
2423 # And the result object.
2424 self.res = lldb.SBCommandReturnObject()
2425
Johnny Chen44d24972012-04-16 18:55:15 +00002426 # Run global pre-flight code, if defined via the config file.
2427 if lldb.pre_flight:
2428 lldb.pre_flight(self)
2429
Enrico Granatabd0998a2015-10-02 22:53:32 +00002430 if lldb.remote_platform and lldb.remote_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002431 remote_test_dir = lldbutil.join_remote_paths(
2432 lldb.remote_platform_working_dir,
2433 self.getArchitecture(),
2434 str(self.test_number),
2435 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002436 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002437 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002438 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002439
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002440 # This function removes all files from the current working directory while leaving
2441 # the directories in place. The cleaup is required to reduce the disk space required
2442 # by the test suit while leaving the directories untached is neccessary because
2443 # sub-directories might belong to an other test
2444 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002445 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002446 # TODO: Replace the heuristic to remove the files with a logic what collects the
2447 # list of files we have to remove during test runs.
2448 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002449 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002450 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002451 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002452 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002453
Greg Clayton35c91342014-11-17 18:40:27 +00002454 def registerSharedLibrariesWithTarget(self, target, shlibs):
2455 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2456
2457 Any modules in the target that have their remote install file specification set will
2458 get uploaded to the remote host. This function registers the local copies of the
2459 shared libraries with the target and sets their remote install locations so they will
2460 be uploaded when the target is run.
2461 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002462 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002463 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002464
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002465 shlib_environment_var = self.platformContext.shlib_environment_var
2466 shlib_prefix = self.platformContext.shlib_prefix
2467 shlib_extension = '.' + self.platformContext.shlib_extension
2468
2469 working_dir = self.get_process_working_directory()
2470 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2471 # Add any shared libraries to our target if remote so they get
2472 # uploaded into the working directory on the remote side
2473 for name in shlibs:
2474 # The path can be a full path to a shared library, or a make file name like "Foo" for
2475 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2476 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2477 # of the shared library accordingly
2478 if os.path.exists(name):
2479 local_shlib_path = name # name is the full path to the local shared library
2480 else:
2481 # Check relative names
2482 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2483 if not os.path.exists(local_shlib_path):
2484 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002485 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002486 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002487
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002488 # Make sure we found the local shared library in the above code
2489 self.assertTrue(os.path.exists(local_shlib_path))
2490
2491 # Add the shared library to our target
2492 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2493 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002494 # We must set the remote install location if we want the shared library
2495 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002496 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002497 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002498
2499 return environment
2500
Enrico Granata44818162012-10-24 01:23:57 +00002501 # utility methods that tests can use to access the current objects
2502 def target(self):
2503 if not self.dbg:
2504 raise Exception('Invalid debugger instance')
2505 return self.dbg.GetSelectedTarget()
2506
2507 def process(self):
2508 if not self.dbg:
2509 raise Exception('Invalid debugger instance')
2510 return self.dbg.GetSelectedTarget().GetProcess()
2511
2512 def thread(self):
2513 if not self.dbg:
2514 raise Exception('Invalid debugger instance')
2515 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2516
2517 def frame(self):
2518 if not self.dbg:
2519 raise Exception('Invalid debugger instance')
2520 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2521
Greg Claytonc6947512013-12-13 19:18:59 +00002522 def get_process_working_directory(self):
2523 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2524 if lldb.remote_platform:
2525 # Remote tests set the platform working directory up in TestBase.setUp()
2526 return lldb.remote_platform.GetWorkingDirectory()
2527 else:
2528 # local tests change directory into each test subdirectory
2529 return os.getcwd()
2530
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002531 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002532 #import traceback
2533 #traceback.print_stack()
2534
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002535 # Ensure all the references to SB objects have gone away so that we can
2536 # be sure that all test-specific resources have been freed before we
2537 # attempt to delete the targets.
2538 gc.collect()
2539
Johnny Chen3794ad92011-06-15 21:24:24 +00002540 # Delete the target(s) from the debugger as a general cleanup step.
2541 # This includes terminating the process for each target, if any.
2542 # We'd like to reuse the debugger for our next test without incurring
2543 # the initialization overhead.
2544 targets = []
2545 for target in self.dbg:
2546 if target:
2547 targets.append(target)
2548 process = target.GetProcess()
2549 if process:
2550 rc = self.invoke(process, "Kill")
2551 self.assertTrue(rc.Success(), PROCESS_KILLED)
2552 for target in targets:
2553 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002554
Johnny Chen44d24972012-04-16 18:55:15 +00002555 # Run global post-flight code, if defined via the config file.
2556 if lldb.post_flight:
2557 lldb.post_flight(self)
2558
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002559 # Do this last, to make sure it's in reverse order from how we setup.
2560 Base.tearDown(self)
2561
Zachary Turner95812042015-03-26 18:54:21 +00002562 # This must be the last statement, otherwise teardown hooks or other
2563 # lines might depend on this still being active.
2564 del self.dbg
2565
Johnny Chen86268e42011-09-30 21:48:35 +00002566 def switch_to_thread_with_stop_reason(self, stop_reason):
2567 """
2568 Run the 'thread list' command, and select the thread with stop reason as
2569 'stop_reason'. If no such thread exists, no select action is done.
2570 """
2571 from lldbutil import stop_reason_to_str
2572 self.runCmd('thread list')
2573 output = self.res.GetOutput()
2574 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2575 stop_reason_to_str(stop_reason))
2576 for line in output.splitlines():
2577 matched = thread_line_pattern.match(line)
2578 if matched:
2579 self.runCmd('thread select %s' % matched.group(1))
2580
Enrico Granata7594f142013-06-17 22:51:50 +00002581 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002582 """
2583 Ask the command interpreter to handle the command and then check its
2584 return status.
2585 """
2586 # Fail fast if 'cmd' is not meaningful.
2587 if not cmd or len(cmd) == 0:
2588 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002589
Johnny Chen8d55a342010-08-31 17:42:54 +00002590 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002591
Daniel Maleae0f8f572013-08-26 23:57:52 +00002592 # This is an opportunity to insert the 'platform target-install' command if we are told so
2593 # via the settig of lldb.lldbtest_remote_sandbox.
2594 if cmd.startswith("target create "):
2595 cmd = cmd.replace("target create ", "file ")
2596 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
2597 with recording(self, trace) as sbuf:
2598 the_rest = cmd.split("file ")[1]
2599 # Split the rest of the command line.
2600 atoms = the_rest.split()
2601 #
2602 # NOTE: This assumes that the options, if any, follow the file command,
2603 # instead of follow the specified target.
2604 #
2605 target = atoms[-1]
2606 # Now let's get the absolute pathname of our target.
2607 abs_target = os.path.abspath(target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002608 print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002609 fpath, fname = os.path.split(abs_target)
2610 parent_dir = os.path.split(fpath)[0]
2611 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
Zachary Turnerff890da2015-10-19 23:45:41 +00002612 print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002613 self.ci.HandleCommand(platform_target_install_command, self.res)
2614 # And this is the file command we want to execute, instead.
2615 #
2616 # Warning: SIDE EFFECT AHEAD!!!
2617 # Populate the remote executable pathname into the lldb namespace,
2618 # so that test cases can grab this thing out of the namespace.
2619 #
2620 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
2621 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002622 print("And this is the replaced file command: %s" % cmd, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002623
Johnny Chen63dfb272010-09-01 00:15:19 +00002624 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002625
Johnny Chen63dfb272010-09-01 00:15:19 +00002626 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002627 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002628
Johnny Chen150c3cc2010-10-15 01:18:29 +00002629 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002630 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002631 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002632 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002633 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002634 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002635 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002636 print("runCmd failed!", file=sbuf)
2637 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002638
Johnny Chenff3d01d2010-08-20 21:03:09 +00002639 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002640 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002641 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002642 # For process launch, wait some time before possible next try.
2643 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002644 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002645 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002646
Johnny Chen27f212d2010-08-19 23:26:59 +00002647 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002648 self.assertTrue(self.res.Succeeded(),
2649 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002650
Jim Ingham63dfc722012-09-22 00:05:11 +00002651 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2652 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2653
2654 Otherwise, all the arguments have the same meanings as for the expect function"""
2655
2656 trace = (True if traceAlways else trace)
2657
2658 if exe:
2659 # First run the command. If we are expecting error, set check=False.
2660 # Pass the assert message along since it provides more semantic info.
2661 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2662
2663 # Then compare the output against expected strings.
2664 output = self.res.GetError() if error else self.res.GetOutput()
2665
2666 # If error is True, the API client expects the command to fail!
2667 if error:
2668 self.assertFalse(self.res.Succeeded(),
2669 "Command '" + str + "' is expected to fail!")
2670 else:
2671 # No execution required, just compare str against the golden input.
2672 output = str
2673 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002674 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002675
2676 # The heading says either "Expecting" or "Not expecting".
2677 heading = "Expecting" if matching else "Not expecting"
2678
2679 for pattern in patterns:
2680 # Match Objects always have a boolean value of True.
2681 match_object = re.search(pattern, output)
2682 matched = bool(match_object)
2683 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002684 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2685 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002686 if matched:
2687 break
2688
2689 self.assertTrue(matched if matching else not matched,
2690 msg if msg else EXP_MSG(str, exe))
2691
2692 return match_object
2693
Enrico Granata7594f142013-06-17 22:51:50 +00002694 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 +00002695 """
2696 Similar to runCmd; with additional expect style output matching ability.
2697
2698 Ask the command interpreter to handle the command and then check its
2699 return status. The 'msg' parameter specifies an informational assert
2700 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002701 'startstr', matches the substrings contained in 'substrs', and regexp
2702 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002703
2704 If the keyword argument error is set to True, it signifies that the API
2705 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002706 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002707 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002708
2709 If the keyword argument matching is set to False, it signifies that the API
2710 client is expecting the output of the command not to match the golden
2711 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002712
2713 Finally, the required argument 'str' represents the lldb command to be
2714 sent to the command interpreter. In case the keyword argument 'exe' is
2715 set to False, the 'str' is treated as a string to be matched/not-matched
2716 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002717 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002718 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002719
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002720 if exe:
2721 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002722 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002723 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002724
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002725 # Then compare the output against expected strings.
2726 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002727
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002728 # If error is True, the API client expects the command to fail!
2729 if error:
2730 self.assertFalse(self.res.Succeeded(),
2731 "Command '" + str + "' is expected to fail!")
2732 else:
2733 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002734 if isinstance(str,lldb.SBCommandReturnObject):
2735 output = str.GetOutput()
2736 else:
2737 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002738 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002739 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002740
Johnny Chenea88e942010-09-21 21:08:53 +00002741 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002742 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002743
2744 # Start from the startstr, if specified.
2745 # If there's no startstr, set the initial state appropriately.
2746 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002747
Johnny Chen150c3cc2010-10-15 01:18:29 +00002748 if startstr:
2749 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002750 print("%s start string: %s" % (heading, startstr), file=sbuf)
2751 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002752
Johnny Chen86268e42011-09-30 21:48:35 +00002753 # Look for endstr, if specified.
2754 keepgoing = matched if matching else not matched
2755 if endstr:
2756 matched = output.endswith(endstr)
2757 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002758 print("%s end string: %s" % (heading, endstr), file=sbuf)
2759 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002760
Johnny Chenea88e942010-09-21 21:08:53 +00002761 # Look for sub strings, if specified.
2762 keepgoing = matched if matching else not matched
2763 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002764 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002765 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002766 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002767 print("%s sub string: %s" % (heading, str), file=sbuf)
2768 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002769 keepgoing = matched if matching else not matched
2770 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002771 break
2772
Johnny Chenea88e942010-09-21 21:08:53 +00002773 # Search for regular expression patterns, if specified.
2774 keepgoing = matched if matching else not matched
2775 if patterns and keepgoing:
2776 for pattern in patterns:
2777 # Match Objects always have a boolean value of True.
2778 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002779 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002780 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2781 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002782 keepgoing = matched if matching else not matched
2783 if not keepgoing:
2784 break
Johnny Chenea88e942010-09-21 21:08:53 +00002785
2786 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002787 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002788
Johnny Chenf3c59232010-08-25 22:52:45 +00002789 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002790 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002791 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002792
2793 method = getattr(obj, name)
2794 import inspect
2795 self.assertTrue(inspect.ismethod(method),
2796 name + "is a method name of object: " + str(obj))
2797 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002798 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002799 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002800 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002801
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002802 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2803 """Platform specific way to build the default binaries."""
2804 if lldb.skip_build_and_cleanup:
2805 return
2806 module = builder_module()
2807 if target_is_android():
2808 dictionary = append_android_envs(dictionary)
2809 if self.debug_info is None:
2810 return self.buildDefault(architecture, compiler, dictionary, clean)
2811 elif self.debug_info == "dsym":
2812 return self.buildDsym(architecture, compiler, dictionary, clean)
2813 elif self.debug_info == "dwarf":
2814 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002815 elif self.debug_info == "dwo":
2816 return self.buildDwo(architecture, compiler, dictionary, clean)
2817 else:
2818 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002819
Johnny Chenf359cf22011-05-27 23:36:52 +00002820 # =================================================
2821 # Misc. helper methods for debugging test execution
2822 # =================================================
2823
Johnny Chen56b92a72011-07-11 19:15:11 +00002824 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002825 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00002826 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002827
Johnny Chen8d55a342010-08-31 17:42:54 +00002828 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002829 return
2830
2831 err = sys.stderr
2832 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002833 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2834 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2835 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2836 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2837 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2838 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2839 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2840 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2841 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002842
Johnny Chen36c5eb12011-08-05 20:17:27 +00002843 def DebugSBType(self, type):
2844 """Debug print a SBType object, if traceAlways is True."""
2845 if not traceAlways:
2846 return
2847
2848 err = sys.stderr
2849 err.write(type.GetName() + ":\n")
2850 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2851 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2852 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2853
Johnny Chenb877f1e2011-03-12 01:18:19 +00002854 def DebugPExpect(self, child):
2855 """Debug the spwaned pexpect object."""
2856 if not traceAlways:
2857 return
2858
Zachary Turnerff890da2015-10-19 23:45:41 +00002859 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002860
2861 @classmethod
2862 def RemoveTempFile(cls, file):
2863 if os.path.exists(file):
2864 os.remove(file)