blob: 95e676f5e41db0b3e9f37bbdf81a4e7e62d3cc71 [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
Zachary Turnercd236b82015-10-26 18:48:24 +000057import six
58import collections
Siva Chandra8af91662015-06-05 00:22:49 +000059
Vince Harron85d19652015-05-21 19:09:29 +000060# dosep.py starts lots and lots of dotest instances
61# This option helps you find if two (or more) dotest instances are using the same
62# directory at the same time
63# Enable it to cause test failures and stderr messages if dotest instances try to run in
64# the same directory simultaneously
65# it is disabled by default because it litters the test directories with ".dirlock" files
66debug_confirm_directory_exclusivity = False
67
Johnny Chen707b3c92010-10-11 22:25:46 +000068# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000069# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000070
71# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000072if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
73 traceAlways = True
74else:
75 traceAlways = False
76
Johnny Chen707b3c92010-10-11 22:25:46 +000077# By default, doCleanup is True.
78if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
79 doCleanup = False
80else:
81 doCleanup = True
82
Johnny Chen8d55a342010-08-31 17:42:54 +000083
Johnny Chen00778092010-08-09 22:01:17 +000084#
85# Some commonly used assert messages.
86#
87
Johnny Chenaa902922010-09-17 22:45:27 +000088COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
89
Johnny Chen00778092010-08-09 22:01:17 +000090CURRENT_EXECUTABLE_SET = "Current executable set successfully"
91
Johnny Chen7d1d7532010-09-02 21:23:12 +000092PROCESS_IS_VALID = "Process is valid"
93
94PROCESS_KILLED = "Process is killed successfully"
95
Johnny Chend5f66fc2010-12-23 01:12:19 +000096PROCESS_EXITED = "Process exited successfully"
97
98PROCESS_STOPPED = "Process status should be stopped"
99
Sean Callanan05834cd2015-07-01 23:56:30 +0000100RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000101
Johnny Chen17941842010-08-09 23:44:24 +0000102RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000103
Johnny Chen67af43f2010-10-05 19:27:32 +0000104BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
105
Johnny Chen17941842010-08-09 23:44:24 +0000106BREAKPOINT_CREATED = "Breakpoint created successfully"
107
Johnny Chenf10af382010-12-04 00:07:24 +0000108BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
109
Johnny Chene76896c2010-08-17 21:33:31 +0000110BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
111
Johnny Chen17941842010-08-09 23:44:24 +0000112BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000113
Johnny Chen703dbd02010-09-30 17:06:24 +0000114BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
115
Johnny Chen164f1e12010-10-15 18:07:09 +0000116BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
117
Greg Clayton5db6b792012-10-24 18:24:14 +0000118MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
119
Johnny Chen89109ed12011-06-27 20:05:23 +0000120OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
121
Johnny Chen5b3a3572010-12-09 18:22:12 +0000122SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
123
Johnny Chenc70b02a2010-09-22 23:00:20 +0000124STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
125
Johnny Chen1691a162011-04-15 16:44:48 +0000126STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
127
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000128STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
129
Johnny Chen5d6c4642010-11-10 23:46:38 +0000130STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000131
Johnny Chen5d6c4642010-11-10 23:46:38 +0000132STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
133 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000134
Johnny Chen2e431ce2010-10-20 18:38:48 +0000135STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
136
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000137STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
138
Johnny Chenc066ab42010-10-14 01:22:03 +0000139STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
140
Johnny Chen00778092010-08-09 22:01:17 +0000141STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
142
Johnny Chenf68cc122011-09-15 21:09:59 +0000143STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
144
Johnny Chen3c884a02010-08-24 22:07:56 +0000145DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
146
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000147VALID_BREAKPOINT = "Got a valid breakpoint"
148
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000149VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
150
Johnny Chen7209d84f2011-05-06 23:26:12 +0000151VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
152
Johnny Chen5ee88192010-08-27 23:47:36 +0000153VALID_FILESPEC = "Got a valid filespec"
154
Johnny Chen025d1b82010-12-08 01:25:21 +0000155VALID_MODULE = "Got a valid module"
156
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000157VALID_PROCESS = "Got a valid process"
158
Johnny Chen025d1b82010-12-08 01:25:21 +0000159VALID_SYMBOL = "Got a valid symbol"
160
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000161VALID_TARGET = "Got a valid target"
162
Matthew Gardinerc928de32014-10-22 07:22:56 +0000163VALID_PLATFORM = "Got a valid platform"
164
Johnny Chen15f247a2012-02-03 20:43:00 +0000165VALID_TYPE = "Got a valid type"
166
Johnny Chen5819ab42011-07-15 22:28:10 +0000167VALID_VARIABLE = "Got a valid variable"
168
Johnny Chen981463d2010-08-25 19:00:04 +0000169VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000170
Johnny Chenf68cc122011-09-15 21:09:59 +0000171WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000172
Sean Callanan05834cd2015-07-01 23:56:30 +0000173def CMD_MSG(str):
174 '''A generic "Command '%s' returns successfully" message generator.'''
175 return "Command '%s' returns successfully" % str
Johnny Chenc0c67f22010-11-09 18:42:22 +0000176
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000177def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000178 '''A generic message generator for the completion mechanism.'''
179 return "'%s' successfully completes to '%s'" % (str_before, str_after)
180
Johnny Chenc0c67f22010-11-09 18:42:22 +0000181def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000182 '''A generic "'%s' returns expected result" message generator if exe.
183 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000184 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000185
Johnny Chen3343f042010-10-19 19:11:38 +0000186def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000187 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000188 return "Value of setting '%s' is correct" % setting
189
Johnny Chen27c41232010-08-26 21:49:29 +0000190def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000191 """Returns an env variable array from the os.environ map object."""
Zachary Turner606e1e32015-10-23 17:53:51 +0000192 return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
Johnny Chen27c41232010-08-26 21:49:29 +0000193
Johnny Chen47ceb032010-10-11 23:52:19 +0000194def line_number(filename, string_to_match):
195 """Helper function to return the line number of the first matched string."""
196 with open(filename, 'r') as f:
197 for i, line in enumerate(f):
198 if line.find(string_to_match) != -1:
199 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000200 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000201 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000202
Johnny Chen67af43f2010-10-05 19:27:32 +0000203def pointer_size():
204 """Return the pointer size of the host system."""
205 import ctypes
206 a_pointer = ctypes.c_void_p(0xffff)
207 return 8 * ctypes.sizeof(a_pointer)
208
Johnny Chen57816732012-02-09 02:01:59 +0000209def is_exe(fpath):
210 """Returns true if fpath is an executable."""
211 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
212
213def which(program):
214 """Returns the full path to a program; None otherwise."""
215 fpath, fname = os.path.split(program)
216 if fpath:
217 if is_exe(program):
218 return program
219 else:
220 for path in os.environ["PATH"].split(os.pathsep):
221 exe_file = os.path.join(path, program)
222 if is_exe(exe_file):
223 return exe_file
224 return None
225
Zachary Turner814236d2015-10-21 17:48:52 +0000226class recording(SixStringIO):
Johnny Chen150c3cc2010-10-15 01:18:29 +0000227 """
228 A nice little context manager for recording the debugger interactions into
229 our session object. If trace flag is ON, it also emits the interactions
230 into the stderr.
231 """
232 def __init__(self, test, trace):
Zachary Turner814236d2015-10-21 17:48:52 +0000233 """Create a SixStringIO instance; record the session obj and trace flag."""
234 SixStringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000235 # The test might not have undergone the 'setUp(self)' phase yet, so that
236 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000237 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000238 self.trace = trace
239
240 def __enter__(self):
241 """
242 Context management protocol on entry to the body of the with statement.
Zachary Turner814236d2015-10-21 17:48:52 +0000243 Just return the SixStringIO object.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000244 """
245 return self
246
247 def __exit__(self, type, value, tb):
248 """
249 Context management protocol on exit from the body of the with statement.
250 If trace is ON, it emits the recordings into stderr. Always add the
Zachary Turner814236d2015-10-21 17:48:52 +0000251 recordings to our session object. And close the SixStringIO object, too.
Johnny Chen150c3cc2010-10-15 01:18:29 +0000252 """
253 if self.trace:
Zachary Turnerff890da2015-10-19 23:45:41 +0000254 print(self.getvalue(), file=sys.stderr)
Johnny Chen690fcef2010-10-15 23:55:05 +0000255 if self.session:
Zachary Turnerff890da2015-10-19 23:45:41 +0000256 print(self.getvalue(), file=self.session)
Johnny Chen150c3cc2010-10-15 01:18:29 +0000257 self.close()
258
Zachary Turner43a01e42015-10-20 21:06:05 +0000259@add_metaclass(abc.ABCMeta)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000260class _BaseProcess(object):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000261
262 @abc.abstractproperty
263 def pid(self):
264 """Returns process PID if has been launched already."""
265
266 @abc.abstractmethod
267 def launch(self, executable, args):
268 """Launches new process with given executable and args."""
269
270 @abc.abstractmethod
271 def terminate(self):
272 """Terminates previously launched process.."""
273
274class _LocalProcess(_BaseProcess):
275
276 def __init__(self, trace_on):
277 self._proc = None
278 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000279 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000280
281 @property
282 def pid(self):
283 return self._proc.pid
284
285 def launch(self, executable, args):
286 self._proc = Popen([executable] + args,
287 stdout = open(os.devnull) if not self._trace_on else None,
288 stdin = PIPE)
289
290 def terminate(self):
291 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000292 # Terminate _proc like it does the pexpect
Adrian McCarthy137d7ba2015-07-07 14:47:34 +0000293 signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)]
294 for sig in signals_to_try:
295 try:
296 self._proc.send_signal(getattr(signal, sig))
297 time.sleep(self._delayafterterminate)
298 if self._proc.poll() != None:
299 return
300 except ValueError:
301 pass # Windows says SIGINT is not a valid signal to send
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000302 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000303 time.sleep(self._delayafterterminate)
304 if self._proc.poll() != None:
305 return
306 self._proc.kill()
307 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000308
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000309 def poll(self):
310 return self._proc.poll()
311
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000312class _RemoteProcess(_BaseProcess):
313
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000314 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000315 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000316 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000317
318 @property
319 def pid(self):
320 return self._pid
321
322 def launch(self, executable, args):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000323 if self._install_remote:
324 src_path = executable
Chaoren Lin5d76b1b2015-06-06 00:25:50 +0000325 dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable))
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000326
327 dst_file_spec = lldb.SBFileSpec(dst_path, False)
328 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
329 if err.Fail():
330 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
331 else:
332 dst_path = executable
333 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000334
335 launch_info = lldb.SBLaunchInfo(args)
336 launch_info.SetExecutableFile(dst_file_spec, True)
Chaoren Lin3e2bdb42015-05-11 17:53:39 +0000337 launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000338
339 # Redirect stdout and stderr to /dev/null
340 launch_info.AddSuppressFileAction(1, False, True)
341 launch_info.AddSuppressFileAction(2, False, True)
342
343 err = lldb.remote_platform.Launch(launch_info)
344 if err.Fail():
345 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
346 self._pid = launch_info.GetProcessID()
347
348 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000349 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000350
Johnny Chen690fcef2010-10-15 23:55:05 +0000351# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000352# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000353def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000354 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000355
356 If the exit code was non-zero it raises a CalledProcessError. The
357 CalledProcessError object will have the return code in the returncode
358 attribute and output in the output attribute.
359
360 The arguments are the same as for the Popen constructor. Example:
361
362 >>> check_output(["ls", "-l", "/dev/null"])
363 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
364
365 The stdout argument is not allowed as it is used internally.
366 To capture standard error in the result, use stderr=STDOUT.
367
368 >>> check_output(["/bin/sh", "-c",
369 ... "ls -l non_existent_file ; exit 0"],
370 ... stderr=STDOUT)
371 'ls: non_existent_file: No such file or directory\n'
372 """
373
374 # Assign the sender object to variable 'test' and remove it from kwargs.
375 test = kwargs.pop('sender', None)
376
Zachary Turner9ef307b2014-07-22 16:19:29 +0000377 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
378 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000379 output = ""
380 error = ""
381 for shellCommand in commandList:
382 if 'stdout' in kwargs:
383 raise ValueError('stdout argument not allowed, it will be overridden.')
384 if 'shell' in kwargs and kwargs['shell']==False:
385 raise ValueError('shell=False not allowed')
386 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
387 pid = process.pid
388 this_output, this_error = process.communicate()
389 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000390
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000391 # Enable trace on failure return while tracking down FreeBSD buildbot issues
392 trace = traceAlways
393 if not trace and retcode and sys.platform.startswith("freebsd"):
394 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000395
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000396 with recording(test, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +0000397 print(file=sbuf)
398 print("os command:", shellCommand, file=sbuf)
399 print("with pid:", pid, file=sbuf)
400 print("stdout:", this_output, file=sbuf)
401 print("stderr:", this_error, file=sbuf)
402 print("retcode:", retcode, file=sbuf)
403 print(file=sbuf)
Ed Maste6e496332014-08-05 20:33:17 +0000404
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000405 if retcode:
406 cmd = kwargs.get("args")
407 if cmd is None:
408 cmd = shellCommand
409 raise CalledProcessError(retcode, cmd)
410 output = output + this_output
411 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000412 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000413
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000414def getsource_if_available(obj):
415 """
416 Return the text of the source code for an object if available. Otherwise,
417 a print representation is returned.
418 """
419 import inspect
420 try:
421 return inspect.getsource(obj)
422 except:
423 return repr(obj)
424
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000425def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000426 if sys.platform.startswith("freebsd"):
427 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000428 return __import__("builder_" + sys.platform)
429
Siva Chandra8af91662015-06-05 00:22:49 +0000430def run_adb_command(cmd, device_id):
431 device_id_args = []
432 if device_id:
433 device_id_args = ["-s", device_id]
434 full_cmd = ["adb"] + device_id_args + cmd
435 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
436 stdout, stderr = p.communicate()
437 return p.returncode, stdout, stderr
438
Chaoren Line9bbabc2015-07-18 00:37:55 +0000439def append_android_envs(dictionary):
440 if dictionary is None:
441 dictionary = {}
442 dictionary["OS"] = "Android"
443 if android_device_api() >= 16:
444 dictionary["PIE"] = 1
445 return dictionary
446
Chaoren Lin9070f532015-07-17 22:13:29 +0000447def target_is_android():
448 if not hasattr(target_is_android, 'result'):
449 triple = lldb.DBG.GetSelectedPlatform().GetTriple()
450 match = re.match(".*-.*-.*-android", triple)
451 target_is_android.result = match is not None
452 return target_is_android.result
453
Siva Chandra8af91662015-06-05 00:22:49 +0000454def android_device_api():
Chaoren Lin9070f532015-07-17 22:13:29 +0000455 if not hasattr(android_device_api, 'result'):
456 assert lldb.platform_url is not None
457 device_id = None
458 parsed_url = urlparse.urlparse(lldb.platform_url)
459 if parsed_url.scheme == "adb":
460 device_id = parsed_url.netloc.split(":")[0]
461 retcode, stdout, stderr = run_adb_command(
462 ["shell", "getprop", "ro.build.version.sdk"], device_id)
463 if retcode == 0:
464 android_device_api.result = int(stdout)
465 else:
466 raise LookupError(
467 ">>> Unable to determine the API level of the Android device.\n"
468 ">>> stdout:\n%s\n"
469 ">>> stderr:\n%s\n" % (stdout, stderr))
470 return android_device_api.result
Siva Chandra8af91662015-06-05 00:22:49 +0000471
Johnny Chena74bb0a2011-08-01 18:46:13 +0000472#
473# Decorators for categorizing test cases.
474#
Johnny Chena74bb0a2011-08-01 18:46:13 +0000475from functools import wraps
Pavel Labathdc8b2d32015-10-26 09:28:32 +0000476def add_test_categories(cat):
477 """Decorate an item with test categories"""
478 cat = test_categories.validate(cat, True)
479 def impl(func):
480 func.getCategories = lambda test: cat
481 return func
482 return impl
Johnny Chena74bb0a2011-08-01 18:46:13 +0000483
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000484def lldbmi_test(func):
485 """Decorate the item as a lldb-mi only test."""
486 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
487 raise Exception("@lldbmi_test can only be used to decorate a test method")
488 @wraps(func)
489 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000490 if lldb.dont_do_lldbmi_test:
491 self.skipTest("lldb-mi tests")
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000492 return func(self, *args, **kwargs)
493
494 # Mark this function as such to separate them from lldb command line tests.
495 wrapper.__lldbmi_test__ = True
496 return wrapper
497
Johnny Chena74bb0a2011-08-01 18:46:13 +0000498def benchmarks_test(func):
499 """Decorate the item as a benchmarks test."""
500 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
501 raise Exception("@benchmarks_test can only be used to decorate a test method")
502 @wraps(func)
503 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000504 if not lldb.just_do_benchmarks_test:
505 self.skipTest("benchmarks tests")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000506 return func(self, *args, **kwargs)
507
508 # Mark this function as such to separate them from the regular tests.
509 wrapper.__benchmarks_test__ = True
510 return wrapper
511
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000512def no_debug_info_test(func):
513 """Decorate the item as a test what don't use any debug info. If this annotation is specified
514 then the test runner won't generate a separate test for each debug info format. """
515 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
516 raise Exception("@no_debug_info_test can only be used to decorate a test method")
517 @wraps(func)
518 def wrapper(self, *args, **kwargs):
519 return func(self, *args, **kwargs)
520
521 # Mark this function as such to separate them from the regular tests.
522 wrapper.__no_debug_info_test__ = True
523 return wrapper
524
Johnny Chenf1548d42012-04-06 00:56:05 +0000525def dsym_test(func):
526 """Decorate the item as a dsym test."""
527 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
528 raise Exception("@dsym_test can only be used to decorate a test method")
529 @wraps(func)
530 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000531 if lldb.dont_do_dsym_test:
532 self.skipTest("dsym tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000533 return func(self, *args, **kwargs)
534
535 # Mark this function as such to separate them from the regular tests.
536 wrapper.__dsym_test__ = True
537 return wrapper
538
539def dwarf_test(func):
540 """Decorate the item as a dwarf test."""
541 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
542 raise Exception("@dwarf_test can only be used to decorate a test method")
543 @wraps(func)
544 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000545 if lldb.dont_do_dwarf_test:
546 self.skipTest("dwarf tests")
Johnny Chenf1548d42012-04-06 00:56:05 +0000547 return func(self, *args, **kwargs)
548
549 # Mark this function as such to separate them from the regular tests.
550 wrapper.__dwarf_test__ = True
551 return wrapper
552
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000553def dwo_test(func):
554 """Decorate the item as a dwo test."""
555 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
556 raise Exception("@dwo_test can only be used to decorate a test method")
557 @wraps(func)
558 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000559 if lldb.dont_do_dwo_test:
560 self.skipTest("dwo tests")
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000561 return func(self, *args, **kwargs)
562
563 # Mark this function as such to separate them from the regular tests.
564 wrapper.__dwo_test__ = True
565 return wrapper
566
Todd Fialaa41d48c2014-04-28 04:49:40 +0000567def debugserver_test(func):
568 """Decorate the item as a debugserver test."""
569 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
570 raise Exception("@debugserver_test can only be used to decorate a test method")
571 @wraps(func)
572 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000573 if lldb.dont_do_debugserver_test:
574 self.skipTest("debugserver tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000575 return func(self, *args, **kwargs)
576
577 # Mark this function as such to separate them from the regular tests.
578 wrapper.__debugserver_test__ = True
579 return wrapper
580
581def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000582 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000583 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
584 raise Exception("@llgs_test can only be used to decorate a test method")
585 @wraps(func)
586 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000587 if lldb.dont_do_llgs_test:
588 self.skipTest("llgs tests")
Todd Fialaa41d48c2014-04-28 04:49:40 +0000589 return func(self, *args, **kwargs)
590
591 # Mark this function as such to separate them from the regular tests.
592 wrapper.__llgs_test__ = True
593 return wrapper
594
Daniel Maleae0f8f572013-08-26 23:57:52 +0000595def not_remote_testsuite_ready(func):
596 """Decorate the item as a test which is not ready yet for remote testsuite."""
597 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
598 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
599 @wraps(func)
600 def wrapper(self, *args, **kwargs):
Pavel Labathf882f6f2015-10-12 13:42:16 +0000601 if lldb.lldbtest_remote_sandbox or lldb.remote_platform:
602 self.skipTest("not ready for remote testsuite")
Daniel Maleae0f8f572013-08-26 23:57:52 +0000603 return func(self, *args, **kwargs)
604
605 # Mark this function as such to separate them from the regular tests.
606 wrapper.__not_ready_for_remote_testsuite_test__ = True
607 return wrapper
608
Ed Maste433790a2014-04-23 12:55:41 +0000609def expectedFailure(expected_fn, bugnumber=None):
610 def expectedFailure_impl(func):
611 @wraps(func)
612 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000613 from unittest2 import case
614 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000615 try:
Ed Maste433790a2014-04-23 12:55:41 +0000616 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000617 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000618 if expected_fn(self):
619 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000620 else:
621 raise
Ed Maste433790a2014-04-23 12:55:41 +0000622 if expected_fn(self):
623 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
624 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000625 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
626 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000627 if six.callable(bugnumber):
Ying Chen464d1e12015-03-27 00:26:52 +0000628 return expectedFailure_impl(bugnumber)
629 else:
630 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000631
Ying Chen7091c2c2015-04-21 01:15:47 +0000632# provide a function to xfail on defined oslist, compiler version, and archs
633# if none is specified for any argument, that argument won't be checked and thus means for all
634# for example,
635# @expectedFailureAll, xfail for all platform/compiler/arch,
636# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
637# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000638def expectedFailureAll(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None):
Ying Chen7091c2c2015-04-21 01:15:47 +0000639 def fn(self):
640 return ((oslist is None or self.getPlatform() in oslist) and
641 (compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))) and
Tamas Berghammercf6f92a2015-09-07 15:50:19 +0000642 self.expectedArch(archs) and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000643 (triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())) and
644 (debug_info is None or self.debug_info in debug_info))
Ying Chen7091c2c2015-04-21 01:15:47 +0000645 return expectedFailure(fn, bugnumber)
646
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000647def expectedFailureDwarf(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000648 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
649
650def expectedFailureDwo(bugnumber=None):
651 return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000652
653def expectedFailureDsym(bugnumber=None):
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +0000654 return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000655
656def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
657 if compiler_version is None:
658 compiler_version=['=', None]
659 return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
660
Vince Harron8974ce22015-03-13 19:54:54 +0000661# to XFAIL a specific clang versions, try this
662# @expectedFailureClang('bugnumber', ['<=', '3.4'])
663def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000664 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000665
666def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000667 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000668
Matt Kopec0de53f02013-03-15 19:10:12 +0000669def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000670 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000671
Ed Maste433790a2014-04-23 12:55:41 +0000672def expectedFailureArch(arch, bugnumber=None):
673 def fn(self):
674 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000675 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000676
Enrico Granatae6cedc12013-02-23 01:05:23 +0000677def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000678 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000679
Matt Kopecee969f92013-09-26 23:30:59 +0000680def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000681 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000682
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000683def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
Ed Maste433790a2014-04-23 12:55:41 +0000684 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000685 return (self.getPlatform() in oslist and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000686 self.expectedCompiler(compilers) and
687 (debug_info is None or self.debug_info in debug_info))
Ying Chen464d1e12015-03-27 00:26:52 +0000688 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000689
Chaoren Linf7160f32015-06-09 17:39:27 +0000690def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
691 def fn(self):
692 return (getHostPlatform() in oslist and
693 self.expectedCompiler(compilers))
694 return expectedFailure(fn, bugnumber)
695
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000696def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000697 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000698 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
Matt Kopecee969f92013-09-26 23:30:59 +0000699
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000700def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
701 return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000702
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000703def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
704 return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000705
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000706def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
707 return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
Zachary Turner80c2c602014-12-09 19:28:00 +0000708
Chaoren Linf7160f32015-06-09 17:39:27 +0000709def expectedFailureHostWindows(bugnumber=None, compilers=None):
710 return expectedFailureHostOS(['windows'], bugnumber, compilers)
711
Pavel Labath090152b2015-08-20 11:37:19 +0000712def matchAndroid(api_levels=None, archs=None):
713 def match(self):
714 if not target_is_android():
715 return False
716 if archs is not None and self.getArchitecture() not in archs:
717 return False
718 if api_levels is not None and android_device_api() not in api_levels:
719 return False
720 return True
721 return match
722
723
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000724def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
Siva Chandra8af91662015-06-05 00:22:49 +0000725 """ Mark a test as xfail for Android.
726
727 Arguments:
728 bugnumber - The LLVM pr associated with the problem.
729 api_levels - A sequence of numbers specifying the Android API levels
Tamas Berghammer050d1e82015-07-22 11:00:06 +0000730 for which a test is expected to fail. None means all API level.
731 arch - A sequence of architecture names specifying the architectures
732 for which a test is expected to fail. None means all architectures.
Siva Chandra8af91662015-06-05 00:22:49 +0000733 """
Pavel Labath090152b2015-08-20 11:37:19 +0000734 return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
Pavel Labath674bc7b2015-05-29 14:54:46 +0000735
Vince Harron7ac3ea42015-06-26 15:13:21 +0000736# if the test passes on the first try, we're done (success)
737# if the test fails once, then passes on the second try, raise an ExpectedFailure
738# if the test fails twice in a row, re-throw the exception from the second test run
739def expectedFlakey(expected_fn, bugnumber=None):
740 def expectedFailure_impl(func):
741 @wraps(func)
742 def wrapper(*args, **kwargs):
743 from unittest2 import case
744 self = args[0]
745 try:
746 func(*args, **kwargs)
Ying Chen0a7202b2015-07-01 22:44:27 +0000747 # don't retry if the test case is already decorated with xfail or skip
748 except (case._ExpectedFailure, case.SkipTest, case._UnexpectedSuccess):
749 raise
Vince Harron7ac3ea42015-06-26 15:13:21 +0000750 except Exception:
751 if expected_fn(self):
Ying Chen0a7202b2015-07-01 22:44:27 +0000752 # before retry, run tearDown for previous run and setup for next
Vince Harron7ac3ea42015-06-26 15:13:21 +0000753 try:
Ying Chen0a7202b2015-07-01 22:44:27 +0000754 self.tearDown()
755 self.setUp()
Vince Harron7ac3ea42015-06-26 15:13:21 +0000756 func(*args, **kwargs)
757 except Exception:
758 # oh snap! two failures in a row, record a failure/error
759 raise
760 # record the expected failure
761 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
762 else:
763 raise
764 return wrapper
765 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
766 # return decorator in this case, so it will be used to decorating original method
Zachary Turnercd236b82015-10-26 18:48:24 +0000767 if six.callable(bugnumber):
Vince Harron7ac3ea42015-06-26 15:13:21 +0000768 return expectedFailure_impl(bugnumber)
769 else:
770 return expectedFailure_impl
771
Tamas Berghammerc8fd1302015-09-30 10:12:40 +0000772def expectedFlakeyDwarf(bugnumber=None):
773 def fn(self):
774 return self.debug_info == "dwarf"
775 return expectedFlakey(fn, bugnumber)
776
777def expectedFlakeyDsym(bugnumber=None):
778 def fn(self):
779 return self.debug_info == "dwarf"
780 return expectedFlakey(fn, bugnumber)
781
Vince Harron7ac3ea42015-06-26 15:13:21 +0000782def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
783 def fn(self):
784 return (self.getPlatform() in oslist and
785 self.expectedCompiler(compilers))
786 return expectedFlakey(fn, bugnumber)
787
788def expectedFlakeyDarwin(bugnumber=None, compilers=None):
789 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
790 return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
791
792def expectedFlakeyLinux(bugnumber=None, compilers=None):
793 return expectedFlakeyOS(['linux'], bugnumber, compilers)
794
795def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
796 return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
797
798def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
799 if compiler_version is None:
800 compiler_version=['=', None]
801 def fn(self):
802 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
803 return expectedFlakey(fn, bugnumber)
804
805# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
806def expectedFlakeyClang(bugnumber=None, compiler_version=None):
807 return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
808
809# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
810def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
811 return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
812
Pavel Labath63a579c2015-09-07 12:15:27 +0000813def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
814 return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
815
Greg Clayton12514562013-12-05 22:22:32 +0000816def skipIfRemote(func):
817 """Decorate the item to skip tests if testing remotely."""
818 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
819 raise Exception("@skipIfRemote can only be used to decorate a test method")
820 @wraps(func)
821 def wrapper(*args, **kwargs):
822 from unittest2 import case
823 if lldb.remote_platform:
824 self = args[0]
825 self.skipTest("skip on remote platform")
826 else:
827 func(*args, **kwargs)
828 return wrapper
829
Siva Chandra4470f382015-06-17 22:32:27 +0000830def skipUnlessListedRemote(remote_list=None):
831 def myImpl(func):
832 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
833 raise Exception("@skipIfRemote can only be used to decorate a "
834 "test method")
835
836 @wraps(func)
837 def wrapper(*args, **kwargs):
838 if remote_list and lldb.remote_platform:
839 self = args[0]
840 triple = self.dbg.GetSelectedPlatform().GetTriple()
841 for r in remote_list:
842 if r in triple:
843 func(*args, **kwargs)
844 return
845 self.skipTest("skip on remote platform %s" % str(triple))
846 else:
847 func(*args, **kwargs)
848 return wrapper
849
850 return myImpl
851
Greg Clayton12514562013-12-05 22:22:32 +0000852def skipIfRemoteDueToDeadlock(func):
853 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
854 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
855 raise Exception("@skipIfRemote can only be used to decorate a test method")
856 @wraps(func)
857 def wrapper(*args, **kwargs):
858 from unittest2 import case
859 if lldb.remote_platform:
860 self = args[0]
861 self.skipTest("skip on remote platform (deadlocks)")
862 else:
863 func(*args, **kwargs)
864 return wrapper
865
Enrico Granatab633e432014-10-06 21:37:06 +0000866def skipIfNoSBHeaders(func):
867 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
868 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000869 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000870 @wraps(func)
871 def wrapper(*args, **kwargs):
872 from unittest2 import case
873 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000874 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +0000875 header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
Shawn Best181b09b2014-11-08 00:04:04 +0000876 else:
877 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000878 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000879 if not os.path.exists(header):
880 self.skipTest("skip because LLDB.h header not found")
881 else:
882 func(*args, **kwargs)
883 return wrapper
884
Robert Flack13c7ad92015-03-30 14:12:17 +0000885def skipIfFreeBSD(func):
886 """Decorate the item to skip tests that should be skipped on FreeBSD."""
887 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000888
Greg Claytone0d0a762015-04-02 18:24:03 +0000889def getDarwinOSTriples():
890 return ['darwin', 'macosx', 'ios']
891
Daniel Maleab3d41a22013-07-09 00:08:01 +0000892def skipIfDarwin(func):
893 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000894 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000895
Robert Flack13c7ad92015-03-30 14:12:17 +0000896def skipIfLinux(func):
897 """Decorate the item to skip tests that should be skipped on Linux."""
898 return skipIfPlatform(["linux"])(func)
899
Oleksiy Vyalovabb5a352015-07-29 22:18:16 +0000900def skipUnlessHostLinux(func):
901 """Decorate the item to skip tests that should be skipped on any non Linux host."""
902 return skipUnlessHostPlatform(["linux"])(func)
903
Robert Flack13c7ad92015-03-30 14:12:17 +0000904def skipIfWindows(func):
905 """Decorate the item to skip tests that should be skipped on Windows."""
906 return skipIfPlatform(["windows"])(func)
907
Chaoren Line6eea5d2015-06-08 22:13:28 +0000908def skipIfHostWindows(func):
909 """Decorate the item to skip tests that should be skipped on Windows."""
910 return skipIfHostPlatform(["windows"])(func)
911
Adrian McCarthyd9dbae52015-09-16 18:17:11 +0000912def skipUnlessWindows(func):
913 """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
914 return skipUnlessPlatform(["windows"])(func)
915
Robert Flack13c7ad92015-03-30 14:12:17 +0000916def skipUnlessDarwin(func):
917 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000918 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000919
Ryan Brown57bee1e2015-09-14 22:45:11 +0000920def skipUnlessGoInstalled(func):
921 """Decorate the item to skip tests when no Go compiler is available."""
922 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
923 raise Exception("@skipIfGcc can only be used to decorate a test method")
924 @wraps(func)
925 def wrapper(*args, **kwargs):
926 from unittest2 import case
927 self = args[0]
928 compiler = self.getGoCompilerVersion()
929 if not compiler:
930 self.skipTest("skipping because go compiler not found")
931 else:
Todd Fialabe5dfc52015-10-06 19:15:56 +0000932 # Ensure the version is the minimum version supported by
Todd Fiala02c08d02015-10-06 22:14:33 +0000933 # the LLDB go support.
Todd Fialabe5dfc52015-10-06 19:15:56 +0000934 match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
935 if not match_version:
936 # Couldn't determine version.
937 self.skipTest(
938 "skipping because go version could not be parsed "
939 "out of {}".format(compiler))
940 else:
941 from distutils.version import StrictVersion
Todd Fiala02c08d02015-10-06 22:14:33 +0000942 min_strict_version = StrictVersion("1.4.0")
Todd Fialabe5dfc52015-10-06 19:15:56 +0000943 compiler_strict_version = StrictVersion(match_version.group(1))
944 if compiler_strict_version < min_strict_version:
945 self.skipTest(
946 "skipping because available go version ({}) does "
Todd Fiala02c08d02015-10-06 22:14:33 +0000947 "not meet minimum required go version ({})".format(
Todd Fialabe5dfc52015-10-06 19:15:56 +0000948 compiler_strict_version,
949 min_strict_version))
Todd Fiala9f236802015-10-06 19:23:22 +0000950 func(*args, **kwargs)
Ryan Brown57bee1e2015-09-14 22:45:11 +0000951 return wrapper
952
Robert Flack068898c2015-04-09 18:07:58 +0000953def getPlatform():
Robert Flack6e1fd352015-05-15 12:39:33 +0000954 """Returns the target platform which the tests are running on."""
Robert Flack068898c2015-04-09 18:07:58 +0000955 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
956 if platform.startswith('freebsd'):
957 platform = 'freebsd'
958 return platform
959
Robert Flack6e1fd352015-05-15 12:39:33 +0000960def getHostPlatform():
961 """Returns the host platform running the test suite."""
962 # Attempts to return a platform name matching a target Triple platform.
963 if sys.platform.startswith('linux'):
964 return 'linux'
965 elif sys.platform.startswith('win32'):
966 return 'windows'
967 elif sys.platform.startswith('darwin'):
968 return 'darwin'
969 elif sys.platform.startswith('freebsd'):
970 return 'freebsd'
971 else:
972 return sys.platform
973
Robert Flackfb2f6c62015-04-17 08:02:18 +0000974def platformIsDarwin():
975 """Returns true if the OS triple for the selected platform is any valid apple OS"""
976 return getPlatform() in getDarwinOSTriples()
977
Robert Flack6e1fd352015-05-15 12:39:33 +0000978def skipIfHostIncompatibleWithRemote(func):
979 """Decorate the item to skip tests if binaries built on this host are incompatible."""
980 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
981 raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
982 @wraps(func)
983 def wrapper(*args, **kwargs):
984 from unittest2 import case
985 self = args[0]
986 host_arch = self.getLldbArchitecture()
987 host_platform = getHostPlatform()
988 target_arch = self.getArchitecture()
Robert Flack4629c4b2015-05-15 18:54:32 +0000989 target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
Robert Flack6e1fd352015-05-15 12:39:33 +0000990 if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
991 self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
992 elif target_platform != host_platform:
993 self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
994 else:
995 func(*args, **kwargs)
996 return wrapper
997
Chaoren Line6eea5d2015-06-08 22:13:28 +0000998def skipIfHostPlatform(oslist):
999 """Decorate the item to skip tests if running on one of the listed host platforms."""
1000 return unittest2.skipIf(getHostPlatform() in oslist,
1001 "skip on %s" % (", ".join(oslist)))
1002
1003def skipUnlessHostPlatform(oslist):
1004 """Decorate the item to skip tests unless running on one of the listed host platforms."""
1005 return unittest2.skipUnless(getHostPlatform() in oslist,
1006 "requires on of %s" % (", ".join(oslist)))
1007
Zachary Turner793d9972015-08-14 23:29:24 +00001008def skipUnlessArch(archlist):
1009 """Decorate the item to skip tests unless running on one of the listed architectures."""
1010 def myImpl(func):
1011 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1012 raise Exception("@skipUnlessArch can only be used to decorate a test method")
1013
1014 @wraps(func)
1015 def wrapper(*args, **kwargs):
1016 self = args[0]
1017 if self.getArchitecture() not in archlist:
1018 self.skipTest("skipping for architecture %s (requires one of %s)" %
1019 (self.getArchitecture(), ", ".join(archlist)))
1020 else:
1021 func(*args, **kwargs)
1022 return wrapper
1023
1024 return myImpl
1025
Robert Flack13c7ad92015-03-30 14:12:17 +00001026def skipIfPlatform(oslist):
1027 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001028 return unittest2.skipIf(getPlatform() in oslist,
1029 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +00001030
1031def skipUnlessPlatform(oslist):
1032 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +00001033 return unittest2.skipUnless(getPlatform() in oslist,
1034 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +00001035
Daniel Malea48359902013-05-14 20:48:54 +00001036def skipIfLinuxClang(func):
1037 """Decorate the item to skip tests that should be skipped if building on
1038 Linux with clang.
1039 """
1040 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1041 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
1042 @wraps(func)
1043 def wrapper(*args, **kwargs):
1044 from unittest2 import case
1045 self = args[0]
1046 compiler = self.getCompiler()
Vince Harronc8492672015-05-04 02:59:19 +00001047 platform = self.getPlatform()
1048 if "clang" in compiler and platform == "linux":
Daniel Malea48359902013-05-14 20:48:54 +00001049 self.skipTest("skipping because Clang is used on Linux")
1050 else:
1051 func(*args, **kwargs)
1052 return wrapper
1053
Ying Chen7091c2c2015-04-21 01:15:47 +00001054# provide a function to skip on defined oslist, compiler version, and archs
1055# if none is specified for any argument, that argument won't be checked and thus means for all
1056# for example,
1057# @skipIf, skip for all platform/compiler/arch,
1058# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
1059# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
1060
1061# TODO: refactor current code, to make skipIfxxx functions to call this function
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001062def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None):
Ying Chen7091c2c2015-04-21 01:15:47 +00001063 def fn(self):
1064 return ((oslist is None or self.getPlatform() in oslist) and
1065 (compiler is None or (compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version))) and
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001066 self.expectedArch(archs) and
1067 (debug_info is None or self.debug_info in debug_info))
1068 return skipTestIfFn(fn, bugnumber, skipReason="skipping because os:%s compiler: %s %s arch: %s debug info: %s"%(oslist, compiler, compiler_version, archs, debug_info))
1069
1070def skipIfDebugInfo(bugnumber=None, debug_info=None):
1071 return skipIf(bugnumber=bugnumber, debug_info=debug_info)
1072
Greg Claytonedea2372015-10-07 20:01:13 +00001073def skipIfDWO(bugnumber=None):
1074 return skipIfDebugInfo(bugnumber, ["dwo"])
1075
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00001076def skipIfDwarf(bugnumber=None):
1077 return skipIfDebugInfo(bugnumber, ["dwarf"])
1078
1079def skipIfDsym(bugnumber=None):
1080 return skipIfDebugInfo(bugnumber, ["dsym"])
Ying Chen7091c2c2015-04-21 01:15:47 +00001081
1082def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
1083 def skipTestIfFn_impl(func):
1084 @wraps(func)
1085 def wrapper(*args, **kwargs):
1086 from unittest2 import case
1087 self = args[0]
1088 if expected_fn(self):
1089 self.skipTest(skipReason)
1090 else:
1091 func(*args, **kwargs)
1092 return wrapper
Zachary Turnercd236b82015-10-26 18:48:24 +00001093 if six.callable(bugnumber):
Ying Chen7091c2c2015-04-21 01:15:47 +00001094 return skipTestIfFn_impl(bugnumber)
1095 else:
1096 return skipTestIfFn_impl
1097
Daniel Maleabe230792013-01-24 23:52:09 +00001098def skipIfGcc(func):
1099 """Decorate the item to skip tests that should be skipped if building with gcc ."""
1100 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +00001101 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +00001102 @wraps(func)
1103 def wrapper(*args, **kwargs):
1104 from unittest2 import case
1105 self = args[0]
1106 compiler = self.getCompiler()
1107 if "gcc" in compiler:
1108 self.skipTest("skipping because gcc is the test compiler")
1109 else:
1110 func(*args, **kwargs)
1111 return wrapper
1112
Matt Kopec0de53f02013-03-15 19:10:12 +00001113def skipIfIcc(func):
1114 """Decorate the item to skip tests that should be skipped if building with icc ."""
1115 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1116 raise Exception("@skipIfIcc can only be used to decorate a test method")
1117 @wraps(func)
1118 def wrapper(*args, **kwargs):
1119 from unittest2 import case
1120 self = args[0]
1121 compiler = self.getCompiler()
1122 if "icc" in compiler:
1123 self.skipTest("skipping because icc is the test compiler")
1124 else:
1125 func(*args, **kwargs)
1126 return wrapper
1127
Daniel Malea55faa402013-05-02 21:44:31 +00001128def skipIfi386(func):
1129 """Decorate the item to skip tests that should be skipped if building 32-bit."""
1130 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1131 raise Exception("@skipIfi386 can only be used to decorate a test method")
1132 @wraps(func)
1133 def wrapper(*args, **kwargs):
1134 from unittest2 import case
1135 self = args[0]
1136 if "i386" == self.getArchitecture():
1137 self.skipTest("skipping because i386 is not a supported architecture")
1138 else:
1139 func(*args, **kwargs)
1140 return wrapper
1141
Pavel Labath090152b2015-08-20 11:37:19 +00001142def skipIfTargetAndroid(api_levels=None, archs=None):
Siva Chandra77f20fc2015-06-05 19:54:49 +00001143 """Decorator to skip tests when the target is Android.
1144
1145 Arguments:
1146 api_levels - The API levels for which the test should be skipped. If
1147 it is None, then the test will be skipped for all API levels.
Pavel Labath090152b2015-08-20 11:37:19 +00001148 arch - A sequence of architecture names specifying the architectures
1149 for which a test is skipped. None means all architectures.
Siva Chandra77f20fc2015-06-05 19:54:49 +00001150 """
1151 def myImpl(func):
1152 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1153 raise Exception("@skipIfTargetAndroid can only be used to "
1154 "decorate a test method")
1155 @wraps(func)
1156 def wrapper(*args, **kwargs):
1157 from unittest2 import case
1158 self = args[0]
Pavel Labath090152b2015-08-20 11:37:19 +00001159 if matchAndroid(api_levels, archs)(self):
1160 self.skipTest("skiped on Android target with API %d and architecture %s" %
1161 (android_device_api(), self.getArchitecture()))
Tamas Berghammer1253a812015-03-13 10:12:25 +00001162 func(*args, **kwargs)
Siva Chandra77f20fc2015-06-05 19:54:49 +00001163 return wrapper
1164 return myImpl
Tamas Berghammer1253a812015-03-13 10:12:25 +00001165
Ilia Kd9953052015-03-12 07:19:41 +00001166def skipUnlessCompilerRt(func):
1167 """Decorate the item to skip tests if testing remotely."""
1168 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
1169 raise Exception("@skipUnless can only be used to decorate a test method")
1170 @wraps(func)
1171 def wrapper(*args, **kwargs):
1172 from unittest2 import case
1173 import os.path
1174 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "projects", "compiler-rt")
1175 if not os.path.exists(compilerRtPath):
1176 self = args[0]
1177 self.skipTest("skip if compiler-rt not found")
1178 else:
1179 func(*args, **kwargs)
1180 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +00001181
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001182class _PlatformContext(object):
1183 """Value object class which contains platform-specific options."""
1184
1185 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
1186 self.shlib_environment_var = shlib_environment_var
1187 self.shlib_prefix = shlib_prefix
1188 self.shlib_extension = shlib_extension
1189
1190
Johnny Chena74bb0a2011-08-01 18:46:13 +00001191class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +00001192 """
Johnny Chena74bb0a2011-08-01 18:46:13 +00001193 Abstract base for performing lldb (see TestBase) or other generic tests (see
1194 BenchBase for one example). lldbtest.Base works with the test driver to
1195 accomplish things.
1196
Johnny Chen8334dad2010-10-22 23:15:46 +00001197 """
Enrico Granata5020f952012-10-24 21:42:49 +00001198
Enrico Granata19186272012-10-24 21:44:48 +00001199 # The concrete subclass should override this attribute.
1200 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001201
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001202 # Keep track of the old current working directory.
1203 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001204
Greg Clayton4570d3e2013-12-10 23:19:29 +00001205 @staticmethod
1206 def compute_mydir(test_file):
1207 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
1208
1209 mydir = TestBase.compute_mydir(__file__)'''
1210 test_dir = os.path.dirname(test_file)
1211 return test_dir[len(os.environ["LLDB_TEST"])+1:]
1212
Johnny Chenfb4264c2011-08-01 19:50:58 +00001213 def TraceOn(self):
1214 """Returns True if we are in trace mode (tracing detailed test execution)."""
1215 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +00001216
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001217 @classmethod
1218 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001219 """
1220 Python unittest framework class setup fixture.
1221 Do current directory manipulation.
1222 """
Johnny Chenf02ec122010-07-03 20:41:42 +00001223 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001224 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +00001225 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +00001226
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001227 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001228 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001229
1230 # Change current working directory if ${LLDB_TEST} is defined.
1231 # See also dotest.py which sets up ${LLDB_TEST}.
1232 if ("LLDB_TEST" in os.environ):
Vince Harron85d19652015-05-21 19:09:29 +00001233 full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001234 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001235 print("Change dir to:", full_dir, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001236 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
1237
Vince Harron85d19652015-05-21 19:09:29 +00001238 if debug_confirm_directory_exclusivity:
Zachary Turnerb48b4042015-05-21 20:16:02 +00001239 import lock
Vince Harron85d19652015-05-21 19:09:29 +00001240 cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
1241 try:
1242 cls.dir_lock.try_acquire()
1243 # write the class that owns the lock into the lock file
1244 cls.dir_lock.handle.write(cls.__name__)
1245 except IOError as ioerror:
1246 # nothing else should have this directory lock
1247 # wait here until we get a lock
1248 cls.dir_lock.acquire()
1249 # read the previous owner from the lock file
1250 lock_id = cls.dir_lock.handle.read()
Zachary Turnerff890da2015-10-19 23:45:41 +00001251 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 +00001252 raise ioerror
1253
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001254 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +00001255 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001256 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Robert Flackfb2f6c62015-04-17 08:02:18 +00001257 elif getPlatform() == "linux" or getPlatform() == "freebsd":
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001258 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001259 else:
1260 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001261
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001262 @classmethod
1263 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +00001264 """
1265 Python unittest framework class teardown fixture.
1266 Do class-wide cleanup.
1267 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001268
Johnny Chen0fddfb22011-11-17 19:57:27 +00001269 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +00001270 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +00001271 module = builder_module()
Zachary Turnerb1490b62015-08-26 19:44:56 +00001272 module.cleanup()
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001273
Johnny Chen707b3c92010-10-11 22:25:46 +00001274 # Subclass might have specific cleanup function defined.
1275 if getattr(cls, "classCleanup", None):
1276 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001277 print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
Johnny Chen707b3c92010-10-11 22:25:46 +00001278 try:
1279 cls.classCleanup()
1280 except:
1281 exc_type, exc_value, exc_tb = sys.exc_info()
1282 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001283
Vince Harron85d19652015-05-21 19:09:29 +00001284 if debug_confirm_directory_exclusivity:
1285 cls.dir_lock.release()
1286 del cls.dir_lock
1287
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001288 # Restore old working directory.
1289 if traceAlways:
Zachary Turnerff890da2015-10-19 23:45:41 +00001290 print("Restore dir to:", cls.oldcwd, file=sys.stderr)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001291 os.chdir(cls.oldcwd)
1292
Johnny Chena74bb0a2011-08-01 18:46:13 +00001293 @classmethod
1294 def skipLongRunningTest(cls):
1295 """
1296 By default, we skip long running test case.
1297 This can be overridden by passing '-l' to the test driver (dotest.py).
1298 """
1299 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
1300 return False
1301 else:
1302 return True
Johnny Chened492022011-06-21 00:53:00 +00001303
Vince Harron6d3d0f12015-05-10 22:01:59 +00001304 def enableLogChannelsForCurrentTest(self):
1305 if len(lldbtest_config.channels) == 0:
1306 return
1307
1308 # if debug channels are specified in lldbtest_config.channels,
1309 # create a new set of log files for every test
1310 log_basename = self.getLogBasenameForCurrentTest()
1311
1312 # confirm that the file is writeable
1313 host_log_path = "{}-host.log".format(log_basename)
1314 open(host_log_path, 'w').close()
1315
1316 log_enable = "log enable -Tpn -f {} ".format(host_log_path)
1317 for channel_with_categories in lldbtest_config.channels:
1318 channel_then_categories = channel_with_categories.split(' ', 1)
1319 channel = channel_then_categories[0]
1320 if len(channel_then_categories) > 1:
1321 categories = channel_then_categories[1]
1322 else:
1323 categories = "default"
1324
1325 if channel == "gdb-remote":
1326 # communicate gdb-remote categories to debugserver
1327 os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
1328
1329 self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
1330 if not self.res.Succeeded():
1331 raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)')
1332
1333 # Communicate log path name to debugserver & lldb-server
1334 server_log_path = "{}-server.log".format(log_basename)
1335 open(server_log_path, 'w').close()
1336 os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
1337
1338 # Communicate channels to lldb-server
1339 os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
1340
1341 if len(lldbtest_config.channels) == 0:
1342 return
1343
1344 def disableLogChannelsForCurrentTest(self):
1345 # close all log files that we opened
1346 for channel_and_categories in lldbtest_config.channels:
1347 # channel format - <channel-name> [<category0> [<category1> ...]]
1348 channel = channel_and_categories.split(' ', 1)[0]
1349 self.ci.HandleCommand("log disable " + channel, self.res)
1350 if not self.res.Succeeded():
1351 raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)')
1352
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001353 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001354 """Fixture for unittest test case setup.
1355
1356 It works with the test driver to conditionally skip tests and does other
1357 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +00001358 #import traceback
1359 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001360
Daniel Malea9115f072013-08-06 15:02:32 +00001361 if "LIBCXX_PATH" in os.environ:
1362 self.libcxxPath = os.environ["LIBCXX_PATH"]
1363 else:
1364 self.libcxxPath = None
1365
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001366 if "LLDBMI_EXEC" in os.environ:
1367 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
1368 else:
1369 self.lldbMiExec = None
1370 self.dont_do_lldbmi_test = True
Vince Harron790d95c2015-05-18 19:39:03 +00001371
Johnny Chenebe51722011-10-07 19:21:09 +00001372 # If we spawn an lldb process for test (via pexpect), do not load the
1373 # init file unless told otherwise.
1374 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
1375 self.lldbOption = ""
1376 else:
1377 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +00001378
Johnny Chen985e7402011-08-01 21:13:26 +00001379 # Assign the test method name to self.testMethodName.
1380 #
1381 # For an example of the use of this attribute, look at test/types dir.
1382 # There are a bunch of test cases under test/types and we don't want the
1383 # module cacheing subsystem to be confused with executable name "a.out"
1384 # used for all the test cases.
1385 self.testMethodName = self._testMethodName
1386
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +00001387 # lldb-mi only test is decorated with @lldbmi_test,
1388 # which also sets the "__lldbmi_test__" attribute of the
1389 # function object to True.
1390 try:
1391 if lldb.just_do_lldbmi_test:
1392 testMethod = getattr(self, self._testMethodName)
1393 if getattr(testMethod, "__lldbmi_test__", False):
1394 pass
1395 else:
1396 self.skipTest("non lldb-mi test")
1397 except AttributeError:
1398 pass
1399
Johnny Chen5ccbccf2011-07-30 01:39:58 +00001400 # Benchmarks test is decorated with @benchmarks_test,
1401 # which also sets the "__benchmarks_test__" attribute of the
1402 # function object to True.
1403 try:
1404 if lldb.just_do_benchmarks_test:
1405 testMethod = getattr(self, self._testMethodName)
1406 if getattr(testMethod, "__benchmarks_test__", False):
1407 pass
1408 else:
1409 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +00001410 except AttributeError:
1411 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001412
Johnny Chen985e7402011-08-01 21:13:26 +00001413 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1414 # with it using pexpect.
1415 self.child = None
1416 self.child_prompt = "(lldb) "
1417 # If the child is interacting with the embedded script interpreter,
1418 # there are two exits required during tear down, first to quit the
1419 # embedded script interpreter and second to quit the lldb command
1420 # interpreter.
1421 self.child_in_script_interpreter = False
1422
Johnny Chenfb4264c2011-08-01 19:50:58 +00001423 # These are for customized teardown cleanup.
1424 self.dict = None
1425 self.doTearDownCleanup = False
1426 # And in rare cases where there are multiple teardown cleanups.
1427 self.dicts = []
1428 self.doTearDownCleanups = False
1429
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001430 # List of spawned subproces.Popen objects
1431 self.subprocesses = []
1432
Daniel Malea69207462013-06-05 21:07:02 +00001433 # List of forked process PIDs
1434 self.forkedProcessPids = []
1435
Johnny Chenfb4264c2011-08-01 19:50:58 +00001436 # Create a string buffer to record the session info, to be dumped into a
1437 # test case specific file if test failure is encountered.
Vince Harron1f160372015-05-21 18:51:20 +00001438 self.log_basename = self.getLogBasenameForCurrentTest()
Vince Harron35b17dc2015-05-21 18:20:21 +00001439
Vince Harron1f160372015-05-21 18:51:20 +00001440 session_file = "{}.log".format(self.log_basename)
Vince Harron35b17dc2015-05-21 18:20:21 +00001441 unbuffered = 0 # 0 is the constant for unbuffered
Vince Harron1f160372015-05-21 18:51:20 +00001442 self.session = open(session_file, "w", unbuffered)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001443
1444 # Optimistically set __errored__, __failed__, __expected__ to False
1445 # initially. If the test errored/failed, the session info
1446 # (self.session) is then dumped into a session specific file for
1447 # diagnosis.
Zachary Turnerb1490b62015-08-26 19:44:56 +00001448 self.__cleanup_errored__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001449 self.__errored__ = False
1450 self.__failed__ = False
1451 self.__expected__ = False
1452 # We are also interested in unexpected success.
1453 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001454 # And skipped tests.
1455 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001456
1457 # See addTearDownHook(self, hook) which allows the client to add a hook
1458 # function to be run during tearDown() time.
1459 self.hooks = []
1460
1461 # See HideStdout(self).
1462 self.sys_stdout_hidden = False
1463
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001464 if self.platformContext:
1465 # set environment variable names for finding shared libraries
1466 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001467
Vince Harron6d3d0f12015-05-10 22:01:59 +00001468 # Create the debugger instance if necessary.
1469 try:
1470 self.dbg = lldb.DBG
1471 except AttributeError:
1472 self.dbg = lldb.SBDebugger.Create()
1473
1474 if not self.dbg:
1475 raise Exception('Invalid debugger instance')
1476
1477 # Retrieve the associated command interpreter instance.
1478 self.ci = self.dbg.GetCommandInterpreter()
1479 if not self.ci:
1480 raise Exception('Could not get the command interpreter')
1481
1482 # And the result object.
1483 self.res = lldb.SBCommandReturnObject()
1484
1485 self.enableLogChannelsForCurrentTest()
1486
Johnny Chen2a808582011-10-19 16:48:07 +00001487 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001488 """Perform the run hooks to bring lldb debugger to the desired state.
1489
Johnny Chen2a808582011-10-19 16:48:07 +00001490 By default, expect a pexpect spawned child and child prompt to be
1491 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1492 and child prompt and use self.runCmd() to run the hooks one by one.
1493
Johnny Chena737ba52011-10-19 01:06:21 +00001494 Note that child is a process spawned by pexpect.spawn(). If not, your
1495 test case is mostly likely going to fail.
1496
1497 See also dotest.py where lldb.runHooks are processed/populated.
1498 """
1499 if not lldb.runHooks:
1500 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001501 if use_cmd_api:
1502 for hook in lldb.runhooks:
1503 self.runCmd(hook)
1504 else:
1505 if not child or not child_prompt:
1506 self.fail("Both child and child_prompt need to be defined.")
1507 for hook in lldb.runHooks:
1508 child.sendline(hook)
1509 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001510
Daniel Malea249287a2013-02-19 16:08:57 +00001511 def setAsync(self, value):
1512 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1513 old_async = self.dbg.GetAsync()
1514 self.dbg.SetAsync(value)
1515 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1516
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001517 def cleanupSubprocesses(self):
1518 # Ensure any subprocesses are cleaned up
1519 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001520 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001521 del p
1522 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001523 # Ensure any forked processes are cleaned up
1524 for pid in self.forkedProcessPids:
1525 if os.path.exists("/proc/" + str(pid)):
1526 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001527
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001528 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001529 """ Creates a subprocess.Popen object with the specified executable and arguments,
1530 saves it in self.subprocesses, and returns the object.
1531 NOTE: if using this function, ensure you also call:
1532
1533 self.addTearDownHook(self.cleanupSubprocesses)
1534
1535 otherwise the test suite will leak processes.
1536 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001537 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001538 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001539 self.subprocesses.append(proc)
1540 return proc
1541
Daniel Malea69207462013-06-05 21:07:02 +00001542 def forkSubprocess(self, executable, args=[]):
1543 """ Fork a subprocess with its own group ID.
1544 NOTE: if using this function, ensure you also call:
1545
1546 self.addTearDownHook(self.cleanupSubprocesses)
1547
1548 otherwise the test suite will leak processes.
1549 """
1550 child_pid = os.fork()
1551 if child_pid == 0:
1552 # If more I/O support is required, this can be beefed up.
1553 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001554 os.dup2(fd, 1)
1555 os.dup2(fd, 2)
1556 # This call causes the child to have its of group ID
1557 os.setpgid(0,0)
1558 os.execvp(executable, [executable] + args)
1559 # Give the child time to get through the execvp() call
1560 time.sleep(0.1)
1561 self.forkedProcessPids.append(child_pid)
1562 return child_pid
1563
Johnny Chenfb4264c2011-08-01 19:50:58 +00001564 def HideStdout(self):
1565 """Hide output to stdout from the user.
1566
1567 During test execution, there might be cases where we don't want to show the
1568 standard output to the user. For example,
1569
Zachary Turner35d017f2015-10-23 17:04:29 +00001570 self.runCmd(r'''sc print("\n\n\tHello!\n")''')
Johnny Chenfb4264c2011-08-01 19:50:58 +00001571
1572 tests whether command abbreviation for 'script' works or not. There is no
1573 need to show the 'Hello' output to the user as long as the 'script' command
1574 succeeds and we are not in TraceOn() mode (see the '-t' option).
1575
1576 In this case, the test method calls self.HideStdout(self) to redirect the
1577 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1578
1579 Note that you should only call this method at most once during a test case
1580 execution. Any subsequent call has no effect at all."""
1581 if self.sys_stdout_hidden:
1582 return
1583
1584 self.sys_stdout_hidden = True
1585 old_stdout = sys.stdout
1586 sys.stdout = open(os.devnull, 'w')
1587 def restore_stdout():
1588 sys.stdout = old_stdout
1589 self.addTearDownHook(restore_stdout)
1590
1591 # =======================================================================
1592 # Methods for customized teardown cleanups as well as execution of hooks.
1593 # =======================================================================
1594
1595 def setTearDownCleanup(self, dictionary=None):
1596 """Register a cleanup action at tearDown() time with a dictinary"""
1597 self.dict = dictionary
1598 self.doTearDownCleanup = True
1599
1600 def addTearDownCleanup(self, dictionary):
1601 """Add a cleanup action at tearDown() time with a dictinary"""
1602 self.dicts.append(dictionary)
1603 self.doTearDownCleanups = True
1604
1605 def addTearDownHook(self, hook):
1606 """
1607 Add a function to be run during tearDown() time.
1608
1609 Hooks are executed in a first come first serve manner.
1610 """
Zachary Turnercd236b82015-10-26 18:48:24 +00001611 if six.callable(hook):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001612 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001613 print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001614 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001615
1616 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001617
Jim Inghamda3a3862014-10-16 23:02:14 +00001618 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001619 # This is for the case of directly spawning 'lldb' and interacting with it
1620 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001621 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001622 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001623 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001624 print("tearing down the child process....", file=sbuf)
Johnny Chen985e7402011-08-01 21:13:26 +00001625 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001626 if self.child_in_script_interpreter:
1627 self.child.sendline('quit()')
1628 self.child.expect_exact(self.child_prompt)
1629 self.child.sendline('settings set interpreter.prompt-on-quit false')
1630 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001631 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001632 except (ValueError, pexpect.ExceptionPexpect):
1633 # child is already terminated
1634 pass
1635 except OSError as exception:
1636 import errno
1637 if exception.errno != errno.EIO:
1638 # unexpected error
1639 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001640 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001641 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001642 finally:
1643 # Give it one final blow to make sure the child is terminated.
1644 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001645
1646 def tearDown(self):
1647 """Fixture for unittest test case teardown."""
1648 #import traceback
1649 #traceback.print_stack()
1650
1651 self.deletePexpectChild()
1652
Johnny Chenfb4264c2011-08-01 19:50:58 +00001653 # Check and run any hook functions.
1654 for hook in reversed(self.hooks):
1655 with recording(self, traceAlways) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00001656 print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
Enrico Granataab0e8312014-11-05 21:31:57 +00001657 import inspect
1658 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001659 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001660 hook()
1661 elif hook_argc == 1:
1662 hook(self)
1663 else:
1664 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001665
1666 del self.hooks
1667
1668 # Perform registered teardown cleanup.
1669 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001670 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001671
1672 # In rare cases where there are multiple teardown cleanups added.
1673 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001674 if self.dicts:
1675 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001676 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001677
Vince Harron9753dd92015-05-10 15:22:09 +00001678 self.disableLogChannelsForCurrentTest()
1679
Johnny Chenfb4264c2011-08-01 19:50:58 +00001680 # =========================================================
1681 # Various callbacks to allow introspection of test progress
1682 # =========================================================
1683
1684 def markError(self):
1685 """Callback invoked when an error (unexpected exception) errored."""
1686 self.__errored__ = True
1687 with recording(self, False) as sbuf:
1688 # False because there's no need to write "ERROR" to the stderr twice.
1689 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001690 print("ERROR", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001691
Zachary Turnerb1490b62015-08-26 19:44:56 +00001692 def markCleanupError(self):
1693 """Callback invoked when an error occurs while a test is cleaning up."""
1694 self.__cleanup_errored__ = True
1695 with recording(self, False) as sbuf:
1696 # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
1697 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001698 print("CLEANUP_ERROR", file=sbuf)
Zachary Turnerb1490b62015-08-26 19:44:56 +00001699
Johnny Chenfb4264c2011-08-01 19:50:58 +00001700 def markFailure(self):
1701 """Callback invoked when a failure (test assertion failure) occurred."""
1702 self.__failed__ = True
1703 with recording(self, False) as sbuf:
1704 # False because there's no need to write "FAIL" to the stderr twice.
1705 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001706 print("FAIL", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001707
Enrico Granatae6cedc12013-02-23 01:05:23 +00001708 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001709 """Callback invoked when an expected failure/error occurred."""
1710 self.__expected__ = True
1711 with recording(self, False) as sbuf:
1712 # False because there's no need to write "expected failure" to the
1713 # stderr twice.
1714 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001715 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001716 print("expected failure", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001717 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001718 print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001719
Johnny Chenc5cc6252011-08-15 23:09:08 +00001720 def markSkippedTest(self):
1721 """Callback invoked when a test is skipped."""
1722 self.__skipped__ = True
1723 with recording(self, False) as sbuf:
1724 # False because there's no need to write "skipped test" to the
1725 # stderr twice.
1726 # Once by the Python unittest framework, and a second time by us.
Zachary Turnerff890da2015-10-19 23:45:41 +00001727 print("skipped test", file=sbuf)
Johnny Chenc5cc6252011-08-15 23:09:08 +00001728
Enrico Granatae6cedc12013-02-23 01:05:23 +00001729 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001730 """Callback invoked when an unexpected success occurred."""
1731 self.__unexpected__ = True
1732 with recording(self, False) as sbuf:
1733 # False because there's no need to write "unexpected success" to the
1734 # stderr twice.
1735 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001736 if bugnumber == None:
Zachary Turnerff890da2015-10-19 23:45:41 +00001737 print("unexpected success", file=sbuf)
Enrico Granatae6cedc12013-02-23 01:05:23 +00001738 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00001739 print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001740
Greg Clayton70995582015-01-07 22:25:50 +00001741 def getRerunArgs(self):
1742 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
Vince Harron9753dd92015-05-10 15:22:09 +00001743
1744 def getLogBasenameForCurrentTest(self, prefix=None):
1745 """
1746 returns a partial path that can be used as the beginning of the name of multiple
1747 log files pertaining to this test
1748
1749 <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
1750 """
1751 dname = os.path.join(os.environ["LLDB_TEST"],
1752 os.environ["LLDB_SESSION_DIRNAME"])
1753 if not os.path.isdir(dname):
1754 os.mkdir(dname)
1755
1756 compiler = self.getCompiler()
1757
1758 if compiler[1] == ':':
1759 compiler = compiler[2:]
Chaoren Lin636a0e32015-07-17 21:40:11 +00001760 if os.path.altsep is not None:
1761 compiler = compiler.replace(os.path.altsep, os.path.sep)
Vince Harron9753dd92015-05-10 15:22:09 +00001762
Vince Harron19e300f2015-05-12 00:50:54 +00001763 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
Vince Harron9753dd92015-05-10 15:22:09 +00001764 if len(fname) > 200:
Vince Harron19e300f2015-05-12 00:50:54 +00001765 fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
Vince Harron9753dd92015-05-10 15:22:09 +00001766
1767 if prefix is not None:
1768 fname = "{}-{}".format(prefix, fname)
1769
1770 return os.path.join(dname, fname)
1771
Johnny Chenfb4264c2011-08-01 19:50:58 +00001772 def dumpSessionInfo(self):
1773 """
1774 Dump the debugger interactions leading to a test error/failure. This
1775 allows for more convenient postmortem analysis.
1776
1777 See also LLDBTestResult (dotest.py) which is a singlton class derived
1778 from TextTestResult and overwrites addError, addFailure, and
1779 addExpectedFailure methods to allow us to to mark the test instance as
1780 such.
1781 """
1782
1783 # We are here because self.tearDown() detected that this test instance
1784 # either errored or failed. The lldb.test_result singleton contains
1785 # two lists (erros and failures) which get populated by the unittest
1786 # framework. Look over there for stack trace information.
1787 #
1788 # The lists contain 2-tuples of TestCase instances and strings holding
1789 # formatted tracebacks.
1790 #
1791 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
Vince Harron9753dd92015-05-10 15:22:09 +00001792
Vince Harron35b17dc2015-05-21 18:20:21 +00001793 # output tracebacks into session
Vince Harron9753dd92015-05-10 15:22:09 +00001794 pairs = []
Johnny Chenfb4264c2011-08-01 19:50:58 +00001795 if self.__errored__:
1796 pairs = lldb.test_result.errors
1797 prefix = 'Error'
Zachary Turner14181db2015-09-11 21:27:37 +00001798 elif self.__cleanup_errored__:
Zachary Turnerb1490b62015-08-26 19:44:56 +00001799 pairs = lldb.test_result.cleanup_errors
1800 prefix = 'CleanupError'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001801 elif self.__failed__:
1802 pairs = lldb.test_result.failures
1803 prefix = 'Failure'
1804 elif self.__expected__:
1805 pairs = lldb.test_result.expectedFailures
1806 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001807 elif self.__skipped__:
1808 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001809 elif self.__unexpected__:
Vince Harron35b17dc2015-05-21 18:20:21 +00001810 prefix = 'UnexpectedSuccess'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001811 else:
Vince Harron35b17dc2015-05-21 18:20:21 +00001812 prefix = 'Success'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001813
Johnny Chenc5cc6252011-08-15 23:09:08 +00001814 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001815 for test, traceback in pairs:
1816 if test is self:
Zachary Turnerff890da2015-10-19 23:45:41 +00001817 print(traceback, file=self.session)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001818
Vince Harron35b17dc2015-05-21 18:20:21 +00001819 # put footer (timestamp/rerun instructions) into session
Johnny Chen8082a002011-08-11 00:16:28 +00001820 testMethod = getattr(self, self._testMethodName)
1821 if getattr(testMethod, "__benchmarks_test__", False):
1822 benchmarks = True
1823 else:
1824 benchmarks = False
1825
Vince Harron35b17dc2015-05-21 18:20:21 +00001826 import datetime
Zachary Turnerff890da2015-10-19 23:45:41 +00001827 print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
1828 print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
1829 print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
Vince Harron35b17dc2015-05-21 18:20:21 +00001830 ('+b' if benchmarks else '-t'),
Zachary Turnerff890da2015-10-19 23:45:41 +00001831 self.getRerunArgs()), file=self.session)
Vince Harron35b17dc2015-05-21 18:20:21 +00001832 self.session.close()
1833 del self.session
1834
1835 # process the log files
Vince Harron1f160372015-05-21 18:51:20 +00001836 log_files_for_this_test = glob.glob(self.log_basename + "*")
Vince Harron35b17dc2015-05-21 18:20:21 +00001837
1838 if prefix != 'Success' or lldbtest_config.log_success:
1839 # keep all log files, rename them to include prefix
1840 dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
1841 for src in log_files_for_this_test:
Zachary Turner306278f2015-05-26 20:26:29 +00001842 if os.path.isfile(src):
1843 dst = src.replace(self.log_basename, dst_log_basename)
1844 if os.name == "nt" and os.path.isfile(dst):
1845 # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
1846 # it silently replaces the destination. Ultimately this means that atomic renames are not
1847 # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
1848 # destination first if it already exists.
1849 os.remove(dst)
Zachary Turner5de068b2015-05-26 19:52:24 +00001850
Zachary Turner306278f2015-05-26 20:26:29 +00001851 os.rename(src, dst)
Vince Harron35b17dc2015-05-21 18:20:21 +00001852 else:
1853 # success! (and we don't want log files) delete log files
1854 for log_file in log_files_for_this_test:
Adrian McCarthya7292042015-09-04 20:48:48 +00001855 try:
1856 os.unlink(log_file)
1857 except:
1858 # We've seen consistent unlink failures on Windows, perhaps because the
1859 # just-created log file is being scanned by anti-virus. Empirically, this
1860 # sleep-and-retry approach allows tests to succeed much more reliably.
1861 # Attempts to figure out exactly what process was still holding a file handle
1862 # have failed because running instrumentation like Process Monitor seems to
1863 # slow things down enough that the problem becomes much less consistent.
1864 time.sleep(0.5)
1865 os.unlink(log_file)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001866
1867 # ====================================================
1868 # Config. methods supported through a plugin interface
1869 # (enables reading of the current test configuration)
1870 # ====================================================
1871
1872 def getArchitecture(self):
1873 """Returns the architecture in effect the test suite is running with."""
1874 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001875 arch = module.getArchitecture()
1876 if arch == 'amd64':
1877 arch = 'x86_64'
1878 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001879
Vince Harron02613762015-05-04 00:17:53 +00001880 def getLldbArchitecture(self):
1881 """Returns the architecture of the lldb binary."""
1882 if not hasattr(self, 'lldbArchitecture'):
1883
1884 # spawn local process
1885 command = [
Vince Harron790d95c2015-05-18 19:39:03 +00001886 lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001887 "-o",
Vince Harron790d95c2015-05-18 19:39:03 +00001888 "file " + lldbtest_config.lldbExec,
Vince Harron02613762015-05-04 00:17:53 +00001889 "-o",
1890 "quit"
1891 ]
1892
1893 output = check_output(command)
1894 str = output.decode("utf-8");
1895
1896 for line in str.splitlines():
1897 m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
1898 if m:
1899 self.lldbArchitecture = m.group(1)
1900 break
1901
1902 return self.lldbArchitecture
1903
Johnny Chenfb4264c2011-08-01 19:50:58 +00001904 def getCompiler(self):
1905 """Returns the compiler in effect the test suite is running with."""
1906 module = builder_module()
1907 return module.getCompiler()
1908
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001909 def getCompilerBinary(self):
1910 """Returns the compiler binary the test suite is running with."""
1911 return self.getCompiler().split()[0]
1912
Daniel Malea0aea0162013-02-27 17:29:46 +00001913 def getCompilerVersion(self):
1914 """ Returns a string that represents the compiler version.
1915 Supports: llvm, clang.
1916 """
1917 from lldbutil import which
1918 version = 'unknown'
1919
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001920 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001921 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001922 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001923 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001924 if m:
1925 version = m.group(1)
1926 return version
1927
Ryan Brown57bee1e2015-09-14 22:45:11 +00001928 def getGoCompilerVersion(self):
1929 """ Returns a string that represents the go compiler version, or None if go is not found.
1930 """
1931 compiler = which("go")
1932 if compiler:
1933 version_output = system([[compiler, "version"]])[0]
1934 for line in version_output.split(os.linesep):
1935 m = re.search('go version (devel|go\\S+)', line)
1936 if m:
1937 return m.group(1)
1938 return None
1939
Greg Claytone0d0a762015-04-02 18:24:03 +00001940 def platformIsDarwin(self):
1941 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00001942 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00001943
Robert Flack13c7ad92015-03-30 14:12:17 +00001944 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00001945 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001946 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00001947
Daniel Maleaadaaec92013-08-06 20:51:41 +00001948 def isIntelCompiler(self):
1949 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1950 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1951
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001952 def expectedCompilerVersion(self, compiler_version):
1953 """Returns True iff compiler_version[1] matches the current compiler version.
1954 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1955 Any operator other than the following defaults to an equality test:
1956 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1957 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001958 if (compiler_version == None):
1959 return True
1960 operator = str(compiler_version[0])
1961 version = compiler_version[1]
1962
1963 if (version == None):
1964 return True
1965 if (operator == '>'):
1966 return self.getCompilerVersion() > version
1967 if (operator == '>=' or operator == '=>'):
1968 return self.getCompilerVersion() >= version
1969 if (operator == '<'):
1970 return self.getCompilerVersion() < version
1971 if (operator == '<=' or operator == '=<'):
1972 return self.getCompilerVersion() <= version
1973 if (operator == '!=' or operator == '!' or operator == 'not'):
1974 return str(version) not in str(self.getCompilerVersion())
1975 return str(version) in str(self.getCompilerVersion())
1976
1977 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001978 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001979 if (compilers == None):
1980 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001981
1982 for compiler in compilers:
1983 if compiler in self.getCompiler():
1984 return True
1985
1986 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001987
Ying Chen7091c2c2015-04-21 01:15:47 +00001988 def expectedArch(self, archs):
1989 """Returns True iff any element of archs is a sub-string of the current architecture."""
1990 if (archs == None):
1991 return True
1992
1993 for arch in archs:
1994 if arch in self.getArchitecture():
1995 return True
1996
1997 return False
1998
Johnny Chenfb4264c2011-08-01 19:50:58 +00001999 def getRunOptions(self):
2000 """Command line option for -A and -C to run this test again, called from
2001 self.dumpSessionInfo()."""
2002 arch = self.getArchitecture()
2003 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00002004 if arch:
2005 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00002006 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00002007 option_str = ""
2008 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00002009 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00002010 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00002011
2012 # ==================================================
2013 # Build methods supported through a plugin interface
2014 # ==================================================
2015
Ed Mastec97323e2014-04-01 18:47:58 +00002016 def getstdlibFlag(self):
2017 """ Returns the proper -stdlib flag, or empty if not required."""
Robert Flack4629c4b2015-05-15 18:54:32 +00002018 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Ed Mastec97323e2014-04-01 18:47:58 +00002019 stdlibflag = "-stdlib=libc++"
2020 else:
2021 stdlibflag = ""
2022 return stdlibflag
2023
Matt Kopec7663b3a2013-09-25 17:44:00 +00002024 def getstdFlag(self):
2025 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00002026 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00002027 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00002028 else:
2029 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00002030 return stdflag
2031
2032 def buildDriver(self, sources, exe_name):
2033 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
2034 or LLDB.framework).
2035 """
2036
2037 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00002038 stdlibflag = self.getstdlibFlag()
Greg Clayton22fd3b12015-10-26 17:52:16 +00002039
2040 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002041 if sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002042 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Daniel Malea55faa402013-05-02 21:44:31 +00002043 d = {'CXX_SOURCES' : sources,
2044 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002045 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002046 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2047 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00002048 }
Ed Maste372c24d2013-07-25 21:02:34 +00002049 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 +00002050 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00002051 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00002052 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002053 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002054 elif sys.platform.startswith('win'):
2055 d = {'CXX_SOURCES' : sources,
2056 'EXE' : exe_name,
2057 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002058 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
Daniel Malea55faa402013-05-02 21:44:31 +00002059 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002060 print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
Daniel Malea55faa402013-05-02 21:44:31 +00002061
2062 self.buildDefault(dictionary=d)
2063
Matt Kopec7663b3a2013-09-25 17:44:00 +00002064 def buildLibrary(self, sources, lib_name):
2065 """Platform specific way to build a default library. """
2066
2067 stdflag = self.getstdFlag()
2068
Greg Clayton22fd3b12015-10-26 17:52:16 +00002069 lib_dir = os.environ["LLDB_LIB_DIR"]
Robert Flack4629c4b2015-05-15 18:54:32 +00002070 if self.platformIsDarwin():
Greg Clayton22fd3b12015-10-26 17:52:16 +00002071 dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
Matt Kopec7663b3a2013-09-25 17:44:00 +00002072 d = {'DYLIB_CXX_SOURCES' : sources,
2073 'DYLIB_NAME' : lib_name,
2074 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
Greg Clayton22fd3b12015-10-26 17:52:16 +00002075 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
2076 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
Matt Kopec7663b3a2013-09-25 17:44:00 +00002077 }
Robert Flack4629c4b2015-05-15 18:54:32 +00002078 elif self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux' or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00002079 d = {'DYLIB_CXX_SOURCES' : sources,
2080 'DYLIB_NAME' : lib_name,
2081 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002082 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
Robert Flack4629c4b2015-05-15 18:54:32 +00002083 elif self.getPlatform() == 'windows':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00002084 d = {'DYLIB_CXX_SOURCES' : sources,
2085 'DYLIB_NAME' : lib_name,
2086 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Greg Clayton22fd3b12015-10-26 17:52:16 +00002087 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
Matt Kopec7663b3a2013-09-25 17:44:00 +00002088 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002089 print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
Matt Kopec7663b3a2013-09-25 17:44:00 +00002090
2091 self.buildDefault(dictionary=d)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002092
Daniel Malea55faa402013-05-02 21:44:31 +00002093 def buildProgram(self, sources, exe_name):
2094 """ Platform specific way to build an executable from C/C++ sources. """
2095 d = {'CXX_SOURCES' : sources,
2096 'EXE' : exe_name}
2097 self.buildDefault(dictionary=d)
2098
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002099 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002100 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002101 if lldb.skip_build_and_cleanup:
2102 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002103 module = builder_module()
Chaoren Line9bbabc2015-07-18 00:37:55 +00002104 if target_is_android():
2105 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002106 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002107 raise Exception("Don't know how to build default binary")
2108
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002109 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002110 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002111 if lldb.skip_build_and_cleanup:
2112 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002113 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002114 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002115 raise Exception("Don't know how to build binary with dsym")
2116
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002117 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002118 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002119 if lldb.skip_build_and_cleanup:
2120 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00002121 module = builder_module()
Chaoren Lin9070f532015-07-17 22:13:29 +00002122 if target_is_android():
Chaoren Line9bbabc2015-07-18 00:37:55 +00002123 dictionary = append_android_envs(dictionary)
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00002124 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00002125 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00002126
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002127 def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
2128 """Platform specific way to build binaries with dwarf maps."""
2129 if lldb.skip_build_and_cleanup:
2130 return
2131 module = builder_module()
2132 if target_is_android():
2133 dictionary = append_android_envs(dictionary)
2134 if not module.buildDwo(self, architecture, compiler, dictionary, clean):
2135 raise Exception("Don't know how to build binary with dwo")
2136
Ryan Brown57bee1e2015-09-14 22:45:11 +00002137 def buildGo(self):
2138 """Build the default go binary.
2139 """
2140 system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
2141
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00002142 def signBinary(self, binary_path):
2143 if sys.platform.startswith("darwin"):
2144 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
2145 call(codesign_cmd, shell=True)
2146
Kuba Breckabeed8212014-09-04 01:03:18 +00002147 def findBuiltClang(self):
2148 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
2149 paths_to_try = [
2150 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
2151 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
2152 "llvm-build/Release/x86_64/Release/bin/clang",
2153 "llvm-build/Debug/x86_64/Debug/bin/clang",
2154 ]
2155 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
2156 for p in paths_to_try:
2157 path = os.path.join(lldb_root_path, p)
2158 if os.path.exists(path):
2159 return path
Ilia Kd9953052015-03-12 07:19:41 +00002160
2161 # Tries to find clang at the same folder as the lldb
Vince Harron790d95c2015-05-18 19:39:03 +00002162 path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
Ilia Kd9953052015-03-12 07:19:41 +00002163 if os.path.exists(path):
2164 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00002165
2166 return os.environ["CC"]
2167
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002168 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00002169 """ Returns a dictionary (which can be provided to build* functions above) which
2170 contains OS-specific build flags.
2171 """
2172 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00002173 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00002174
2175 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
Robert Flack4629c4b2015-05-15 18:54:32 +00002176 if not use_libstdcxx and self.platformIsDarwin():
Daniel Malea9115f072013-08-06 15:02:32 +00002177 use_libcxx = True
2178
2179 if use_libcxx and self.libcxxPath:
2180 cflags += "-stdlib=libc++ "
2181 if self.libcxxPath:
2182 libcxxInclude = os.path.join(self.libcxxPath, "include")
2183 libcxxLib = os.path.join(self.libcxxPath, "lib")
2184 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
2185 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
2186
Andrew Kaylor93132f52013-05-28 23:04:25 +00002187 if use_cpp11:
2188 cflags += "-std="
2189 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
2190 cflags += "c++0x"
2191 else:
2192 cflags += "c++11"
Robert Flack4629c4b2015-05-15 18:54:32 +00002193 if self.platformIsDarwin() or self.getPlatform() == "freebsd":
Andrew Kaylor93132f52013-05-28 23:04:25 +00002194 cflags += " -stdlib=libc++"
2195 elif "clang" in self.getCompiler():
2196 cflags += " -stdlib=libstdc++"
2197
Andrew Kaylor93132f52013-05-28 23:04:25 +00002198 return {'CFLAGS_EXTRAS' : cflags,
2199 'LD_EXTRAS' : ldflags,
2200 }
2201
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002202 def cleanup(self, dictionary=None):
2203 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00002204 if lldb.skip_build_and_cleanup:
2205 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002206 module = builder_module()
2207 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00002208 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00002209
Daniel Malea55faa402013-05-02 21:44:31 +00002210 def getLLDBLibraryEnvVal(self):
2211 """ Returns the path that the OS-specific library search environment variable
2212 (self.dylibPath) should be set to in order for a program to find the LLDB
2213 library. If an environment variable named self.dylibPath is already set,
2214 the new path is appended to it and returned.
2215 """
2216 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
Greg Clayton22fd3b12015-10-26 17:52:16 +00002217 lib_dir = os.environ["LLDB_LIB_DIR"]
Daniel Malea55faa402013-05-02 21:44:31 +00002218 if existing_library_path:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002219 return "%s:%s" % (existing_library_path, lib_dir)
Daniel Malea55faa402013-05-02 21:44:31 +00002220 elif sys.platform.startswith("darwin"):
Greg Clayton22fd3b12015-10-26 17:52:16 +00002221 return os.path.join(lib_dir, 'LLDB.framework')
Daniel Malea55faa402013-05-02 21:44:31 +00002222 else:
Greg Clayton22fd3b12015-10-26 17:52:16 +00002223 return lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00002224
Ed Maste437f8f62013-09-09 14:04:04 +00002225 def getLibcPlusPlusLibs(self):
Robert Flackfa5ad652015-05-13 20:17:34 +00002226 if self.getPlatform() == 'freebsd' or self.getPlatform() == 'linux':
Ed Maste437f8f62013-09-09 14:04:04 +00002227 return ['libc++.so.1']
2228 else:
2229 return ['libc++.1.dylib','libc++abi.dylib']
2230
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002231# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
2232# We change the test methods to create a new test method for each test for each debug info we are
2233# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
2234# the new test method we remove the old method at the same time.
2235class LLDBTestCaseFactory(type):
2236 def __new__(cls, name, bases, attrs):
2237 newattrs = {}
Zachary Turner606e1e32015-10-23 17:53:51 +00002238 for attrname, attrvalue in attrs.items():
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002239 if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
2240 @dsym_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002241 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002242 def dsym_test_method(self, attrvalue=attrvalue):
2243 self.debug_info = "dsym"
2244 return attrvalue(self)
2245 dsym_method_name = attrname + "_dsym"
2246 dsym_test_method.__name__ = dsym_method_name
2247 newattrs[dsym_method_name] = dsym_test_method
2248
2249 @dwarf_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002250 @wraps(attrvalue)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002251 def dwarf_test_method(self, attrvalue=attrvalue):
2252 self.debug_info = "dwarf"
2253 return attrvalue(self)
2254 dwarf_method_name = attrname + "_dwarf"
2255 dwarf_test_method.__name__ = dwarf_method_name
2256 newattrs[dwarf_method_name] = dwarf_test_method
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002257
2258 @dwo_test
Pavel Labathdc8b2d32015-10-26 09:28:32 +00002259 @wraps(attrvalue)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002260 def dwo_test_method(self, attrvalue=attrvalue):
2261 self.debug_info = "dwo"
2262 return attrvalue(self)
2263 dwo_method_name = attrname + "_dwo"
2264 dwo_test_method.__name__ = dwo_method_name
2265 newattrs[dwo_method_name] = dwo_test_method
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002266 else:
2267 newattrs[attrname] = attrvalue
2268 return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
2269
Zachary Turner43a01e42015-10-20 21:06:05 +00002270# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
2271@add_metaclass(LLDBTestCaseFactory)
Johnny Chena74bb0a2011-08-01 18:46:13 +00002272class TestBase(Base):
2273 """
2274 This abstract base class is meant to be subclassed. It provides default
2275 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
2276 among other things.
2277
2278 Important things for test class writers:
2279
2280 - Overwrite the mydir class attribute, otherwise your test class won't
2281 run. It specifies the relative directory to the top level 'test' so
2282 the test harness can change to the correct working directory before
2283 running your test.
2284
2285 - The setUp method sets up things to facilitate subsequent interactions
2286 with the debugger as part of the test. These include:
2287 - populate the test method name
2288 - create/get a debugger set with synchronous mode (self.dbg)
2289 - get the command interpreter from with the debugger (self.ci)
2290 - create a result object for use with the command interpreter
2291 (self.res)
2292 - plus other stuffs
2293
2294 - The tearDown method tries to perform some necessary cleanup on behalf
2295 of the test to return the debugger to a good state for the next test.
2296 These include:
2297 - execute any tearDown hooks registered by the test method with
2298 TestBase.addTearDownHook(); examples can be found in
2299 settings/TestSettings.py
2300 - kill the inferior process associated with each target, if any,
2301 and, then delete the target from the debugger's target list
2302 - perform build cleanup before running the next test method in the
2303 same test class; examples of registering for this service can be
2304 found in types/TestIntegerTypes.py with the call:
2305 - self.setTearDownCleanup(dictionary=d)
2306
2307 - Similarly setUpClass and tearDownClass perform classwise setup and
2308 teardown fixtures. The tearDownClass method invokes a default build
2309 cleanup for the entire test class; also, subclasses can implement the
2310 classmethod classCleanup(cls) to perform special class cleanup action.
2311
2312 - The instance methods runCmd and expect are used heavily by existing
2313 test cases to send a command to the command interpreter and to perform
2314 string/pattern matching on the output of such command execution. The
2315 expect method also provides a mode to peform string/pattern matching
2316 without running a command.
2317
2318 - The build methods buildDefault, buildDsym, and buildDwarf are used to
2319 build the binaries used during a particular test scenario. A plugin
2320 should be provided for the sys.platform running the test suite. The
2321 Mac OS X implementation is located in plugins/darwin.py.
2322 """
2323
2324 # Maximum allowed attempts when launching the inferior process.
2325 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
2326 maxLaunchCount = 3;
2327
2328 # Time to wait before the next launching attempt in second(s).
2329 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
2330 timeWaitNextLaunch = 1.0;
2331
2332 def doDelay(self):
2333 """See option -w of dotest.py."""
2334 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
2335 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
2336 waitTime = 1.0
2337 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
2338 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
2339 time.sleep(waitTime)
2340
Enrico Granata165f8af2012-09-21 19:10:53 +00002341 # Returns the list of categories to which this test case belongs
2342 # by default, look for a ".categories" file, and read its contents
2343 # if no such file exists, traverse the hierarchy - we guarantee
2344 # a .categories to exist at the top level directory so we do not end up
2345 # looping endlessly - subclasses are free to define their own categories
2346 # in whatever way makes sense to them
2347 def getCategories(self):
2348 import inspect
2349 import os.path
2350 folder = inspect.getfile(self.__class__)
2351 folder = os.path.dirname(folder)
2352 while folder != '/':
2353 categories_file_name = os.path.join(folder,".categories")
2354 if os.path.exists(categories_file_name):
2355 categories_file = open(categories_file_name,'r')
2356 categories = categories_file.readline()
2357 categories_file.close()
2358 categories = str.replace(categories,'\n','')
2359 categories = str.replace(categories,'\r','')
2360 return categories.split(',')
2361 else:
2362 folder = os.path.dirname(folder)
2363 continue
2364
Johnny Chena74bb0a2011-08-01 18:46:13 +00002365 def setUp(self):
2366 #import traceback
2367 #traceback.print_stack()
2368
2369 # Works with the test driver to conditionally skip tests via decorators.
2370 Base.setUp(self)
2371
Johnny Chena74bb0a2011-08-01 18:46:13 +00002372 try:
2373 if lldb.blacklist:
2374 className = self.__class__.__name__
2375 classAndMethodName = "%s.%s" % (className, self._testMethodName)
2376 if className in lldb.blacklist:
2377 self.skipTest(lldb.blacklist.get(className))
2378 elif classAndMethodName in lldb.blacklist:
2379 self.skipTest(lldb.blacklist.get(classAndMethodName))
2380 except AttributeError:
2381 pass
2382
Johnny Chened492022011-06-21 00:53:00 +00002383 # Insert some delay between successive test cases if specified.
2384 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00002385
Johnny Chenf2b70232010-08-25 18:49:48 +00002386 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
2387 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
2388
Johnny Chen430eb762010-10-19 16:00:42 +00002389 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00002390 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00002391
Daniel Maleae0f8f572013-08-26 23:57:52 +00002392 #
2393 # Warning: MAJOR HACK AHEAD!
2394 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
2395 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
2396 # command, instead. See also runCmd() where it decorates the "file filename" call
2397 # with additional functionality when running testsuite remotely.
2398 #
2399 if lldb.lldbtest_remote_sandbox:
2400 def DecoratedCreateTarget(arg):
2401 self.runCmd("file %s" % arg)
2402 target = self.dbg.GetSelectedTarget()
2403 #
Greg Claytonc6947512013-12-13 19:18:59 +00002404 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00002405 # johnny @ 04/23/2012
2406 #
2407 def DecoratedLaunchSimple(argv, envp, wd):
2408 self.runCmd("run")
2409 return target.GetProcess()
2410 target.LaunchSimple = DecoratedLaunchSimple
2411
2412 return target
2413 self.dbg.CreateTarget = DecoratedCreateTarget
2414 if self.TraceOn():
Zachary Turnerff890da2015-10-19 23:45:41 +00002415 print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
Daniel Maleae0f8f572013-08-26 23:57:52 +00002416
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002417 # We want our debugger to be synchronous.
2418 self.dbg.SetAsync(False)
2419
2420 # Retrieve the associated command interpreter instance.
2421 self.ci = self.dbg.GetCommandInterpreter()
2422 if not self.ci:
2423 raise Exception('Could not get the command interpreter')
2424
2425 # And the result object.
2426 self.res = lldb.SBCommandReturnObject()
2427
Johnny Chen44d24972012-04-16 18:55:15 +00002428 # Run global pre-flight code, if defined via the config file.
2429 if lldb.pre_flight:
2430 lldb.pre_flight(self)
2431
Enrico Granatabd0998a2015-10-02 22:53:32 +00002432 if lldb.remote_platform and lldb.remote_platform_working_dir:
Chaoren Lin3e2bdb42015-05-11 17:53:39 +00002433 remote_test_dir = lldbutil.join_remote_paths(
2434 lldb.remote_platform_working_dir,
2435 self.getArchitecture(),
2436 str(self.test_number),
2437 self.mydir)
Zachary Turner14116682015-10-26 18:48:14 +00002438 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
Greg Claytonfb909312013-11-23 01:58:15 +00002439 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00002440 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002441
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002442 # This function removes all files from the current working directory while leaving
2443 # the directories in place. The cleaup is required to reduce the disk space required
2444 # by the test suit while leaving the directories untached is neccessary because
2445 # sub-directories might belong to an other test
2446 def clean_working_directory():
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002447 # TODO: Make it working on Windows when we need it for remote debugging support
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002448 # TODO: Replace the heuristic to remove the files with a logic what collects the
2449 # list of files we have to remove during test runs.
2450 shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
Tamas Berghammerf2addf82015-10-07 12:38:29 +00002451 lldb.remote_platform.Run(shell_cmd)
Tamas Berghammer11db2d32015-10-07 14:52:16 +00002452 self.addTearDownHook(clean_working_directory)
Greg Claytonfb909312013-11-23 01:58:15 +00002453 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002454 print("error: making remote directory '%s': %s" % (remote_test_dir, error))
Greg Claytonfb909312013-11-23 01:58:15 +00002455
Greg Clayton35c91342014-11-17 18:40:27 +00002456 def registerSharedLibrariesWithTarget(self, target, shlibs):
2457 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
2458
2459 Any modules in the target that have their remote install file specification set will
2460 get uploaded to the remote host. This function registers the local copies of the
2461 shared libraries with the target and sets their remote install locations so they will
2462 be uploaded when the target is run.
2463 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00002464 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002465 return None
Greg Clayton35c91342014-11-17 18:40:27 +00002466
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002467 shlib_environment_var = self.platformContext.shlib_environment_var
2468 shlib_prefix = self.platformContext.shlib_prefix
2469 shlib_extension = '.' + self.platformContext.shlib_extension
2470
2471 working_dir = self.get_process_working_directory()
2472 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
2473 # Add any shared libraries to our target if remote so they get
2474 # uploaded into the working directory on the remote side
2475 for name in shlibs:
2476 # The path can be a full path to a shared library, or a make file name like "Foo" for
2477 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
2478 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
2479 # of the shared library accordingly
2480 if os.path.exists(name):
2481 local_shlib_path = name # name is the full path to the local shared library
2482 else:
2483 # Check relative names
2484 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
2485 if not os.path.exists(local_shlib_path):
2486 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00002487 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002488 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00002489
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002490 # Make sure we found the local shared library in the above code
2491 self.assertTrue(os.path.exists(local_shlib_path))
2492
2493 # Add the shared library to our target
2494 shlib_module = target.AddModule(local_shlib_path, None, None, None)
2495 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00002496 # We must set the remote install location if we want the shared library
2497 # to get uploaded to the remote target
Chaoren Lin5d76b1b2015-06-06 00:25:50 +00002498 remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
Greg Clayton35c91342014-11-17 18:40:27 +00002499 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00002500
2501 return environment
2502
Enrico Granata44818162012-10-24 01:23:57 +00002503 # utility methods that tests can use to access the current objects
2504 def target(self):
2505 if not self.dbg:
2506 raise Exception('Invalid debugger instance')
2507 return self.dbg.GetSelectedTarget()
2508
2509 def process(self):
2510 if not self.dbg:
2511 raise Exception('Invalid debugger instance')
2512 return self.dbg.GetSelectedTarget().GetProcess()
2513
2514 def thread(self):
2515 if not self.dbg:
2516 raise Exception('Invalid debugger instance')
2517 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
2518
2519 def frame(self):
2520 if not self.dbg:
2521 raise Exception('Invalid debugger instance')
2522 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
2523
Greg Claytonc6947512013-12-13 19:18:59 +00002524 def get_process_working_directory(self):
2525 '''Get the working directory that should be used when launching processes for local or remote processes.'''
2526 if lldb.remote_platform:
2527 # Remote tests set the platform working directory up in TestBase.setUp()
2528 return lldb.remote_platform.GetWorkingDirectory()
2529 else:
2530 # local tests change directory into each test subdirectory
2531 return os.getcwd()
2532
Johnny Chenbf6ffa32010-07-03 03:41:59 +00002533 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00002534 #import traceback
2535 #traceback.print_stack()
2536
Adrian McCarthy6ecdbc82015-10-15 22:39:55 +00002537 # Ensure all the references to SB objects have gone away so that we can
2538 # be sure that all test-specific resources have been freed before we
2539 # attempt to delete the targets.
2540 gc.collect()
2541
Johnny Chen3794ad92011-06-15 21:24:24 +00002542 # Delete the target(s) from the debugger as a general cleanup step.
2543 # This includes terminating the process for each target, if any.
2544 # We'd like to reuse the debugger for our next test without incurring
2545 # the initialization overhead.
2546 targets = []
2547 for target in self.dbg:
2548 if target:
2549 targets.append(target)
2550 process = target.GetProcess()
2551 if process:
2552 rc = self.invoke(process, "Kill")
2553 self.assertTrue(rc.Success(), PROCESS_KILLED)
2554 for target in targets:
2555 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00002556
Johnny Chen44d24972012-04-16 18:55:15 +00002557 # Run global post-flight code, if defined via the config file.
2558 if lldb.post_flight:
2559 lldb.post_flight(self)
2560
Zachary Turner65fe1eb2015-03-26 16:43:25 +00002561 # Do this last, to make sure it's in reverse order from how we setup.
2562 Base.tearDown(self)
2563
Zachary Turner95812042015-03-26 18:54:21 +00002564 # This must be the last statement, otherwise teardown hooks or other
2565 # lines might depend on this still being active.
2566 del self.dbg
2567
Johnny Chen86268e42011-09-30 21:48:35 +00002568 def switch_to_thread_with_stop_reason(self, stop_reason):
2569 """
2570 Run the 'thread list' command, and select the thread with stop reason as
2571 'stop_reason'. If no such thread exists, no select action is done.
2572 """
2573 from lldbutil import stop_reason_to_str
2574 self.runCmd('thread list')
2575 output = self.res.GetOutput()
2576 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
2577 stop_reason_to_str(stop_reason))
2578 for line in output.splitlines():
2579 matched = thread_line_pattern.match(line)
2580 if matched:
2581 self.runCmd('thread select %s' % matched.group(1))
2582
Enrico Granata7594f142013-06-17 22:51:50 +00002583 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00002584 """
2585 Ask the command interpreter to handle the command and then check its
2586 return status.
2587 """
2588 # Fail fast if 'cmd' is not meaningful.
2589 if not cmd or len(cmd) == 0:
2590 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002591
Johnny Chen8d55a342010-08-31 17:42:54 +00002592 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002593
Daniel Maleae0f8f572013-08-26 23:57:52 +00002594 # This is an opportunity to insert the 'platform target-install' command if we are told so
2595 # via the settig of lldb.lldbtest_remote_sandbox.
2596 if cmd.startswith("target create "):
2597 cmd = cmd.replace("target create ", "file ")
2598 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
2599 with recording(self, trace) as sbuf:
2600 the_rest = cmd.split("file ")[1]
2601 # Split the rest of the command line.
2602 atoms = the_rest.split()
2603 #
2604 # NOTE: This assumes that the options, if any, follow the file command,
2605 # instead of follow the specified target.
2606 #
2607 target = atoms[-1]
2608 # Now let's get the absolute pathname of our target.
2609 abs_target = os.path.abspath(target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002610 print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002611 fpath, fname = os.path.split(abs_target)
2612 parent_dir = os.path.split(fpath)[0]
2613 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
Zachary Turnerff890da2015-10-19 23:45:41 +00002614 print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002615 self.ci.HandleCommand(platform_target_install_command, self.res)
2616 # And this is the file command we want to execute, instead.
2617 #
2618 # Warning: SIDE EFFECT AHEAD!!!
2619 # Populate the remote executable pathname into the lldb namespace,
2620 # so that test cases can grab this thing out of the namespace.
2621 #
2622 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
2623 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
Zachary Turnerff890da2015-10-19 23:45:41 +00002624 print("And this is the replaced file command: %s" % cmd, file=sbuf)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002625
Johnny Chen63dfb272010-09-01 00:15:19 +00002626 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002627
Johnny Chen63dfb272010-09-01 00:15:19 +00002628 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002629 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002630
Johnny Chen150c3cc2010-10-15 01:18:29 +00002631 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002632 print("runCmd:", cmd, file=sbuf)
Johnny Chenab254f52010-10-15 16:13:00 +00002633 if not check:
Zachary Turnerff890da2015-10-19 23:45:41 +00002634 print("check of return status not required", file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002635 if self.res.Succeeded():
Zachary Turnerff890da2015-10-19 23:45:41 +00002636 print("output:", self.res.GetOutput(), file=sbuf)
Johnny Chenf2b70232010-08-25 18:49:48 +00002637 else:
Zachary Turnerff890da2015-10-19 23:45:41 +00002638 print("runCmd failed!", file=sbuf)
2639 print(self.res.GetError(), file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002640
Johnny Chenff3d01d2010-08-20 21:03:09 +00002641 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002642 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002643 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002644 # For process launch, wait some time before possible next try.
2645 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002646 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002647 print("Command '" + cmd + "' failed!", file=sbuf)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002648
Johnny Chen27f212d2010-08-19 23:26:59 +00002649 if check:
Sean Callanan05834cd2015-07-01 23:56:30 +00002650 self.assertTrue(self.res.Succeeded(),
2651 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002652
Jim Ingham63dfc722012-09-22 00:05:11 +00002653 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2654 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2655
2656 Otherwise, all the arguments have the same meanings as for the expect function"""
2657
2658 trace = (True if traceAlways else trace)
2659
2660 if exe:
2661 # First run the command. If we are expecting error, set check=False.
2662 # Pass the assert message along since it provides more semantic info.
2663 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2664
2665 # Then compare the output against expected strings.
2666 output = self.res.GetError() if error else self.res.GetOutput()
2667
2668 # If error is True, the API client expects the command to fail!
2669 if error:
2670 self.assertFalse(self.res.Succeeded(),
2671 "Command '" + str + "' is expected to fail!")
2672 else:
2673 # No execution required, just compare str against the golden input.
2674 output = str
2675 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002676 print("looking at:", output, file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002677
2678 # The heading says either "Expecting" or "Not expecting".
2679 heading = "Expecting" if matching else "Not expecting"
2680
2681 for pattern in patterns:
2682 # Match Objects always have a boolean value of True.
2683 match_object = re.search(pattern, output)
2684 matched = bool(match_object)
2685 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002686 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2687 print("Matched" if matched else "Not matched", file=sbuf)
Jim Ingham63dfc722012-09-22 00:05:11 +00002688 if matched:
2689 break
2690
2691 self.assertTrue(matched if matching else not matched,
2692 msg if msg else EXP_MSG(str, exe))
2693
2694 return match_object
2695
Enrico Granata7594f142013-06-17 22:51:50 +00002696 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 +00002697 """
2698 Similar to runCmd; with additional expect style output matching ability.
2699
2700 Ask the command interpreter to handle the command and then check its
2701 return status. The 'msg' parameter specifies an informational assert
2702 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002703 'startstr', matches the substrings contained in 'substrs', and regexp
2704 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002705
2706 If the keyword argument error is set to True, it signifies that the API
2707 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002708 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002709 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002710
2711 If the keyword argument matching is set to False, it signifies that the API
2712 client is expecting the output of the command not to match the golden
2713 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002714
2715 Finally, the required argument 'str' represents the lldb command to be
2716 sent to the command interpreter. In case the keyword argument 'exe' is
2717 set to False, the 'str' is treated as a string to be matched/not-matched
2718 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002719 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002720 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002721
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002722 if exe:
2723 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002724 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002725 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002726
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002727 # Then compare the output against expected strings.
2728 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002729
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002730 # If error is True, the API client expects the command to fail!
2731 if error:
2732 self.assertFalse(self.res.Succeeded(),
2733 "Command '" + str + "' is expected to fail!")
2734 else:
2735 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002736 if isinstance(str,lldb.SBCommandReturnObject):
2737 output = str.GetOutput()
2738 else:
2739 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002740 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002741 print("looking at:", output, file=sbuf)
Johnny Chenb3307862010-09-17 22:28:51 +00002742
Johnny Chenea88e942010-09-21 21:08:53 +00002743 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002744 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002745
2746 # Start from the startstr, if specified.
2747 # If there's no startstr, set the initial state appropriately.
2748 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002749
Johnny Chen150c3cc2010-10-15 01:18:29 +00002750 if startstr:
2751 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002752 print("%s start string: %s" % (heading, startstr), file=sbuf)
2753 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenb145bba2010-08-20 18:25:15 +00002754
Johnny Chen86268e42011-09-30 21:48:35 +00002755 # Look for endstr, if specified.
2756 keepgoing = matched if matching else not matched
2757 if endstr:
2758 matched = output.endswith(endstr)
2759 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002760 print("%s end string: %s" % (heading, endstr), file=sbuf)
2761 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chen86268e42011-09-30 21:48:35 +00002762
Johnny Chenea88e942010-09-21 21:08:53 +00002763 # Look for sub strings, if specified.
2764 keepgoing = matched if matching else not matched
2765 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002766 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002767 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002768 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002769 print("%s sub string: %s" % (heading, str), file=sbuf)
2770 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002771 keepgoing = matched if matching else not matched
2772 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002773 break
2774
Johnny Chenea88e942010-09-21 21:08:53 +00002775 # Search for regular expression patterns, if specified.
2776 keepgoing = matched if matching else not matched
2777 if patterns and keepgoing:
2778 for pattern in patterns:
2779 # Match Objects always have a boolean value of True.
2780 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002781 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002782 print("%s pattern: %s" % (heading, pattern), file=sbuf)
2783 print("Matched" if matched else "Not matched", file=sbuf)
Johnny Chenea88e942010-09-21 21:08:53 +00002784 keepgoing = matched if matching else not matched
2785 if not keepgoing:
2786 break
Johnny Chenea88e942010-09-21 21:08:53 +00002787
2788 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002789 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002790
Johnny Chenf3c59232010-08-25 22:52:45 +00002791 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002792 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002793 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002794
2795 method = getattr(obj, name)
2796 import inspect
2797 self.assertTrue(inspect.ismethod(method),
2798 name + "is a method name of object: " + str(obj))
2799 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002800 with recording(self, trace) as sbuf:
Zachary Turnerff890da2015-10-19 23:45:41 +00002801 print(str(method) + ":", result, file=sbuf)
Johnny Chenf3c59232010-08-25 22:52:45 +00002802 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002803
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002804 def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
2805 """Platform specific way to build the default binaries."""
2806 if lldb.skip_build_and_cleanup:
2807 return
2808 module = builder_module()
2809 if target_is_android():
2810 dictionary = append_android_envs(dictionary)
2811 if self.debug_info is None:
2812 return self.buildDefault(architecture, compiler, dictionary, clean)
2813 elif self.debug_info == "dsym":
2814 return self.buildDsym(architecture, compiler, dictionary, clean)
2815 elif self.debug_info == "dwarf":
2816 return self.buildDwarf(architecture, compiler, dictionary, clean)
Tamas Berghammer4c0c7a72015-10-07 10:02:17 +00002817 elif self.debug_info == "dwo":
2818 return self.buildDwo(architecture, compiler, dictionary, clean)
2819 else:
2820 self.fail("Can't build for debug info: %s" % self.debug_info)
Tamas Berghammerc8fd1302015-09-30 10:12:40 +00002821
Johnny Chenf359cf22011-05-27 23:36:52 +00002822 # =================================================
2823 # Misc. helper methods for debugging test execution
2824 # =================================================
2825
Johnny Chen56b92a72011-07-11 19:15:11 +00002826 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002827 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00002828 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002829
Johnny Chen8d55a342010-08-31 17:42:54 +00002830 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002831 return
2832
2833 err = sys.stderr
2834 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002835 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2836 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2837 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2838 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2839 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2840 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2841 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2842 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2843 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002844
Johnny Chen36c5eb12011-08-05 20:17:27 +00002845 def DebugSBType(self, type):
2846 """Debug print a SBType object, if traceAlways is True."""
2847 if not traceAlways:
2848 return
2849
2850 err = sys.stderr
2851 err.write(type.GetName() + ":\n")
2852 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2853 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2854 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2855
Johnny Chenb877f1e2011-03-12 01:18:19 +00002856 def DebugPExpect(self, child):
2857 """Debug the spwaned pexpect object."""
2858 if not traceAlways:
2859 return
2860
Zachary Turnerff890da2015-10-19 23:45:41 +00002861 print(child)
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002862
2863 @classmethod
2864 def RemoveTempFile(cls, file):
2865 if os.path.exists(file):
2866 os.remove(file)