blob: 3876cae36664514e5555390268011b667bd8d9e6 [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
12entire test suite. Users who want to run a test case on its own can specify the
13LLDB_TEST and PYTHONPATH environment variables, for example:
14
15$ export LLDB_TEST=$PWD
Johnny Chen8d55a342010-08-31 17:42:54 +000016$ export PYTHONPATH=/Volumes/data/lldb/svn/trunk/build/Debug/LLDB.framework/Resources/Python:$LLDB_TEST:$LLDB_TEST/plugins
Johnny Chenbf6ffa32010-07-03 03:41:59 +000017$ echo $LLDB_TEST
18/Volumes/data/lldb/svn/trunk/test
19$ echo $PYTHONPATH
Johnny Chen8d55a342010-08-31 17:42:54 +000020/Volumes/data/lldb/svn/trunk/build/Debug/LLDB.framework/Resources/Python:/Volumes/data/lldb/svn/trunk/test:/Volumes/data/lldb/svn/trunk/test/plugins
Johnny Chenbf6ffa32010-07-03 03:41:59 +000021$ python function_types/TestFunctionTypes.py
22.
23----------------------------------------------------------------------
24Ran 1 test in 0.363s
25
26OK
Johnny Chend0190a62010-08-23 17:10:44 +000027$ LLDB_COMMAND_TRACE=YES python array_types/TestArrayTypes.py
Johnny Chen57b47382010-09-02 22:25:47 +000028
29...
Johnny Chend0190a62010-08-23 17:10:44 +000030
31runCmd: breakpoint set -f main.c -l 42
32output: Breakpoint created: 1: file ='main.c', line = 42, locations = 1
33
34runCmd: run
35output: Launching '/Volumes/data/lldb/svn/trunk/test/array_types/a.out' (x86_64)
36
Johnny Chen57b47382010-09-02 22:25:47 +000037...
Johnny Chend0190a62010-08-23 17:10:44 +000038
Johnny Chen57b47382010-09-02 22:25:47 +000039runCmd: frame variable strings
Johnny Chend0190a62010-08-23 17:10:44 +000040output: (char *[4]) strings = {
41 (char *) strings[0] = 0x0000000100000f0c "Hello",
42 (char *) strings[1] = 0x0000000100000f12 "Hola",
43 (char *) strings[2] = 0x0000000100000f17 "Bonjour",
44 (char *) strings[3] = 0x0000000100000f1f "Guten Tag"
45}
46
Johnny Chen57b47382010-09-02 22:25:47 +000047runCmd: frame variable char_16
Johnny Chend0190a62010-08-23 17:10:44 +000048output: (char [16]) char_16 = {
49 (char) char_16[0] = 'H',
50 (char) char_16[1] = 'e',
51 (char) char_16[2] = 'l',
52 (char) char_16[3] = 'l',
53 (char) char_16[4] = 'o',
54 (char) char_16[5] = ' ',
55 (char) char_16[6] = 'W',
56 (char) char_16[7] = 'o',
57 (char) char_16[8] = 'r',
58 (char) char_16[9] = 'l',
59 (char) char_16[10] = 'd',
60 (char) char_16[11] = '\n',
61 (char) char_16[12] = '\0',
62 (char) char_16[13] = '\0',
63 (char) char_16[14] = '\0',
64 (char) char_16[15] = '\0'
65}
66
Johnny Chen57b47382010-09-02 22:25:47 +000067runCmd: frame variable ushort_matrix
Johnny Chend0190a62010-08-23 17:10:44 +000068output: (unsigned short [2][3]) ushort_matrix = {
69 (unsigned short [3]) ushort_matrix[0] = {
70 (unsigned short) ushort_matrix[0][0] = 0x0001,
71 (unsigned short) ushort_matrix[0][1] = 0x0002,
72 (unsigned short) ushort_matrix[0][2] = 0x0003
73 },
74 (unsigned short [3]) ushort_matrix[1] = {
75 (unsigned short) ushort_matrix[1][0] = 0x000b,
76 (unsigned short) ushort_matrix[1][1] = 0x0016,
77 (unsigned short) ushort_matrix[1][2] = 0x0021
78 }
79}
80
Johnny Chen57b47382010-09-02 22:25:47 +000081runCmd: frame variable long_6
Johnny Chend0190a62010-08-23 17:10:44 +000082output: (long [6]) long_6 = {
83 (long) long_6[0] = 1,
84 (long) long_6[1] = 2,
85 (long) long_6[2] = 3,
86 (long) long_6[3] = 4,
87 (long) long_6[4] = 5,
88 (long) long_6[5] = 6
89}
90
91.
92----------------------------------------------------------------------
93Ran 1 test in 0.349s
94
95OK
Johnny Chenbf6ffa32010-07-03 03:41:59 +000096$
97"""
98
Johnny Chen90312a82010-09-21 22:34:45 +000099import os, sys, traceback
Johnny Chenea88e942010-09-21 21:08:53 +0000100import re
Johnny Chen8952a2d2010-08-30 21:35:00 +0000101from subprocess import *
Johnny Chenf2b70232010-08-25 18:49:48 +0000102import time
Johnny Chena33a93c2010-08-30 23:08:52 +0000103import types
Johnny Chen73258832010-08-05 23:42:46 +0000104import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000105import lldb
106
Johnny Chen8d55a342010-08-31 17:42:54 +0000107if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
108 traceAlways = True
109else:
110 traceAlways = False
111
112
Johnny Chen00778092010-08-09 22:01:17 +0000113#
114# Some commonly used assert messages.
115#
116
Johnny Chenaa902922010-09-17 22:45:27 +0000117COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
118
Johnny Chen00778092010-08-09 22:01:17 +0000119CURRENT_EXECUTABLE_SET = "Current executable set successfully"
120
Johnny Chen7d1d7532010-09-02 21:23:12 +0000121PROCESS_IS_VALID = "Process is valid"
122
123PROCESS_KILLED = "Process is killed successfully"
124
Johnny Chen5ee88192010-08-27 23:47:36 +0000125RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000126
Johnny Chen17941842010-08-09 23:44:24 +0000127RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000128
Johnny Chen67af43f2010-10-05 19:27:32 +0000129BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
130
Johnny Chen17941842010-08-09 23:44:24 +0000131BREAKPOINT_CREATED = "Breakpoint created successfully"
132
Johnny Chene76896c2010-08-17 21:33:31 +0000133BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
134
Johnny Chen17941842010-08-09 23:44:24 +0000135BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000136
Johnny Chen703dbd02010-09-30 17:06:24 +0000137BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
138
Johnny Chenc70b02a2010-09-22 23:00:20 +0000139STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
140
Johnny Chen00778092010-08-09 22:01:17 +0000141STOPPED_DUE_TO_BREAKPOINT = "Process state is stopped due to breakpoint"
142
143STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
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 Chen5ee88192010-08-27 23:47:36 +0000149VALID_FILESPEC = "Got a valid filespec"
150
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000151VALID_PROCESS = "Got a valid process"
152
153VALID_TARGET = "Got a valid target"
154
Johnny Chen981463d2010-08-25 19:00:04 +0000155VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000156
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000157
Johnny Chen17941842010-08-09 23:44:24 +0000158#
159# And a generic "Command '%s' returns successfully" message generator.
160#
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000161def CMD_MSG(str, exe):
162 if exe:
163 return "Command '%s' returns successfully" % str
164 else:
165 return "'%s' compares successfully" % str
Johnny Chen17941842010-08-09 23:44:24 +0000166
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000167#
Johnny Chen27c41232010-08-26 21:49:29 +0000168# Returns an env variable array from the os.environ map object.
169#
170def EnvArray():
171 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
172
Johnny Chen8d55a342010-08-31 17:42:54 +0000173# From 2.7's subprocess.check_output() convenience function.
174def system(*popenargs, **kwargs):
175 r"""Run command with arguments and return its output as a byte string.
176
177 If the exit code was non-zero it raises a CalledProcessError. The
178 CalledProcessError object will have the return code in the returncode
179 attribute and output in the output attribute.
180
181 The arguments are the same as for the Popen constructor. Example:
182
183 >>> check_output(["ls", "-l", "/dev/null"])
184 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
185
186 The stdout argument is not allowed as it is used internally.
187 To capture standard error in the result, use stderr=STDOUT.
188
189 >>> check_output(["/bin/sh", "-c",
190 ... "ls -l non_existent_file ; exit 0"],
191 ... stderr=STDOUT)
192 'ls: non_existent_file: No such file or directory\n'
193 """
194 if 'stdout' in kwargs:
195 raise ValueError('stdout argument not allowed, it will be overridden.')
196 process = Popen(stdout=PIPE, *popenargs, **kwargs)
Johnny Chen1aad5c62010-09-14 22:01:40 +0000197 output, error = process.communicate()
Johnny Chen8d55a342010-08-31 17:42:54 +0000198 retcode = process.poll()
199
200 if traceAlways:
201 if isinstance(popenargs, types.StringTypes):
202 args = [popenargs]
203 else:
204 args = list(popenargs)
205 print >> sys.stderr
206 print >> sys.stderr, "os command:", args
Johnny Chene0490512010-09-14 22:39:02 +0000207 print >> sys.stderr, "stdout:", output
208 print >> sys.stderr, "stderr:", error
209 print >> sys.stderr, "retcode:", retcode
Johnny Chen1aad5c62010-09-14 22:01:40 +0000210 print >> sys.stderr
Johnny Chen8d55a342010-08-31 17:42:54 +0000211
212 if retcode:
213 cmd = kwargs.get("args")
214 if cmd is None:
215 cmd = popenargs[0]
Johnny Chen2fcc0e52010-09-16 18:26:06 +0000216 raise CalledProcessError(retcode, cmd)
Johnny Chen8d55a342010-08-31 17:42:54 +0000217 return output
218
Johnny Chen67af43f2010-10-05 19:27:32 +0000219def pointer_size():
220 """Return the pointer size of the host system."""
221 import ctypes
222 a_pointer = ctypes.c_void_p(0xffff)
223 return 8 * ctypes.sizeof(a_pointer)
224
Johnny Chen827edff2010-08-27 00:15:48 +0000225
Johnny Chen73258832010-08-05 23:42:46 +0000226class TestBase(unittest2.TestCase):
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000227 """This LLDB abstract base class is meant to be subclassed."""
228
Johnny Chenda884342010-10-01 22:59:49 +0000229 @classmethod
230 def skipLongRunningTest(cls):
231 """
232 By default, we skip long running test case.
233 This can be overridden by passing '-l' to the test driver (dotest.py).
234 """
235 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
236 return False
237 else:
238 return True
239
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000240 # The concrete subclass should override this attribute.
Johnny Chenf02ec122010-07-03 20:41:42 +0000241 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000242
Johnny Chen6ca006c2010-08-16 21:28:10 +0000243 # State pertaining to the inferior process, if any.
Johnny Chen57b47382010-09-02 22:25:47 +0000244 # This reflects inferior process started through the command interface with
245 # either the lldb "run" or "process launch" command.
246 # See also self.runCmd().
Johnny Chen6ca006c2010-08-16 21:28:10 +0000247 runStarted = False
248
Johnny Chenf2b70232010-08-25 18:49:48 +0000249 # Maximum allowed attempts when launching the inferior process.
250 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
251 maxLaunchCount = 3;
252
253 # Time to wait before the next launching attempt in second(s).
254 # Can be overridden by the LLDB_TIME_WAIT environment variable.
255 timeWait = 1.0;
256
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000257 # Keep track of the old current working directory.
258 oldcwd = None
Johnny Chena2124952010-08-05 21:23:45 +0000259
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000260 @classmethod
261 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000262 """
263 Python unittest framework class setup fixture.
264 Do current directory manipulation.
265 """
266
Johnny Chenf02ec122010-07-03 20:41:42 +0000267 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000268 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000269 raise Exception("Subclasses must override the 'mydir' attribute.")
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000270 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000271 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000272
273 # Change current working directory if ${LLDB_TEST} is defined.
274 # See also dotest.py which sets up ${LLDB_TEST}.
275 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000276 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000277 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000278 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
279
280 @classmethod
281 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000282 """
283 Python unittest framework class teardown fixture.
284 Do class-wide cleanup.
285 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000286
287 # First, let's do the platform-specific cleanup.
288 module = __import__(sys.platform)
289 if not module.cleanup():
290 raise Exception("Don't know how to do cleanup")
291
292 # Subclass might have specific cleanup function defined.
293 if getattr(cls, "classCleanup", None):
294 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000295 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
Johnny Chen90312a82010-09-21 22:34:45 +0000296 try:
297 cls.classCleanup()
298 except:
299 exc_type, exc_value, exc_tb = sys.exc_info()
300 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000301
302 # Restore old working directory.
303 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000304 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000305 os.chdir(cls.oldcwd)
306
307 def setUp(self):
308 #import traceback
309 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000310
Johnny Chen0ed37c92010-10-07 02:04:14 +0000311 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
312 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
313 time.sleep(0.5)
314
Johnny Chenf2b70232010-08-25 18:49:48 +0000315 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
316 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
317
318 if "LLDB_TIME_WAIT" in os.environ:
319 self.timeWait = float(os.environ["LLDB_TIME_WAIT"])
320
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000321 # Create the debugger instance if necessary.
322 try:
323 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000324 except AttributeError:
325 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +0000326
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000327 if not self.dbg.IsValid():
328 raise Exception('Invalid debugger instance')
329
330 # We want our debugger to be synchronous.
331 self.dbg.SetAsync(False)
332
Johnny Chen7d1d7532010-09-02 21:23:12 +0000333 # There is no process associated with the debugger as yet.
Johnny Chen57b47382010-09-02 22:25:47 +0000334 # See also self.tearDown() where it checks whether self.process has a
335 # valid reference and calls self.process.Kill() to kill the process.
Johnny Chen7d1d7532010-09-02 21:23:12 +0000336 self.process = None
337
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000338 # Retrieve the associated command interpreter instance.
339 self.ci = self.dbg.GetCommandInterpreter()
340 if not self.ci:
341 raise Exception('Could not get the command interpreter')
342
343 # And the result object.
344 self.res = lldb.SBCommandReturnObject()
345
Johnny Chenc70b02a2010-09-22 23:00:20 +0000346 # These are for customized teardown cleanup.
347 self.dict = None
348 self.doTearDownCleanup = False
349
350 def setTearDownCleanup(self, dictionary=None):
351 self.dict = dictionary
352 self.doTearDownCleanup = True
353
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000354 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +0000355 #import traceback
356 #traceback.print_stack()
357
358 # Terminate the current process being debugged, if any.
Johnny Chen6ca006c2010-08-16 21:28:10 +0000359 if self.runStarted:
Johnny Chen7d1d7532010-09-02 21:23:12 +0000360 self.runCmd("process kill", PROCESS_KILLED, check=False)
361 elif self.process and self.process.IsValid():
Johnny Chen0ed37c92010-10-07 02:04:14 +0000362 rc = self.invoke(self.process, "Kill")
Johnny Chen7d1d7532010-09-02 21:23:12 +0000363 self.assertTrue(rc.Success(), PROCESS_KILLED)
Johnny Chen0ed37c92010-10-07 02:04:14 +0000364 del self.process
Johnny Chen6ca006c2010-08-16 21:28:10 +0000365
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000366 del self.dbg
367
Johnny Chenc70b02a2010-09-22 23:00:20 +0000368 # Perform registered teardown cleanup.
369 if self.doTearDownCleanup:
370 module = __import__(sys.platform)
371 if not module.cleanup(dictionary=self.dict):
372 raise Exception("Don't know how to do cleanup")
373
Johnny Chen63dfb272010-09-01 00:15:19 +0000374 def runCmd(self, cmd, msg=None, check=True, trace=False, setCookie=True):
Johnny Chen27f212d2010-08-19 23:26:59 +0000375 """
376 Ask the command interpreter to handle the command and then check its
377 return status.
378 """
379 # Fail fast if 'cmd' is not meaningful.
380 if not cmd or len(cmd) == 0:
381 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +0000382
Johnny Chen8d55a342010-08-31 17:42:54 +0000383 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +0000384
Johnny Chen63dfb272010-09-01 00:15:19 +0000385 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +0000386
Johnny Chen63dfb272010-09-01 00:15:19 +0000387 for i in range(self.maxLaunchCount if running else 1):
Johnny Chenf2b70232010-08-25 18:49:48 +0000388 self.ci.HandleCommand(cmd, self.res)
Johnny Chen5bbb88f2010-08-20 17:57:32 +0000389
Johnny Chenf2b70232010-08-25 18:49:48 +0000390 if trace:
391 print >> sys.stderr, "runCmd:", cmd
392 if self.res.Succeeded():
393 print >> sys.stderr, "output:", self.res.GetOutput()
394 else:
395 print >> sys.stderr, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +0000396
Johnny Chen725945d2010-09-03 22:35:47 +0000397 if running:
398 # For process launch, wait some time before possible next try.
399 time.sleep(self.timeWait)
400
Johnny Chenff3d01d2010-08-20 21:03:09 +0000401 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +0000402 break
Johnny Chenf7f0cab2010-09-15 17:33:57 +0000403 elif running:
Johnny Chen9fa03212010-09-15 18:00:19 +0000404 print >> sys.stderr, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +0000405
Johnny Chen7d1d7532010-09-02 21:23:12 +0000406 # Modify runStarted only if "run" or "process launch" was encountered.
407 if running:
408 self.runStarted = running and setCookie
Johnny Chen63dfb272010-09-01 00:15:19 +0000409
Johnny Chen27f212d2010-08-19 23:26:59 +0000410 if check:
411 self.assertTrue(self.res.Succeeded(),
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000412 msg if msg else CMD_MSG(cmd, True))
Johnny Chen27f212d2010-08-19 23:26:59 +0000413
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000414 def expect(self, str, msg=None, patterns=None, startstr=None, substrs=None, trace=False, error=False, matching=True, exe=True):
Johnny Chen27f212d2010-08-19 23:26:59 +0000415 """
416 Similar to runCmd; with additional expect style output matching ability.
417
418 Ask the command interpreter to handle the command and then check its
419 return status. The 'msg' parameter specifies an informational assert
420 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +0000421 'startstr', matches the substrings contained in 'substrs', and regexp
422 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +0000423
424 If the keyword argument error is set to True, it signifies that the API
425 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +0000426 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +0000427 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +0000428
429 If the keyword argument matching is set to False, it signifies that the API
430 client is expecting the output of the command not to match the golden
431 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000432
433 Finally, the required argument 'str' represents the lldb command to be
434 sent to the command interpreter. In case the keyword argument 'exe' is
435 set to False, the 'str' is treated as a string to be matched/not-matched
436 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +0000437 """
Johnny Chen8d55a342010-08-31 17:42:54 +0000438 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +0000439
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000440 if exe:
441 # First run the command. If we are expecting error, set check=False.
442 self.runCmd(str, trace = (True if trace else False), check = not error)
Johnny Chen27f212d2010-08-19 23:26:59 +0000443
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000444 # Then compare the output against expected strings.
445 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +0000446
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000447 # If error is True, the API client expects the command to fail!
448 if error:
449 self.assertFalse(self.res.Succeeded(),
450 "Command '" + str + "' is expected to fail!")
451 else:
452 # No execution required, just compare str against the golden input.
453 output = str
454 if trace:
Johnny Chend64c3e72010-09-21 23:47:01 +0000455 print >> sys.stderr, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +0000456
Johnny Chenea88e942010-09-21 21:08:53 +0000457 # The heading says either "Expecting" or "Not expecting".
458 if trace:
459 heading = "Expecting" if matching else "Not expecting"
460
461 # Start from the startstr, if specified.
462 # If there's no startstr, set the initial state appropriately.
463 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +0000464
Johnny Chenc7c9fcf2010-08-24 23:48:10 +0000465 if startstr and trace:
Johnny Chenea88e942010-09-21 21:08:53 +0000466 print >> sys.stderr, "%s start string: %s" % (heading, startstr)
Johnny Chenc7c9fcf2010-08-24 23:48:10 +0000467 print >> sys.stderr, "Matched" if matched else "Not matched"
468 print >> sys.stderr
Johnny Chenb145bba2010-08-20 18:25:15 +0000469
Johnny Chenea88e942010-09-21 21:08:53 +0000470 # Look for sub strings, if specified.
471 keepgoing = matched if matching else not matched
472 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +0000473 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +0000474 matched = output.find(str) != -1
Johnny Chenc7c9fcf2010-08-24 23:48:10 +0000475 if trace:
Johnny Chenea88e942010-09-21 21:08:53 +0000476 print >> sys.stderr, "%s sub string: %s" % (heading, str)
Johnny Chenc7c9fcf2010-08-24 23:48:10 +0000477 print >> sys.stderr, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +0000478 keepgoing = matched if matching else not matched
479 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +0000480 break
Johnny Chenc7c9fcf2010-08-24 23:48:10 +0000481 if trace:
482 print >> sys.stderr
Johnny Chen27f212d2010-08-19 23:26:59 +0000483
Johnny Chenea88e942010-09-21 21:08:53 +0000484 # Search for regular expression patterns, if specified.
485 keepgoing = matched if matching else not matched
486 if patterns and keepgoing:
487 for pattern in patterns:
488 # Match Objects always have a boolean value of True.
489 matched = bool(re.search(pattern, output))
490 if trace:
491 print >> sys.stderr, "%s pattern: %s" % (heading, pattern)
492 print >> sys.stderr, "Matched" if matched else "Not matched"
493 keepgoing = matched if matching else not matched
494 if not keepgoing:
495 break
496 if trace:
497 print >> sys.stderr
498
499 self.assertTrue(matched if matching else not matched,
Johnny Chen9c48b8d2010-09-21 23:33:30 +0000500 msg if msg else CMD_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +0000501
Johnny Chenf3c59232010-08-25 22:52:45 +0000502 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +0000503 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +0000504 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +0000505
506 method = getattr(obj, name)
507 import inspect
508 self.assertTrue(inspect.ismethod(method),
509 name + "is a method name of object: " + str(obj))
510 result = method()
Johnny Chen8d55a342010-08-31 17:42:54 +0000511 if trace:
Johnny Chen703dbd02010-09-30 17:06:24 +0000512 print >> sys.stderr, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +0000513 return result
Johnny Chen827edff2010-08-27 00:15:48 +0000514
Johnny Chen13639082010-09-01 22:08:51 +0000515 def breakAfterLaunch(self, process, func, trace=False):
516 """
517 Perform some dancees after LaunchProcess() to break at func name.
518
519 Return True if we can successfully break at the func name in due time.
520 """
521 trace = (True if traceAlways else trace)
522
523 count = 0
524 while True:
525 # The stop reason of the thread should be breakpoint.
526 thread = process.GetThreadAtIndex(0)
527 SR = thread.GetStopReason()
528 if trace:
529 print >> sys.stderr, "StopReason =", StopReasonString(SR)
530
531 if SR == StopReasonEnum("Breakpoint"):
532 frame = thread.GetFrameAtIndex(0)
533 name = frame.GetFunction().GetName()
Johnny Chenea772bb2010-09-07 18:55:50 +0000534 if trace:
535 print >> sys.stderr, "function =", name
Johnny Chen13639082010-09-01 22:08:51 +0000536 if (name == func):
537 # We got what we want; now break out of the loop.
538 return True
539
540 # The inferior is in a transient state; continue the process.
541 time.sleep(1.0)
542 if trace:
543 print >> sys.stderr, "Continuing the process:", process
544 process.Continue()
545
546 count = count + 1
Johnny Chenae745562010-09-15 00:00:54 +0000547 if count == 15:
Johnny Chen13639082010-09-01 22:08:51 +0000548 if trace:
Johnny Chenae745562010-09-15 00:00:54 +0000549 print >> sys.stderr, "Reached 15 iterations, giving up..."
Johnny Chen13639082010-09-01 22:08:51 +0000550 # Enough iterations already, break out of the loop.
551 return False
552
553 # End of while loop.
554
555
Johnny Chenc70b02a2010-09-22 23:00:20 +0000556 def buildDefault(self, architecture=None, compiler=None, dictionary=None):
Johnny Chen1b1b9ac2010-09-03 23:49:16 +0000557 """Platform specific way to build the default binaries."""
558 module = __import__(sys.platform)
Johnny Chenc70b02a2010-09-22 23:00:20 +0000559 if not module.buildDefault(architecture, compiler, dictionary):
Johnny Chen1b1b9ac2010-09-03 23:49:16 +0000560 raise Exception("Don't know how to build default binary")
561
Johnny Chenc70b02a2010-09-22 23:00:20 +0000562 def buildDsym(self, architecture=None, compiler=None, dictionary=None):
Johnny Chen2f1ad5e2010-08-30 22:26:48 +0000563 """Platform specific way to build binaries with dsym info."""
Johnny Chen8d55a342010-08-31 17:42:54 +0000564 module = __import__(sys.platform)
Johnny Chenc70b02a2010-09-22 23:00:20 +0000565 if not module.buildDsym(architecture, compiler, dictionary):
Johnny Chen2f1ad5e2010-08-30 22:26:48 +0000566 raise Exception("Don't know how to build binary with dsym")
567
Johnny Chenc70b02a2010-09-22 23:00:20 +0000568 def buildDwarf(self, architecture=None, compiler=None, dictionary=None):
Johnny Chen2f1ad5e2010-08-30 22:26:48 +0000569 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen8d55a342010-08-31 17:42:54 +0000570 module = __import__(sys.platform)
Johnny Chenc70b02a2010-09-22 23:00:20 +0000571 if not module.buildDwarf(architecture, compiler, dictionary):
Johnny Chen2f1ad5e2010-08-30 22:26:48 +0000572 raise Exception("Don't know how to build binary with dwarf")
573
Johnny Chen827edff2010-08-27 00:15:48 +0000574 def DebugSBValue(self, frame, val):
Johnny Chen8d55a342010-08-31 17:42:54 +0000575 """Debug print a SBValue object, if traceAlways is True."""
576 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +0000577 return
578
579 err = sys.stderr
580 err.write(val.GetName() + ":\n")
581 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
582 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
583 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
584 err.write('\t' + "Value -> " + str(val.GetValue(frame)) + '\n')
585 err.write('\t' + "Summary -> " + str(val.GetSummary(frame)) + '\n')
586 err.write('\t' + "IsPtrType -> " + str(val.TypeIsPtrType()) + '\n')
587 err.write('\t' + "Location -> " + val.GetLocation(frame) + '\n')
588