-
Notifications
You must be signed in to change notification settings - Fork 12.3k
/
lldbtest.py
2694 lines (2231 loc) · 102 KB
/
lldbtest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
LLDB module which provides the abstract base class of lldb test case.
The concrete subclass can override lldbtest.TestBase in order to inherit the
common behavior for unitest.TestCase.setUp/tearDown implemented in this file.
./dotest.py provides a test driver which sets up the environment to run the
entire of part of the test suite . Example:
# Exercises the test suite in the types directory....
/Volumes/data/lldb/svn/ToT/test $ ./dotest.py -A x86_64 types
...
Session logs for test failures/errors/unexpected successes will go into directory '2012-05-16-13_35_42'
Command invoked: python ./dotest.py -A x86_64 types
compilers=['clang']
Configuration: arch=x86_64 compiler=clang
----------------------------------------------------------------------
Collected 72 tests
........................................................................
----------------------------------------------------------------------
Ran 72 tests in 135.468s
OK
$
"""
# System modules
import abc
from functools import wraps
import gc
import io
import json
import os.path
import re
import shutil
import signal
from subprocess import *
import sys
import time
import traceback
# Third-party modules
import unittest
# LLDB modules
import lldb
from . import configuration
from . import decorators
from . import lldbplatformutil
from . import lldbtest_config
from . import lldbutil
from . import test_categories
from lldbsuite.support import encoded_file
from lldbsuite.support import funcutils
from lldbsuite.support import seven
from lldbsuite.test_event import build_exception
# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
# LLDB_COMMAND_TRACE is set from '-t' option.
# By default, traceAlways is False.
if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"] == "YES":
traceAlways = True
else:
traceAlways = False
# By default, doCleanup is True.
if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"] == "NO":
doCleanup = False
else:
doCleanup = True
#
# Some commonly used assert messages.
#
COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
CURRENT_EXECUTABLE_SET = "Current executable set successfully"
PROCESS_IS_VALID = "Process is valid"
PROCESS_KILLED = "Process is killed successfully"
PROCESS_EXITED = "Process exited successfully"
PROCESS_STOPPED = "Process status should be stopped"
RUN_SUCCEEDED = "Process is launched successfully"
RUN_COMPLETED = "Process exited successfully"
BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
BREAKPOINT_CREATED = "Breakpoint created successfully"
BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit count = 1"
BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit count = 2"
BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit count = 3"
MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
STEP_IN_SUCCEEDED = "Thread step-in succeeded"
STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
STOPPED_DUE_TO_BREAKPOINT,
"instead, the actual stop reason is: '%s'",
)
STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
STOPPED_DUE_TO_BREAKPOINT_JITTED_CONDITION = (
"Stopped due to breakpoint jitted condition"
)
STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
VALID_BREAKPOINT = "Got a valid breakpoint"
VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
VALID_FILESPEC = "Got a valid filespec"
VALID_MODULE = "Got a valid module"
VALID_PROCESS = "Got a valid process"
VALID_SYMBOL = "Got a valid symbol"
VALID_TARGET = "Got a valid target"
VALID_PLATFORM = "Got a valid platform"
VALID_TYPE = "Got a valid type"
VALID_VARIABLE = "Got a valid variable"
VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
WATCHPOINT_CREATED = "Watchpoint created successfully"
def CMD_MSG(command):
"""A generic "Command '%s' did not return successfully" message generator."""
return f"Command '{command}' did not return successfully"
def COMPLETION_MSG(str_before, str_after, completions):
"""A generic assertion failed message generator for the completion mechanism."""
return "'%s' successfully completes to '%s', but completions were:\n%s" % (
str_before,
str_after,
"\n".join(completions),
)
def EXP_MSG(str, actual, exe):
"""A generic "'%s' returned unexpected result" message generator if exe.
Otherwise, it generates "'%s' does not match expected result" message."""
return "'%s' %s result, got '%s'" % (
str,
"returned unexpected" if exe else "does not match expected",
actual.strip(),
)
def SETTING_MSG(setting):
"""A generic "Value of setting '%s' is not correct" message generator."""
return "Value of setting '%s' is not correct" % setting
def line_number(filename, string_to_match):
"""Helper function to return the line number of the first matched string."""
with io.open(filename, mode="r", encoding="utf-8") as f:
for i, line in enumerate(f):
if line.find(string_to_match) != -1:
# Found our match.
return i + 1
raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
def get_line(filename, line_number):
"""Return the text of the line at the 1-based line number."""
with io.open(filename, mode="r", encoding="utf-8") as f:
return f.readlines()[line_number - 1]
def pointer_size():
"""Return the pointer size of the host system."""
import ctypes
a_pointer = ctypes.c_void_p(0xFFFF)
return 8 * ctypes.sizeof(a_pointer)
def is_exe(fpath):
"""Returns true if fpath is an executable."""
if fpath is None:
return False
if sys.platform == "win32":
if not fpath.endswith(".exe"):
fpath += ".exe"
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
def which(program):
"""Returns the full path to a program; None otherwise."""
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
class ValueCheck:
def __init__(
self,
name=None,
value=None,
type=None,
summary=None,
children=None,
dereference=None,
):
"""
:param name: The name that the SBValue should have. None if the summary
should not be checked.
:param summary: The summary that the SBValue should have. None if the
summary should not be checked.
:param value: The value that the SBValue should have. None if the value
should not be checked.
:param type: The type that the SBValue result should have. None if the
type should not be checked.
:param children: A list of ValueChecks that need to match the children
of this SBValue. None if children shouldn't be checked.
The order of checks is the order of the checks in the
list. The number of checks has to match the number of
children.
:param dereference: A ValueCheck for the SBValue returned by the
`Dereference` function.
"""
self.expect_name = name
self.expect_value = value
self.expect_type = type
self.expect_summary = summary
self.children = children
self.dereference = dereference
def check_value(self, test_base, val, error_msg=None):
"""
Checks that the given value matches the currently set properties
of this ValueCheck. If a match failed, the given TestBase will
be used to emit an error. A custom error message can be specified
that will be used to describe failed check for this SBValue (but
not errors in the child values).
"""
this_error_msg = error_msg if error_msg else ""
this_error_msg += "\nChecking SBValue: " + str(val)
test_base.assertSuccess(val.GetError())
# Python 3.6 doesn't declare a `re.Pattern` type, get the dynamic type.
pattern_type = type(re.compile(""))
if self.expect_name:
test_base.assertEqual(self.expect_name, val.GetName(), this_error_msg)
if self.expect_value:
if isinstance(self.expect_value, pattern_type):
test_base.assertRegex(val.GetValue(), self.expect_value, this_error_msg)
else:
test_base.assertEqual(self.expect_value, val.GetValue(), this_error_msg)
if self.expect_type:
test_base.assertEqual(
self.expect_type, val.GetDisplayTypeName(), this_error_msg
)
if self.expect_summary:
if isinstance(self.expect_summary, pattern_type):
test_base.assertRegex(
val.GetSummary(), self.expect_summary, this_error_msg
)
else:
test_base.assertEqual(
self.expect_summary, val.GetSummary(), this_error_msg
)
if self.children is not None:
self.check_value_children(test_base, val, error_msg)
if self.dereference is not None:
self.dereference.check_value(test_base, val.Dereference(), error_msg)
def check_value_children(self, test_base, val, error_msg=None):
"""
Checks that the children of a SBValue match a certain structure and
have certain properties.
:param test_base: The current test's TestBase object.
:param val: The SBValue to check.
"""
this_error_msg = error_msg if error_msg else ""
this_error_msg += "\nChecking SBValue: " + str(val)
test_base.assertEqual(len(self.children), val.GetNumChildren(), this_error_msg)
for i in range(0, val.GetNumChildren()):
expected_child = self.children[i]
actual_child = val.GetChildAtIndex(i)
child_error = "Checking child with index " + str(i) + ":\n" + error_msg
expected_child.check_value(test_base, actual_child, child_error)
class recording(io.StringIO):
"""
A nice little context manager for recording the debugger interactions into
our session object. If trace flag is ON, it also emits the interactions
into the stderr.
"""
def __init__(self, test, trace):
"""Create a io.StringIO instance; record the session obj and trace flag."""
io.StringIO.__init__(self)
# The test might not have undergone the 'setUp(self)' phase yet, so that
# the attribute 'session' might not even exist yet.
self.session = getattr(test, "session", None) if test else None
self.trace = trace
def __enter__(self):
"""
Context management protocol on entry to the body of the with statement.
Just return the io.StringIO object.
"""
return self
def __exit__(self, type, value, tb):
"""
Context management protocol on exit from the body of the with statement.
If trace is ON, it emits the recordings into stderr. Always add the
recordings to our session object. And close the io.StringIO object, too.
"""
if self.trace:
print(self.getvalue(), file=sys.stderr)
if self.session:
print(self.getvalue(), file=self.session)
self.close()
class _BaseProcess(object, metaclass=abc.ABCMeta):
@abc.abstractproperty
def pid(self):
"""Returns process PID if has been launched already."""
@abc.abstractmethod
def launch(self, executable, args, extra_env):
"""Launches new process with given executable and args."""
@abc.abstractmethod
def terminate(self):
"""Terminates previously launched process.."""
class _LocalProcess(_BaseProcess):
def __init__(self, trace_on):
self._proc = None
self._trace_on = trace_on
self._delayafterterminate = 0.1
@property
def pid(self):
return self._proc.pid
def launch(self, executable, args, extra_env):
env = None
if extra_env:
env = dict(os.environ)
env.update([kv.split("=", 1) for kv in extra_env])
self._proc = Popen(
[executable] + args,
stdout=DEVNULL if not self._trace_on else None,
stdin=PIPE,
env=env,
)
def terminate(self):
if self._proc.poll() is None:
# Terminate _proc like it does the pexpect
signals_to_try = [
sig for sig in ["SIGHUP", "SIGCONT", "SIGINT"] if sig in dir(signal)
]
for sig in signals_to_try:
try:
self._proc.send_signal(getattr(signal, sig))
time.sleep(self._delayafterterminate)
if self._proc.poll() is not None:
return
except ValueError:
pass # Windows says SIGINT is not a valid signal to send
self._proc.terminate()
time.sleep(self._delayafterterminate)
if self._proc.poll() is not None:
return
self._proc.kill()
time.sleep(self._delayafterterminate)
def poll(self):
return self._proc.poll()
def wait(self, timeout=None):
return self._proc.wait(timeout)
class _RemoteProcess(_BaseProcess):
def __init__(self, install_remote):
self._pid = None
self._install_remote = install_remote
@property
def pid(self):
return self._pid
def launch(self, executable, args, extra_env):
if self._install_remote:
src_path = executable
dst_path = lldbutil.join_remote_paths(
lldb.remote_platform.GetWorkingDirectory(), os.path.basename(executable)
)
dst_file_spec = lldb.SBFileSpec(dst_path, False)
err = lldb.remote_platform.Install(
lldb.SBFileSpec(src_path, True), dst_file_spec
)
if err.Fail():
raise Exception(
"remote_platform.Install('%s', '%s') failed: %s"
% (src_path, dst_path, err)
)
else:
dst_path = executable
dst_file_spec = lldb.SBFileSpec(executable, False)
launch_info = lldb.SBLaunchInfo(args)
launch_info.SetExecutableFile(dst_file_spec, True)
launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory())
# Redirect stdout and stderr to /dev/null
launch_info.AddSuppressFileAction(1, False, True)
launch_info.AddSuppressFileAction(2, False, True)
if extra_env:
launch_info.SetEnvironmentEntries(extra_env, True)
err = lldb.remote_platform.Launch(launch_info)
if err.Fail():
raise Exception(
"remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err)
)
self._pid = launch_info.GetProcessID()
def terminate(self):
lldb.remote_platform.Kill(self._pid)
def getsource_if_available(obj):
"""
Return the text of the source code for an object if available. Otherwise,
a print representation is returned.
"""
import inspect
try:
return inspect.getsource(obj)
except:
return repr(obj)
def builder_module():
return lldbplatformutil.builder_module()
class Base(unittest.TestCase):
"""
Abstract base for performing lldb (see TestBase) or other generic tests (see
BenchBase for one example). lldbtest.Base works with the test driver to
accomplish things.
"""
# The concrete subclass should override this attribute.
mydir = None
# Keep track of the old current working directory.
oldcwd = None
# Maximum allowed attempts when launching the inferior process.
# Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
maxLaunchCount = 1
# Time to wait before the next launching attempt in second(s).
# Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
timeWaitNextLaunch = 1.0
@staticmethod
def compute_mydir(test_file):
"""Subclasses should call this function to correctly calculate the
required "mydir" attribute as follows:
mydir = TestBase.compute_mydir(__file__)
"""
# /abs/path/to/packages/group/subdir/mytest.py -> group/subdir
lldb_test_src = configuration.test_src_root
if not test_file.startswith(lldb_test_src):
raise Exception(
"Test file '%s' must reside within lldb_test_src "
"(which is '%s')." % (test_file, lldb_test_src)
)
return os.path.dirname(os.path.relpath(test_file, start=lldb_test_src))
def TraceOn(self):
"""Returns True if we are in trace mode (tracing detailed test execution)."""
return traceAlways
def trace(self, *args, **kwargs):
with recording(self, self.TraceOn()) as sbuf:
print(*args, file=sbuf, **kwargs)
@classmethod
def setUpClass(cls):
"""
Python unittest framework class setup fixture.
Do current directory manipulation.
"""
# Fail fast if 'mydir' attribute is not overridden.
if not cls.mydir:
cls.mydir = Base.compute_mydir(sys.modules[cls.__module__].__file__)
if not cls.mydir:
raise Exception("Subclasses must override the 'mydir' attribute.")
# Save old working directory.
cls.oldcwd = os.getcwd()
full_dir = os.path.join(configuration.test_src_root, cls.mydir)
if traceAlways:
print("Change dir to:", full_dir, file=sys.stderr)
os.chdir(full_dir)
# Set platform context.
cls.platformContext = lldbplatformutil.createPlatformContext()
@classmethod
def tearDownClass(cls):
"""
Python unittest framework class teardown fixture.
Do class-wide cleanup.
"""
if doCleanup:
# First, let's do the platform-specific cleanup.
module = builder_module()
module.cleanup()
# Subclass might have specific cleanup function defined.
if getattr(cls, "classCleanup", None):
if traceAlways:
print(
"Call class-specific cleanup function for class:",
cls,
file=sys.stderr,
)
try:
cls.classCleanup()
except:
exc_type, exc_value, exc_tb = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_tb)
# Restore old working directory.
if traceAlways:
print("Restore dir to:", cls.oldcwd, file=sys.stderr)
os.chdir(cls.oldcwd)
def enableLogChannelsForCurrentTest(self):
if len(lldbtest_config.channels) == 0:
return
# if debug channels are specified in lldbtest_config.channels,
# create a new set of log files for every test
log_basename = self.getLogBasenameForCurrentTest()
# confirm that the file is writeable
host_log_path = "{}-host.log".format(log_basename)
open(host_log_path, "w").close()
self.log_files.append(host_log_path)
log_enable = "log enable -Tpn -f {} ".format(host_log_path)
for channel_with_categories in lldbtest_config.channels:
channel_then_categories = channel_with_categories.split(" ", 1)
channel = channel_then_categories[0]
if len(channel_then_categories) > 1:
categories = channel_then_categories[1]
else:
categories = "default"
if channel == "gdb-remote" and lldb.remote_platform is None:
# communicate gdb-remote categories to debugserver
os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories
self.ci.HandleCommand(log_enable + channel_with_categories, self.res)
if not self.res.Succeeded():
raise Exception(
"log enable failed (check LLDB_LOG_OPTION env variable)"
)
# Communicate log path name to debugserver & lldb-server
# For remote debugging, these variables need to be set when starting the platform
# instance.
if lldb.remote_platform is None:
server_log_path = "{}-server.log".format(log_basename)
open(server_log_path, "w").close()
self.log_files.append(server_log_path)
os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
# Communicate channels to lldb-server
os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
self.addTearDownHook(self.disableLogChannelsForCurrentTest)
def disableLogChannelsForCurrentTest(self):
# close all log files that we opened
for channel_and_categories in lldbtest_config.channels:
# channel format - <channel-name> [<category0> [<category1> ...]]
channel = channel_and_categories.split(" ", 1)[0]
self.ci.HandleCommand("log disable " + channel, self.res)
if not self.res.Succeeded():
raise Exception(
"log disable failed (check LLDB_LOG_OPTION env variable)"
)
# Retrieve the server log (if any) from the remote system. It is assumed the server log
# is writing to the "server.log" file in the current test directory. This can be
# achieved by setting LLDB_DEBUGSERVER_LOG_FILE="server.log" when starting remote
# platform.
if lldb.remote_platform:
server_log_path = self.getLogBasenameForCurrentTest() + "-server.log"
if lldb.remote_platform.Get(
lldb.SBFileSpec("server.log"), lldb.SBFileSpec(server_log_path)
).Success():
self.log_files.append(server_log_path)
def setPlatformWorkingDir(self):
if not lldb.remote_platform or not configuration.lldb_platform_working_dir:
return
components = self.mydir.split(os.path.sep) + [
str(self.test_number),
self.getBuildDirBasename(),
]
remote_test_dir = configuration.lldb_platform_working_dir
for c in components:
remote_test_dir = lldbutil.join_remote_paths(remote_test_dir, c)
error = lldb.remote_platform.MakeDirectory(
remote_test_dir, 448
) # 448 = 0o700
if error.Fail():
raise Exception(
"making remote directory '%s': %s" % (remote_test_dir, error)
)
lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
# This function removes all files from the current working directory while leaving
# the directories in place. The cleanup is required to reduce the disk space required
# by the test suite while leaving the directories untouched is neccessary because
# sub-directories might belong to an other test
def clean_working_directory():
# TODO: Make it working on Windows when we need it for remote debugging support
# TODO: Replace the heuristic to remove the files with a logic what collects the
# list of files we have to remove during test runs.
shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir)
lldb.remote_platform.Run(shell_cmd)
self.addTearDownHook(clean_working_directory)
def getSourceDir(self):
"""Return the full path to the current test."""
return os.path.join(configuration.test_src_root, self.mydir)
def getBuildDirBasename(self):
return self.__class__.__module__ + "." + self.testMethodName
def getBuildDir(self):
"""Return the full path to the current test."""
return os.path.join(
configuration.test_build_dir, self.mydir, self.getBuildDirBasename()
)
def makeBuildDir(self):
"""Create the test-specific working directory, deleting any previous
contents."""
bdir = self.getBuildDir()
if os.path.isdir(bdir):
shutil.rmtree(bdir)
lldbutil.mkdir_p(bdir)
def getBuildArtifact(self, name="a.out"):
"""Return absolute path to an artifact in the test's build directory."""
return os.path.join(self.getBuildDir(), name)
def getSourcePath(self, name):
"""Return absolute path to a file in the test's source directory."""
return os.path.join(self.getSourceDir(), name)
@classmethod
def setUpCommands(cls):
commands = [
# First of all, clear all settings to have clean state of global properties.
"settings clear -all",
# Disable Spotlight lookup. The testsuite creates
# different binaries with the same UUID, because they only
# differ in the debug info, which is not being hashed.
"settings set symbols.enable-external-lookup false",
# Inherit the TCC permissions from the inferior's parent.
"settings set target.inherit-tcc true",
# Based on https://discourse.llvm.org/t/running-lldb-in-a-container/76801/4
"settings set target.disable-aslr false",
# Kill rather than detach from the inferior if something goes wrong.
"settings set target.detach-on-error false",
# Disable fix-its by default so that incorrect expressions in tests don't
# pass just because Clang thinks it has a fix-it.
"settings set target.auto-apply-fixits false",
# Testsuite runs in parallel and the host can have also other load.
"settings set plugin.process.gdb-remote.packet-timeout 60",
'settings set symbols.clang-modules-cache-path "{}"'.format(
configuration.lldb_module_cache_dir
),
"settings set use-color false",
]
# Set any user-overridden settings.
for setting, value in configuration.settings:
commands.append("setting set %s %s" % (setting, value))
# Make sure that a sanitizer LLDB's environment doesn't get passed on.
if (
cls.platformContext
and cls.platformContext.shlib_environment_var in os.environ
):
commands.append(
"settings set target.env-vars {}=".format(
cls.platformContext.shlib_environment_var
)
)
# Set environment variables for the inferior.
if lldbtest_config.inferior_env:
commands.append(
"settings set target.env-vars {}".format(lldbtest_config.inferior_env)
)
return commands
def setUp(self):
"""Fixture for unittest test case setup.
It works with the test driver to conditionally skip tests and does other
initializations."""
# import traceback
# traceback.print_stack()
if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
if "LIBCXX_PATH" in os.environ:
self.libcxxPath = os.environ["LIBCXX_PATH"]
else:
self.libcxxPath = None
if "LLDBDAP_EXEC" in os.environ:
self.lldbDAPExec = os.environ["LLDBDAP_EXEC"]
else:
self.lldbDAPExec = None
self.lldbOption = " ".join("-o '" + s + "'" for s in self.setUpCommands())
# If we spawn an lldb process for test (via pexpect), do not load the
# init file unless told otherwise.
if os.environ.get("NO_LLDBINIT") != "NO":
self.lldbOption += " --no-lldbinit"
# Assign the test method name to self.testMethodName.
#
# For an example of the use of this attribute, look at test/types dir.
# There are a bunch of test cases under test/types and we don't want the
# module cacheing subsystem to be confused with executable name "a.out"
# used for all the test cases.
self.testMethodName = self._testMethodName
# This is for the case of directly spawning 'lldb'/'gdb' and interacting
# with it using pexpect.
self.child = None
self.child_prompt = "(lldb) "
# If the child is interacting with the embedded script interpreter,
# there are two exits required during tear down, first to quit the
# embedded script interpreter and second to quit the lldb command
# interpreter.
self.child_in_script_interpreter = False
# These are for customized teardown cleanup.
self.dict = None
self.doTearDownCleanup = False
# And in rare cases where there are multiple teardown cleanups.
self.dicts = []
self.doTearDownCleanups = False
# List of spawned subproces.Popen objects
self.subprocesses = []
# List of log files produced by the current test.
self.log_files = []
# Create the build directory.
# The logs are stored in the build directory, so we have to create it
# before creating the first log file.
self.makeBuildDir()
session_file = self.getLogBasenameForCurrentTest() + ".log"
self.log_files.append(session_file)
# Python 3 doesn't support unbuffered I/O in text mode. Open buffered.
self.session = encoded_file.open(session_file, "utf-8", mode="w")
# Optimistically set __errored__, __failed__, __expected__ to False
# initially. If the test errored/failed, the session info
# (self.session) is then dumped into a session specific file for
# diagnosis.
self.__cleanup_errored__ = False
self.__errored__ = False
self.__failed__ = False
self.__expected__ = False
# We are also interested in unexpected success.
self.__unexpected__ = False
# And skipped tests.
self.__skipped__ = False
# See addTearDownHook(self, hook) which allows the client to add a hook
# function to be run during tearDown() time.
self.hooks = []
# See HideStdout(self).
self.sys_stdout_hidden = False
if self.platformContext:
# set environment variable names for finding shared libraries
self.dylibPath = self.platformContext.shlib_environment_var
# Create the debugger instance.
self.dbg = lldb.SBDebugger.Create()
# Copy selected platform from a global instance if it exists.
if lldb.selected_platform is not None:
self.dbg.SetSelectedPlatform(lldb.selected_platform)
if not self.dbg:
raise Exception("Invalid debugger instance")
# Retrieve the associated command interpreter instance.
self.ci = self.dbg.GetCommandInterpreter()
if not self.ci:
raise Exception("Could not get the command interpreter")
# And the result object.
self.res = lldb.SBCommandReturnObject()
self.setPlatformWorkingDir()
self.enableLogChannelsForCurrentTest()
self.lib_lldb = None
self.framework_dir = None
self.darwinWithFramework = False
if sys.platform.startswith("darwin") and configuration.lldb_framework_path:
framework = configuration.lldb_framework_path
lib = os.path.join(framework, "LLDB")
if os.path.exists(lib):
self.framework_dir = os.path.dirname(framework)
self.lib_lldb = lib
self.darwinWithFramework = self.platformIsDarwin()
def setAsync(self, value):
"""Sets async mode to True/False and ensures it is reset after the testcase completes."""
old_async = self.dbg.GetAsync()
self.dbg.SetAsync(value)
self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
def cleanupSubprocesses(self):
# Terminate subprocesses in reverse order from how they were created.
for p in reversed(self.subprocesses):
p.terminate()
del p
del self.subprocesses[:]
def spawnSubprocess(self, executable, args=[], extra_env=None, install_remote=True):
"""Creates a subprocess.Popen object with the specified executable and arguments,
saves it in self.subprocesses, and returns the object.
"""
proc = (
_RemoteProcess(install_remote)
if lldb.remote_platform
else _LocalProcess(self.TraceOn())
)
proc.launch(executable, args, extra_env=extra_env)
self.subprocesses.append(proc)
return proc
def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
"""
Ask the command interpreter to handle the command and then check its
return status.
"""
# Fail fast if 'cmd' is not meaningful.
if cmd is None:
raise Exception("Bad 'cmd' parameter encountered")
trace = True if traceAlways else trace
if cmd.startswith("target create "):
cmd = cmd.replace("target create ", "file ")
running = cmd.startswith("run") or cmd.startswith("process launch")
for i in range(self.maxLaunchCount if running else 1):
with recording(self, trace) as sbuf:
print("runCmd:", cmd, file=sbuf)
if not check:
print("check of return status not required", file=sbuf)
self.ci.HandleCommand(cmd, self.res, inHistory)
with recording(self, trace) as sbuf:
if self.res.Succeeded():
print("output:", self.res.GetOutput(), file=sbuf)
else:
print("runCmd failed!", file=sbuf)
print(self.res.GetError(), file=sbuf)
if self.res.Succeeded():
break
elif running:
# For process launch, wait some time before possible next try.
time.sleep(self.timeWaitNextLaunch)
with recording(self, trace) as sbuf:
print("Command '" + cmd + "' failed!", file=sbuf)
if check:
if not msg:
msg = CMD_MSG(cmd)
output = ""
if self.res.GetOutput():
output += "\nCommand output:\n" + self.res.GetOutput()
if self.res.GetError():
output += "\nError output:\n" + self.res.GetError()
self.assertTrue(self.res.Succeeded(), msg + output)